My problem is that whenever I use a letter for a keystroke it does not work. The code worked when I changed the keystrokes to arrow keys but didn't work if I tried to use WASD. I have tried replacing the variables and many other things but it still does not work.
Here is my code that works:
import pygame
import os
pygame.init()
width = 1200
height = 800
FPS = 60
# Player 1
playerImg1 = pygame.image.load('spaceship1.png')
playerX1 = 200
playerY1 = 370
playerX_change1 = 0
playerY_change1 = 0
def player1(x1, y1):
window.blit(playerImg1, (x1, y1))
# Player 2
playerImg2 = pygame.image.load('spaceship2.png')
playerX2 = 800
playerY2 = 370
playerX_change2 = 0
playerY_change2 = 0
def player2(x2, y2):
window.blit(playerImg2, (x2, y2))
# gameLoop
running = True
clock = pygame.time.Clock()
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Keystrokes
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT: #left
playerX_change1 = -5
if event.key == pygame.K_RIGHT: #right
playerX_change1 = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or event.key == pygame.K_RIGHT:
playerX_change1 = 0
playerX1 += playerX_change1
if playerX1 <= 0:
playerX1 = 0
elif playerX1 >= 400:
playerX1 = 400
window.blit(bg,(0,0))
player1(playerX1, playerY1)
player2(playerX2, playerY2)
pygame.display.update()
Here is the code that doesn't work:
import pygame
import os
pygame.init()
width = 1200
height = 800
FPS = 60
# Creating and naming the screen
window = pygame.display.set_mode((width, height))
name = pygame.display.set_caption("Duel")
# Player 1
playerImg1 = pygame.image.load('spaceship1.png')
playerX1 = 200
playerY1 = 370
playerX_change1 = 0
playerY_change1 = 0
def player1(x1, y1):
window.blit(playerImg1, (x1, y1))
# Player 2
playerImg2 = pygame.image.load('spaceship2.png')
playerX2 = 800
playerY2 = 370
playerX_change2 = 0
playerY_change2 = 0
def player2(x2, y2):
window.blit(playerImg2, (x2, y2))
# gameLoop
running = True
clock = pygame.time.Clock()
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Keystrokes
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a: #left
playerX_change1 = -5
if event.key == pygame.K_d: #right
playerX_change1 = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
playerX_change1 = 0
playerX1 += playerX_change1
if playerX1 <= 0:
playerX1 = 0
elif playerX1 >= 400:
playerX1 = 400
window.blit(bg,(0,0))
player1(playerX1, playerY1)
player2(playerX2, playerY2)
pygame.display.update()
```