I tried making a movement system for my game, why wont the square move?

Question:

I was working on a pygame and thought I should start a movement system, why wont is work, I worked hours and It wont work, if you have a fix, please tell me. Also the game I’m making is a collect game so please help. Also tell me what I did wrong besides a while loop not being there.
I need help, and stackoverflow is making me type so much lol.

import pygame
import time

pygame.init()

WINDOW = pygame.display.set_mode((640, 480))

BACKGROUND = (255, 255, 255)



def show():
    x = 0
    y = 0

    WINDOW.fill(BACKGROUND)




    RED = (255, 30, 70)

    box = pygame.Rect(x, y, 100, 120)

    pygame.draw.rect(WINDOW, RED, box)

    key = pygame.key.get_pressed()

    a = 2

    if key[pygame.K_UP]:
        a = a + 1
        y = y + 1


if key[pygame.K_DOWN]:
    a = a - 1
    y = y - 1


if a == 2:

    print("0")
    print("1")
    print("0")

if a == 3:
    print("1")
    print("0")
    print("0")

if a == 1:
    print("0")
    print("0")
    print("1")
pygame.display.update()

x = 0
y = 0

show()
time.sleep(1)
show()
time.sleep(1)
show()
time.sleep(1)
show()
time.sleep(1)
show()
time.sleep(1)
show()
time.sleep(1)
show()
time.sleep(1)
show()
Asked By: crosby lawyer

||

Answers:

Im not sure what your code tries to do. If you are just looking for rect movement, here is a rudimentary example.

import pygame
pygame.init()

win = pygame.display.set_mode((500,500))
pygame.display.set_caption("First Game")

x = 50
y = 50
width = 40
height = 60
vel = 5

run = True

while run:
    pygame.time.delay(100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    
    if keys[pygame.K_LEFT]:
        x -= vel

    if keys[pygame.K_RIGHT]:
        x += vel

    if keys[pygame.K_UP]:
        y -= vel

    if keys[pygame.K_DOWN]:
        y += vel
    
    win.fill((0,0,0))  # Fills the screen with black
    pygame.draw.rect(win, (255,0,0), (x, y, width, height))   
    pygame.display.update() 
    
pygame.quit()

For more info on rect management you can use: https://www.pygame.org/docs/ref/rect.html
For more info on keyboard input you can use: https://www.pygame.org/docs/ref/key.html

Answered By: BOOTRE
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.