I have experienced a problem while writing a PyGame project. The project is a spaceship game to be exact.
What I have done is set up the game screen, import two spaceships (one red, the other yellow), set up some functions and conditions. Everything is fine and going as expected, except that I cannot move the red spaceship for some reason although I have already determined the keywords and conditions for moving it. Here’s what I have written in my code for reference:
import pygame
import os
GAME_WIDTH = 900
GAME_HEIGHT = 600
MID_WIDTH = GAME_WIDTH // 2
RED_X = 200
RED_Y = 200
YELLOW_X = 700
YELLOW_Y = 200
SPACESHIP_SIZE = (40, 40)
SPACESHIP_SPEED = 5
FPS = 60
GAME_TITLE = "Space Game For Dummies"
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
pygame.init()
window_screen = pygame.display.set_mode((GAME_WIDTH, GAME_HEIGHT))
pygame.display.set_caption(GAME_TITLE)
redSpaceshipOG = pygame.image.load(os.path.join("Pictures", "spaceship_red.png"))
yellowSpaceshipOG = pygame.image.load(os.path.join("Pictures", "spaceship_yellow.png"))
redSpaceship = pygame.transform.rotate(pygame.transform.scale(redSpaceshipOG, SPACESHIP_SIZE), 90)
yellowSpaceship = pygame.transform.rotate(pygame.transform.scale(yellowSpaceshipOG, SPACESHIP_SIZE), 270)
def drawWindow(window_screen, redSpaceship, yellowSpaceship, red_X, red_Y, yellow_X, yellow_Y):
window_screen.fill(BLACK)
window_screen.blit(redSpaceship, (red_X, red_Y))
window_screen.blit(yellowSpaceship, (yellow_X, yellow_Y))
pygame.draw.line(window_screen, WHITE, (MID_WIDTH, 0), (MID_WIDTH, GAME_HEIGHT), 10)
pygame.display.update()
def Movement(red_X, red_Y):
keys_pressed = pygame.key.get_pressed()
if (keys_pressed[pygame.K_w]) and (red_Y> 0):
red_Y -= SPACESHIP_SPEED
elif (keys_pressed[pygame.K_s]) and (red_Y < GAME_HEIGHT - redSpaceship.get_height()):
red_Y += SPACESHIP_SPEED
elif (keys_pressed[pygame.K_a]) and (red_X > 0):
red_X -= SPACESHIP_SPEED
elif (keys_pressed[pygame.K_d]) and (red_X < GAME_WIDTH - redSpaceship.get_width()):
red_X += SPACESHIP_SPEED
def main():
playing = True
while playing:
drawWindow(window_screen, redSpaceship, yellowSpaceship, RED_X, RED_Y, YELLOW_X, YELLOW_Y)
Movement(RED_X, RED_Y)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
pygame.quit()
if __name__ == "__main__":
main()