pygame having trouble with wasd keybinding - python

trying to do a dumb little begginer game and i wanted to have two players, one using arrow keys and one using wasd, arrows are working with no issue but i have no idea how to do wasd, i apologize in advance im a begginer in python and my names are in portuguese so before i send the code let me just help out in saying that im using "jogador1" and "jogador2" to mean "player1" and "player2"
here's the full code
# jogo plataformer 1
import pygame
# começar o programa
pygame.init()
# ecrã
ecrã = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Trump attack")
backgroundImg = pygame.image.load("weirdbackground.png")
def background():
ecrã.blit(backgroundImg, (0, 0))
funcionar = True
# loop do jogo
# jogador1
jogadorImg =pygame.image.load("biden1.png")
jogadorX = 282
jogadorY = 58
jogadorX_mudar = 0
jogadorY_mudar = 0
# jogador2
jogador2Img = pygame.image.load("trump1.png")
jogador2X = 436
jogador2Y = 58
jogador2Y_mudar = 0
jogador2X_mudar = 0
# bala do jogador 1
balaImg = pygame.image.load("trump2.png")
balaX = jogadorX
balaY = int(jogadorY - 5)
balaY_mudar = 0
balaX_mudar = 0
bala_estado = "pronto"
def disparar(x, y):
global bala_estado
bala_estado = "fire"
ecrã.blit(balaImg, (balaX, balaY))
def jogador2(x, y):
ecrã.blit(jogador2Img, (x, y))
def jogador(x, y):
ecrã.blit(jogadorImg, (x, y))
while funcionar:
for event in pygame.event.get():
if event.type == pygame.QUIT:
funcionar = False
# keybinds jogador 1
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
jogadorX_mudar = -1
if event.key == pygame.K_RIGHT:
jogadorX_mudar = 1
if event.key == pygame.K_UP:
jogadorY_mudar =-1
if event.key == pygame.K_DOWN:
jogadorY_mudar = 1
if event.key == pygame.K_SPACE:
disparar(balaX, balaY)
print("hello")
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
jogadorX_mudar = 0
if jogadorY < -30:
jogadorY_mudar += 1
if jogadorY == float(231.0):
jogadorY_mudar *= 0
jogadorY -= 1
#keybinds jogador 2
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
jogador2X_mudar = -1
if event.key == pygame.K_d:
jogador2X_mudar = 1
if event.key == pygame.K_w:
jogador2Y_mudar =-1
if event.key == pygame.K_s:
jogador2Y_mudar = 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
jogador2X_mudar = 0
if jogador2Y < -30:
jogador2Y_mudar += 1
if jogador2Y == float(231.0):
jogador2Y_mudar *= 0
jogador2Y -= 1
# bloco de cima jogador1
if (jogadorY <=200 and jogadorY >= 45) and (jogadorX >= 227 and jogadorX <= 448):
jogadorY_mudar *= 0
if (jogadorY <= 45) and (jogadorX >= 448 or jogadorX <= 227):
jogadorY_mudar += 1
# bloco de cima jogador2
if (jogador2Y <=200 and jogador2Y >= 45) and (jogador2X >= 227 and jogador2X <= 448):
jogador2Y_mudar *= 0
if (jogador2Y <= 45) and (jogador2X >= 448 or jogador2X <= 227):
jogador2Y_mudar += 1
if bala_estado == "fire":
disparar(balaX, balaY)
balaY += 1
background()
jogadorX += jogadorX_mudar
jogadorY += jogadorY_mudar
jogador2Y += jogador2Y_mudar
jogador2X += jogador2X_mudar
jogador2(jogador2X, jogador2Y)
jogador(jogadorX, jogadorY)
pygame.display.update()
```

It is a matter of Indentation. The events must be handled in the event loop, instead of after the event loop:
while funcionar:
for event in pygame.event.get():
if event.type == pygame.QUIT:
funcionar = False
# INDENTQTION
#-->|
# keybinds jogador 1
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
jogadorX_mudar = -1
if event.key == pygame.K_RIGHT:
jogadorX_mudar = 1
if event.key == pygame.K_UP:
jogadorY_mudar =-1
if event.key == pygame.K_DOWN:
jogadorY_mudar = 1
if event.key == pygame.K_SPACE:
disparar(balaX, balaY)
print("hello")
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
jogadorX_mudar = 0
#[...]

Related

Python pygame's keyboard move command does not operate

I'm currently trying to build a game through vscode using pygame lib.
My code to move character around with keyboard arrow keys won't apply to my module.
My module won't close even though I click exit button or esc.
Any thoughts why its not working?
import pygame
import os
pygame.init()
screen_width = 480
screen_height = 640
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("June's Game")
background = pygame.image.load("D:/Python/pygame_basic/background.png")
character = pygame.image.load("D:/Python/pygame_basic/character.png")
character_size = character.get_rect().size
character_width = character_size[0]
character_height = character_size[1]
character_x_position = (screen_width / 2) - (character_width / 2)
character_y_position = screen_height - character_height
to_x = 0
to_y = 0
running = True #게임이 진행중인가
while running:
for event in pygame.event.get():
if event == pygame.QUIT:
running = False
if event == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
to_x -= 5
elif event.key == pygame.K_RIGHT:
to_x += 5
elif event.key == pygame.K_UP:
to_y -= 5
elif event.key == pygame.K_DOWN:
to_y += 5
if event == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
to_x = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
to_y = 0
character_x_position += to_x
character_y_position += to_y
#screen.fill((0,0,255))
screen.blit(background, (0,0))
screen.blit(character, (character_x_position,character_y_position))
pygame.display.update()
pygame.quit()
i coudln't get it to work
event is an object. You have to get the type of the event, e.g.:
if event == pygame.KEYDOWN
if event.type == pygame.KEYDOWN:
You have to limit the frames per second to limit CPU usage with pygame.time.Clock.tick and to control the speed of the game. Otherwise, the player moves much too fast and immediately disappears from the screen. The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time.
clock = pygame.time.Clock()
running = True
while running:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
to_x -= 5
elif event.key == pygame.K_RIGHT:
to_x += 5
elif event.key == pygame.K_UP:
to_y -= 5
elif event.key == pygame.K_DOWN:
to_y += 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
to_x = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
to_y = 0
character_x_position += to_x
character_y_position += to_y
#screen.fill((0,0,255))
screen.blit(background, (0,0))
screen.blit(character, (character_x_position,character_y_position))
pygame.display.update()
However, there is a better method to move an object when a key is held down (See How can I make a sprite move when key is held down):
to_x = 0
to_y = 0
speed = 5
clock = pygame.time.Clock()
running = True
while running:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
to_x = (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed
to_y = (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * speed
character_x_position += to_x
character_y_position += to_y
screen.blit(background, (0,0))
screen.blit(character, (character_x_position,character_y_position))
pygame.display.update()

why is my square (snake) only moving diagonally?

I am coding 2 snakes/cars and my first snake/car, which use the WASD keyboard format, works perfectly.
But my second snake/car, which uses the arrow keys, is only moving diagonally.
I want both snakes/cars to move in every direction (up, down, left, right, AND diagonally) but right now, the second snake/car only moves diagonally.
#initialize variables for player 1
car1x = 250
car1y = 300
car1width = 20
car1height = 20
car1dx = 0
car1dy = 0
speed = 3
#initialize variables for player 2
car2x = 500
car2y = 300
car2width = 20
car2height = 20
car2dx = 0
car2dy = 0
speed = 3
screen.fill(WHITE)
# set main loop to True so it will run
main = True
# main loop
while main:
for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
if event.type ==pygame.QUIT: # check to see if it was "x" at top right of screen
main = False # set the "main" variable to False to exit while loop
if event.type ==pygame.KEYDOWN:
if event.key == pygame.K_w:
car1dx = 0
car1dy = -speed
elif event.key == pygame.K_s:
car1dx = 0
car1dy = speed
elif event.key == pygame.K_a:
car1dx = -speed
car1dy = 0
elif event.key == pygame.K_d:
car1dx = speed
car1dy = 0
if event.key == pygame.K_UP:
car2dx = 0
car2dy = -speed
elif event.key == pygame.K_DOWN:
car2dx = 0
car2dy = speed
elif event.key == pygame.K_LEFT:
car2dx = -speed
car2dy = 0
elif event.key == pygame.K_RIGHT:
car2dx = speed
car2dy = 0
elif event.key == pygame.K_q:
pygame.quit()
if event.type == pygame.KEYUP:
if event.key in (pygame.K_w, pygame.K_s):
car1dx = 0
elif event.key in (pygame.K_a, pygame.K_d):
car1dy = 0
if event.key in (pygame.K_UP, pygame.K_DOWN):
car1dx = 0
elif event.key in (pygame.K_LEFT, pygame.K_RIGHT):
car1dy = 0
# move the x and y positions of the player
oldcar1x = car1x
oldcar1y = car1y
oldcar2x = car2x
oldcar2y = car2y
car1x = car1x + car1dx
car1y = car1y + car1dy
car2x = car2x + car2dx
car2y = car2y + car2dx
if car1x >= screenwidth:
car1x = oldcar1x
car1y = oldcar1y
if car2x >= screenwidth:
car2x = oldcar2x
car2y = oldcar2y
```
In your final if statement it looks like the KEYUP events that are supposed to reset the dx/dy of Car2 are setting the dx/dy values for Car1 instead. This may be the source of your bug.
This line has a typo:
car2y = car2y + car2dx
It should be:
car2y = car2y + car2dy
Note the last character is corrected to be y not x.
Though would be clearer to use the += operator and write it as:
car2y += car2dy
You also have other errors in this section:
if event.type == pygame.KEYUP:
if event.key in (pygame.K_w, pygame.K_s):
car1dx = 0
elif event.key in (pygame.K_a, pygame.K_d):
car1dy = 0
if event.key in (pygame.K_UP, pygame.K_DOWN):
car1dx = 0
elif event.key in (pygame.K_LEFT, pygame.K_RIGHT):
car1dy = 0
You are resetting the wrong variables. You are resetting the dy instead of the dx and vise versa, and in the arrow key section you forgot to change it to car2. Like this:
if event.type == pygame.KEYUP:
if event.key in (pygame.K_w, pygame.K_s):
car1dy = 0
elif event.key in (pygame.K_a, pygame.K_d):
car1dx = 0
elif event.key in (pygame.K_UP, pygame.K_DOWN):
car2dy = 0
elif event.key in (pygame.K_LEFT, pygame.K_RIGHT):
car2dx = 0
Note: in the above I also changed the second if to an elif. This will not affect the correctness of the code, it just avoids an unnecessary if check in the case where it already matched above.
I think it's because that the key up detection is an if/elif and if/elif unlike the key down. Or maybe it's because that you didn't specify the key up detection for the 2nd car. I dunno, just a suggestion. I can't comment.
I can comment now! yay
There is a mistake here:
if event.type == pygame.KEYUP:
if event.key in (pygame.K_w, pygame.K_s):
car1dx = 0
elif event.key in (pygame.K_a, pygame.K_d):
car1dy = 0
if event.key in (pygame.K_UP, pygame.K_DOWN):
car1dx = 0
elif event.key in (pygame.K_LEFT, pygame.K_RIGHT):
car1dy = 0
You are using car1dx and car1dy where it should be car2dx and car2dy:
if event.type == pygame.KEYUP:
if event.key in (pygame.K_w, pygame.K_s):
car1dx = 0
elif event.key in (pygame.K_a, pygame.K_d):
car1dy = 0
if event.key in (pygame.K_UP, pygame.K_DOWN):
car2dx = 0
elif event.key in (pygame.K_LEFT, pygame.K_RIGHT):
car2dy = 0
Since the arrow keys are for car 2
You should also change the line:
car2y = car2y + car2dx
This should change into:
car2y += car2dy

trying to make a sprite jump

**When ever i press up arrow the sprite jumps but when it comes down it carrys on going down. Here is my code. it does not do this with left and rght keys.
x = (display_width * 0.1)
y = (display_height * 0.75)
x_change = 0
y_change = 0
over = False
while over == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change -= 5
if event.key == pygame.K_RIGHT:
x_change += 5
if event.key == pygame.K_UP:
y_change = -30
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_change = 0
if event.key == pygame.K_RIGHT:
x_change = 0
if event.key == pygame.K_UP:
y_change = 30
x += x_change
y += y_change
The problem is caused by the y_change remaining at 30 during later processing.
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_change = 0
if event.key == pygame.K_RIGHT:
x_change = 0
if event.key == pygame.K_UP:
y_change = 30 # <=== HERE
So when the event fires, the y_change becomes 30 - so the position moves back down. But on the next loop, y_change is still 30, so it keeps moving down, again and again.

python/pygame test specific key to be up

So i'm trying to make a topdown game and i'm having problems with player movement. When i press key [W,A,S or D] player moves that way. But i want it to keep moving as long as button is being held down. So i change [playerMoveLeft, playerMoveRight, playerMoveDown or playerMoveUp] to 1
if allowMovement == 1:
if event.key == pygame.K_a:
playerMoveLeft = 1
print("Hello")
if event.key == pygame.K_d:
playerMoveRight = 1
if event.key == pygame.K_s:
playerMoveDown = 1
if event.key == pygame.K_w:
playerMoveUp = 1
if event.key == pygame.K_LSHIFT:
playerMoveSprint = 1
playerSpeed = 2
So as long as one of playerMoves are 1 player should keep moving.
Know the problem:
When i release the key it sets all playerMoves to 0 what causes the player to stop so i'm trying to find a way to only testfor 1 specific key to be lifted up and that would set thath specific playerMove to 0.
if event.type == pygame.KEYUP:
playerMoveLeft = 0
playerMoveRight = 0
playerMoveUp = 0
playerMoveDown = 0
playerMoveSprint = 0
Below this text there is the Full code area for player movement
for event in pygame.event.get():
if event.type == pygame.QUIT:
valmis = True
if event.type == pygame.KEYDOWN:
############################## CONTROL PLAYER ############################
if allowMovement == 1:
if event.key == pygame.K_a:
playerMoveLeft = 1
print("Hello")
if event.key == pygame.K_d:
playerMoveRight = 1
if event.key == pygame.K_s:
playerMoveDown = 1
if event.key == pygame.K_w:
playerMoveUp = 1
if event.key == pygame.K_LSHIFT:
playerMoveSprint = 1
playerSpeed = 2
if event.type == pygame.KEYUP:
playerMoveLeft = 0
playerMoveRight = 0
playerMoveUp = 0
playerMoveDown = 0
playerMoveSprint = 0
if playerMoveSprint == 1:
playerSpeed = 1
if playerMoveLeft == 1:
player_x -=(playerSpeed)
if playerMoveRight == 1:
player_x +=(playerSpeed)
if playerMoveUp == 1:
player_y -=(playerSpeed)
if playerMoveDown == 1:
player_y +=(playerSpeed)
thanks for every one who helps!
Assuming your player can only go in one direction (up/down/left/right) at a time:
STANDSTILL = 0
UP = 1
RIGHT = 2
DOWN = 3
LEFT = 4
playermovement = STANDSTILL
if event.type == pygame.KEYDOWN:
if allowMovement == 1:
if event.key == pygame.K_a:
playermovement = LEFT
if event.key == pygame.K_d:
playermovement = RIGHT
if event.key == pygame.K_s:
playermovement = DOWN
if event.key == pygame.K_w:
playermovement = UP
if event.key == pygame.K_LSHIFT:
playerMoveSprint = 1
playerSpeed = 2
if event.type == pygame.KEYUP:
if allowMovement == 1:
if event.key == pygame.K_a or event.key == pygame.K_d or event.key == pygame.K_s or event.key == pygame.K_w:
playermovement = STANDSTILL
if event.key == pygame.K_LSHIFT:
playerSpeed = 0
Assuming your player can move in two directions at the same time (up/down and left/right):
if event.type == pygame.KEYDOWN:
if allowMovement == 1:
if event.key == pygame.K_a:
playerMoveLeft = 1
playerMoveRight = 0
if event.key == pygame.K_d:
playerMoveRight = 1
playerMoveLeft = 0
if event.key == pygame.K_s:
playerMoveDown = 1
playerMoveUp = 0
if event.key == pygame.K_w:
playerMoveUp = 1
playerMoveDown = 0
if event.key == pygame.K_LSHIFT:
playerMoveSprint = 1
playerSpeed = 2
if event.type == pygame.KEYUP:
if allowMovement == 1:
if event.key == pygame.K_a:
playerMoveLeft = 0
if event.key == pygame.K_d:
playerMoveRight = 0
if event.key == pygame.K_s:
playerMoveDown = 0
if event.key == pygame.K_w:
playerMoveUp = 0
if event.key == pygame.K_LSHIFT:
playerSpeed = 0
It makes no sense to allow the player figure to move left and right at the same time, so set the opposite direction to zero whenever the player presses the button in one of these directions (same for up/down).

My sprite keeps moving off of the screen in pygame

so I've been messing around with sprites and movement in pygame and the issue I keep running into with my code is that when you hold down the key the sprite won't stop moving, but if it is past the point at which it is supposed to stop and you let go and try again it will do what it is meant to and not move, is there any way I can have it happen straight away so it won't keep disappearing from my screen?
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
if player.x + 4 < 700:
moveX = 4
else:
moveX = 0
if event.key == pygame.K_LEFT:
if player.x == 0:
moveX = 0
else:
moveX = -4
if event.key == pygame.K_UP:
moveY = -4
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
moveX = 0
if event.key == pygame.K_LEFT:
moveX = 0
if event.key == pygame.K_UP:
moveY = 0
player.falling = True
player.collision = False
player.onground = False
Something seems not right with the indentation.
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
if player.x + 4 < 700:
moveX = 4 # <----- should this be here ?
else: # <----- this should match the `event.key == pygame.K_RIGHT` condition
moveX = 0
if event.key == pygame.K_LEFT:
if player.x == 0:
moveX = 0
else:
moveX = -4
if event.key == pygame.K_UP:
moveY = -4
Can you please redo the indentation and check?
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
if player.x + 4 < 700: moveX = 4
else: moveX = 0
if event.key == pygame.K_LEFT:
if player.x == 0: moveX = 0 # here you might want to try player.x <= 0 ...
else: moveX = -4
...
may be easier to handle ...

Categories