I am building a game but I can't move left. Help. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

I am building a game but I can't move left. Help.

I am building a game using python with pygame. I spent a lot of time looking through the code but can't find the error. when I run the code the block moves right but not left!!! Can someone please tell me what I did wrong? Here is the code: import pygame import sys pygame.init() WIDTH = 800 HEIGHT = 600 RED = (255, 0, 0) 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, RED, (player_pos[0], player_pos[1], player_size, player_size)) pygame.display. update()

22nd May 2021, 8:54 AM
Monisha
11 Answers
+ 3
Monisha , could you please provide the originally code in playground and link it here. thanks
23rd May 2021, 6:23 PM
Lothar
Lothar - avatar
+ 3
Monisha , there may be a misunderstanding, so please take your code that causes the error, put it in playground and link it here. use copy paste, do not retype it. thanks!
24th May 2021, 10:57 AM
Lothar
Lothar - avatar
+ 2
I do not experience in pygame but I see in your last two if statements you change the size and not position. Better should be: if event.key == pygame.K_LEFT: x -= player_pos etc.
22nd May 2021, 8:59 AM
JaScript
JaScript - avatar
22nd May 2021, 10:30 AM
JaScript
JaScript - avatar
+ 2
22nd May 2021, 3:35 PM
JaScript
JaScript - avatar
+ 2
Ok i see, that all should be only if statements such as follows. 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
22nd May 2021, 7:08 PM
JaScript
JaScript - avatar
+ 2
Monisha please provide your code in playground and link it here in this way as I my code. Otherwise a really help is imposible. https://code.sololearn.com/c48by8KMm4E4/?ref=app
24th May 2021, 9:15 AM
JaScript
JaScript - avatar
+ 1
I tried that, but it just shows an error
22nd May 2021, 9:05 AM
Monisha
+ 1
I still can't figure it out. when I put a # in front of the elif statement the left key movement works but when I take the # of the left part it won't work but the right one does. IDK what to do
22nd May 2021, 11:16 AM
Monisha
+ 1
I am sorry, I forgot to inform you. I have solved the error. I had hit an extra tab by accident. Thanks for the help though :)
30th May 2021, 6:03 AM
Monisha
0
I am not sure how but I was following a tutorial. here is the link: https://youtu.be/-8n91btt5d8
24th May 2021, 7:23 AM
Monisha