Untitled
unknown
plain_text
3 years ago
2.8 kB
8
Indexable
import pygame
import random
# Initialize pygame
pygame.init()
# Set up the game window
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Snake Game")
# Define colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# Set up the game clock
clock = pygame.time.Clock()
# Set up the font
font = pygame.font.SysFont(None, 30)
# Define the snake class
class Snake:
def __init__(self, x, y):
self.x = x
self.y = y
self.dx = 10
self.dy = 0
self.body = [(x, y)]
def move(self):
self.x += self.dx
self.y += self.dy
self.body.insert(0, (self.x, self.y))
self.body.pop()
def grow(self):
self.body.insert(0, (self.x, self.y))
def draw(self):
for x, y in self.body:
pygame.draw.rect(window, green, (x, y, 10, 10))
# Define the coin class
class Coin:
def __init__(self):
self.x = random.randint(0, window_width - 10)
self.y = random.randint(0, window_height - 10)
def draw(self):
pygame.draw.rect(window, blue, (self.x, self.y, 10, 10))
# Initialize the snake and the coin
snake = Snake(window_width / 2, window_height / 2)
coin = Coin()
# Set up the game loop
game_over = False
score = 0
while not game_over:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake.dx = -10
snake.dy = 0
elif event.key == pygame.K_RIGHT:
snake.dx = 10
snake.dy = 0
elif event.key == pygame.K_UP:
snake.dx = 0
snake.dy = -10
elif event.key == pygame.K_DOWN:
snake.dx = 0
snake.dy = 10
# Move the snake
snake.move()
# Check for collision with the coin
if snake.x == coin.x and snake.y == coin.y:
snake.grow()
coin = Coin()
score += 1
# Check for collision with the walls
if snake.x < 0 or snake.x > window_width - 10 or snake.y < 0 or snake.y > window_height - 10:
game_over = True
# Check for collision with the body
for x, y in snake.body[1:]:
if snake.x == x and snake.y == y:
game_over = True
# Clear the screen
window.fill(black)
# Draw the snake and the coin
snake.draw()
coin.draw()
# Draw the score
score_text = font.render("Score: " + str(score), True, white)
window.blit(score_text, (10, 10))
# Update the display
pygame.display.update
Editor is loading...