0

I am using pygame in replit.com and whenever I run it, it doesn't show any errors but the left and down keys don't work. I don't understand what I did wrong.

Here's my code:

import pygame

pygame.init()

width, height = 800, 600
backgroundColor = 33, 33, 33
color = (0, 128, 255)
screen = pygame.display.set_mode((width, height))
player_x = 30
player_y = -30
while True:
  screen.fill(backgroundColor)
  for event in pygame.event.get():
    if(event.type == pygame.KEYDOWN):
      if(event.key == pygame.K_RIGHT):
        player_x += 10
  for event in pygame.event.get():
    if(event.type == pygame.KEYDOWN):
      if(event.key == pygame.K_LEFT):
        player_x -= 10
  for event in pygame.event.get():
    if(event.type == pygame.KEYDOWN):
      if(event.key == pygame.K_DOWN):
        player_y += 10
  pygame.draw.rect(screen, color, pygame.Rect(player_x, 30, 60, 60))
  pygame.display.update()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Nearday
  • 3
  • 2

1 Answers1

0

First thing, you have to modify the code in your while loop. There is no need for multiple for loops here, just check for the user input in only one for loop. Also at the second-from-last line in the while loop, you haven't considered the y-axis movement of the player, i.e. player_y.

Finally, just in the line above the while loop, set the y-coordinate of the player to 30 instead of -30 so that it appears completely on the screen.

player_y = 30
while True:
    screen.fill(backgroundColor)
    for event in pygame.event.get():
        if(event.type == pygame.KEYDOWN):
            if(event.key == pygame.K_RIGHT):
                player_x += 10

            if(event.key == pygame.K_LEFT):
                player_x -= 10

            if(event.key == pygame.K_DOWN):
                player_y += 10

    pygame.draw.rect(screen, color, (player_x, player_y, 50, 50))
    pygame.display.update()
Geeky Quentin
  • 2,469
  • 2
  • 7
  • 28
  • Also one more thing, I have to press the keys like multiple times. How do I fix that? – Nearday Jul 06 '22 at 02:05
  • You can open a new question for this one, as you cannot ask any questions or comment answers in comments – Geeky Quentin Jul 06 '22 at 02:13
  • Try something like [`pygame.key.set_repeat(500, 50)`](https://www.pygame.org/docs/ref/key.html#pygame.key.set_repeat). In this example after half a second, key press events will be repeated every fifty milliseconds. – import random Jul 06 '22 at 04:09