TransWikia.com

Can someone please tell me where am I wrong in this python code?

Stack Overflow Asked by Saksh on December 30, 2021

Here’s a simple pygame code where I inserted a screen, a pink rectangle and tried moving it.
The rectangle in the pygame window isn’t moving.
Which means the code inside ‘**’ isn’t working.
How do I solve that?

import pygame, sys

pygame.init()

width = 800
height = 600

pink = (244,133,227)

player_pos = [400, 300]
player_size = 50

screen = pygame.display.set_mode((width,height))

game_over = False

while not game_over:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            sys.exit()

**      if event.type == pygame.KEYDOWN:
            x = player_pos[0]
            y = player_pos[1]
            if event.type == pygame.K_LEFT:
                x -= player_size
            elif event.type == pygame.K_RIGHT:
                x += player_size
            player_pos = [x, y]
    screen.fill((0,0,0))  **

    pygame.draw.rect(screen, pink, (player_pos[0], player_pos[1], player_size, player_size))

    pygame.display.update()

One Answer

The key is stored in the key attribute, rather then the type attribute. See pygame.event:

if event.type== pygame.K_LEFT:

if event.key == pygame.K_LEFT:

See the example:

import pygame, sys

pygame.init()

width = 800
height = 600
pink = (244,133,227)
player_pos = [400, 300]
player_size = 50
screen = pygame.display.set_mode((width,height))

game_over = False
while not game_over:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            sys.exit()

        if event.type == pygame.KEYDOWN:
            x = player_pos[0]
            y = player_pos[1]
            if event.key == pygame.K_LEFT:
                x -= player_size
            elif event.key == pygame.K_RIGHT:
                x += player_size
            player_pos = [x, y]

    screen.fill((0,0,0))  
    pygame.draw.rect(screen, pink, (player_pos[0], player_pos[1], player_size, player_size))
    pygame.display.update()

Answered by Rabbid76 on December 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP