Untitled
unknown
plain_text
2 years ago
2.3 kB
3
Indexable
import pygame
# Initialize pygame
pygame.init()
# Create the screen
screen = pygame.display.set_mode((800, 600))
# Set the background color
pygame.display.set_caption("Snake Game")
# Create the snake
snake = [(0, 0), (0, 1), (0, 2)]
# Create the food
food = (100, 100)
# Set the direction of the snake
direction = "up"
# Create a clock to keep track of time
clock = pygame.time.Clock()
# Start the game loop
while True:
# Check for events
for event in pygame.event.get():
# If the user quits, quit the game
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# If the user presses a key, change the direction of the snake
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
if direction != "down":
direction = "up"
elif event.key == pygame.K_DOWN:
if direction != "up":
direction = "down"
elif event.key == pygame.K_LEFT:
if direction != "right":
direction = "left"
elif event.key == pygame.K_RIGHT:
if direction != "left":
direction = "right"
# Move the snake
head = snake[0]
if direction == "up":
head = (head[0], head[1] - 1)
elif direction == "down":
head = (head[0], head[1] + 1)
elif direction == "left":
head = (head[0] - 1, head[1])
elif direction == "right":
head = (head[0] + 1, head[1])
# Check if the snake hit the food
if head == food:
# Grow the snake
snake.append(head)
# Create new food
food = (
int(random.randint(0, 800 - 10) / 10) * 10,
int(random.randint(0, 600 - 10) / 10) * 10,
)
# Check if the snake hit itself
for body in snake[1:]:
if head == body:
# Game over
break
# Clear the screen
screen.fill((0, 0, 0))
# Draw the snake
for body in snake:
pygame.draw.rect(screen, (255, 0, 0), body)
# Draw the food
pygame.draw.rect(screen, (0, 255, 0), food)
# Update the display
pygame.display.update()
# Slow down the game
clock.tick(20)
Editor is loading...