Skip to content

Instantly share code, notes, and snippets.

@Frank-Buss
Created January 11, 2023 21:48
Show Gist options
  • Save Frank-Buss/f68f42a2c7091594f9f190aaa8f61aec to your computer and use it in GitHub Desktop.
Save Frank-Buss/f68f42a2c7091594f9f190aaa8f61aec to your computer and use it in GitHub Desktop.
PyGame sprite movement
# ChatGPT result of this question:
# write a Python script, where the user can move a sprite with cursor keys, using PyGame
import pygame
# Initialize PyGame
pygame.init()
# Set up the screen (width, height, caption)
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Sprite Movement")
# Loop until the user clicks the close button
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# Starting position of the sprite
x = 350
y = 250
# Speed and direction of sprite movement
x_speed = 0
y_speed = 0
# -------- Main Program Loop -----------
while not done:
# --- Main event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# User pressed a key
elif event.type == pygame.KEYDOWN:
# Figure out if it was an arrow key
if event.key == pygame.K_LEFT:
x_speed = -3
elif event.key == pygame.K_RIGHT:
x_speed = 3
elif event.key == pygame.K_UP:
y_speed = -3
elif event.key == pygame.K_DOWN:
y_speed = 3
# User let up on a key
elif event.type == pygame.KEYUP:
# If it is an arrow key, reset vector back to zero
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_speed = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_speed = 0
# --- Game logic should go here
# Move the sprite
x += x_speed
y += y_speed
# --- Drawing code should go here
screen.fill((255, 255, 255)) # Clear the screen
# Draw the sprite
pygame.draw.rect(screen, (0, 0, 0), [x, y, 50, 50])
# --- Go ahead and update the screen.
pygame.display.flip()
# --- Limit frames per second
clock.tick(60)
# Close the window and quit.
pygame.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment