Search code examples
pythonpygamepong

Rect not moving in Pygame


I am trying to make a pong game in pygame. So I needed to make a rectangle controlled by player. I defined some variables for this purpose.

The variables

player = pygame.Rect(s_width - 10, s_height/2 - 35, 5, 70)
player_speed = 0

In the loop

player.y += player_speed

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
    if event.type == pygame.KEYDOWN:
        if pygame.key == pygame.K_DOWN:
            player_speed += 5
        if pygame.key == pygame.K_UP:
            player_speed -= 5
    if event.type == pygame.KEYUP:
        if pygame.key == pygame.K_DOWN:
            player_speed = 0
        if pygame.key == pygame.K_UP:
            player_speed = 0

Solution

  • There is just one problem in your code; you don't check

    if pygame.key == pygame.K_...
    

    You need to replace the pygame.key to event.key:

    if event.key == pygame.K_...
    
    import pygame
    pygame.init()
    
    s_width, s_height = 600, 600
    wn = pygame.display.set_mode((s_width, s_height))
    
    player = pygame.Rect(s_width - 10, s_height/2 - 35, 5, 70)
    player_speed = 0
    
    clock = pygame.time.Clock()
    
    while True:
        clock.tick(60)
        player.y += player_speed
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_DOWN:
                    player_speed += 5
                    print(player_speed)
                if event.key == pygame.K_UP:
                    player_speed -= 5
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_DOWN:
                    player_speed = 0
                if event.key == pygame.K_UP:
                    player_speed = 0
        wn.fill((0, 0, 0))
        pygame.draw.rect(wn, (255, 0, 0), player)
        pygame.display.update()
    

    Output:

    enter image description here