1

im trying to understand the basics of pygame by moving a rectangle using the d-pad on my keyboard but the rectangle isnt moving its staying in its initial position

import pygame
import sys

x1=0
y1=0
x2=100
y2=100

pygame.init()
screen=pygame.display.set_mode((288,512))
clock=pygame.time.Clock()
x = pygame.draw.rect(screen, (0, 255, 0), (0, 0, x2, y2))

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_DOWN:
               y1-=100



pygame.display.update()
clock.tick(120)

1 Answers1

1

You have to draw redraw the entire scene in every frame. This means you have to clear the display, draw the rectangle and update the display in every frame.
Furthermore you to draw the rectangle at the location (x1, y1). When you use pygame.draw.rect the you have to specify the top left position and the width and height of the rectangle:

import pygame
import sys

x1, y1, w1, h1 = 0, 0, 100, 100

pygame.init()
screen=pygame.display.set_mode((288,512))
clock=pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_DOWN:
               y1 += 10

    screen.fill(0)
    x = pygame.draw.rect(screen, (0, 255, 0), (x1, y1, w1, h1))
    pygame.display.update()
    clock.tick(120)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174