Search code examples
pythonpygamereplit

How to move a rectangle in pygame


I'm trying to make a moving rectangle in Pygame. I understand that I first need to use pygame.draw.rect(), in which I have. I am using an online IDE temporarily, Repl.it. I just need to make sure that this code is correct.

import pygame, sys
pygame.init()
screen = pygame.display.set_mode((1000,600))
x = 500
y = 300
white = (255,255,255)
player = pygame.draw.rect(screen, white, (x,y,50,40))

while True:
  for event in pygame.event.get():
    if pygame.event == pygame.QUIT:
      pygame.QUIT
      sys.exit()
    if pygame.event == pygame.KEYDOWN:
      if pygame.key == pygame.K_LEFT:
        x -= 5
      if pygame.event == pygame.K_RIGHT:
        x += 5
  pygame.display.update()

Thank you for your inputs.


Solution

  • Your code is close to working.

    There's a few places you're checking the wrong part of the event, mostly you have the same mistake in multiple places.

    Also you're not re-drawing the rectangle when the co-ordinates change.

    import pygame, sys
    pygame.init()
    screen = pygame.display.set_mode((1000,600))
    x = 500
    y = 300
    black = (  0,  0,  0)
    white = (255,255,255)
    
    while True:
        # Handle Events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:            # <<-- HERE use event.type
                pygame.quit()                        # <<-- HERE use pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:       # <<-- HERE use event.type
                if event.key == pygame.K_LEFT:       # <<-- HERE use event.key
                    x -= 5
                elif event.key == pygame.K_RIGHT:    # <<-- HERE use event.key
                    x += 5
    
        # Reapint the screen
        screen.fill( black )                                     # erase old rectangle
        player = pygame.draw.rect(screen, white, (x,y,50,40))    # draw new rectangle
        pygame.display.update()