-1

The screen pops up with the green rectangle but I can't move it. I don't understand why it won't work. any help would be highly appreciated!

import pygame
pygame.init()
width=1800
height=900
red=(255,0,0)
green=(0,255,0)
blue=(0,0,255)
white=(0,0,0)
black=(255,255,255)
x=800
y=150

running = True

def main():
    global running, screen, x, y

    screen = pygame.display.set_mode((width,height))
    pygame.draw.rect(screen, green,(x,y,100,300))
    pygame.display.update()
    while running:
        ev = pygame.event.get()
        for event in ev:
            if event.type==pygame.KEYDOWN:
                if event.type==pygame.K_RIGHT:
                    x+=20
                    pygame.display.update()
            if event.type==pygame.QUIT:
                pygame.quit()
                exit()
    pygame.display.update()
                
                
main()
Popyo
  • 1
  • 2
  • You have tp draw the object in the application not just before the application loop. See [Why is my PyGame application not running at all?](https://stackoverflow.com/questions/65264616/why-is-my-pygame-application-not-running-at-all/65264742#65264742) – Rabbid76 Jul 23 '22 at 10:19
  • You're checking for `pygame.K_RIGHT` in the wrong attribute - you already know what `event.type` is (it's `pygame.KEYDOWN`), the specific key is going to be something like `event.key`. – jasonharper Jul 25 '22 at 04:00

1 Answers1

0

You have to draw the object in the application not just before the application loop. See My program will run, but the K_RIGHT command will not work:

import pygame

pygame.init()

width, height = 1800, 900
x, y = 800, 150

def main():
    global running, screen, x, y

    screen = pygame.display.set_mode((width,height))
    clock = pygame.time.Clock()
    running = True

    while running:
        clock.tick(100)
        ev = pygame.event.get()
        for event in ev:
            if event.type==pygame.QUIT:
                running = False
            if event.type==pygame.KEYDOWN:
                if event.type==pygame.K_RIGHT:
                    x+=20
                
        screen.fill("black")
        pygame.draw.rect(screen, "green", (x,y,100,300))
        pygame.display.update()

    pygame.quit()
    exit()
                                
main()

The typical PyGame application loop has to:

Rabbid76
  • 202,892
  • 27
  • 131
  • 174