Untitled
unknown
plain_text
9 months ago
3.3 kB
14
Indexable
import pygame
import time
import random
# Initialize pygame
pygame.init()
# Window size
width = 600
height = 400
# Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (200, 0, 0)
green = (0, 255, 0)
# Set up display
window = pygame.display.set_mode((width, height))
pygame.display.set_caption("Simple Snake Game")
# Clock
clock = pygame.time.Clock()
snake_speed = 15
# Snake block size
block_size = 20
font = pygame.font.SysFont(None, 35)
def message(msg, color):
text = font.render(msg, True, color)
window.blit(text, [width / 6, height / 3])
def game_loop():
game_over = False
game_close = False
# Initial position
x = width / 2
y = height / 2
x_change = 0
y_change = 0
snake_list = []
snake_length = 1
# Food position
food_x = round(random.randrange(0, width - block_size) / 20.0) * 20.0
food_y = round(random.randrange(0, height - block_size) / 20.0) * 20.0
while not game_over:
while game_close:
window.fill(black)
message("Game Over! Press Q-Quit or C-Play Again", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -block_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = block_size
y_change = 0
elif event.key == pygame.K_UP:
y_change = -block_size
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = block_size
x_change = 0
x += x_change
y += y_change
# Check wall collision
if x >= width or x < 0 or y >= height or y < 0:
game_close = True
window.fill(black)
pygame.draw.rect(window, green, [food_x, food_y, block_size, block_size])
snake_head = []
snake_head.append(x)
snake_head.append(y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# Check self-collision
for segment in snake_list[:-1]:
if segment == snake_head:
game_close = True
for segment in snake_list:
pygame.draw.rect(window, white, [segment[0], segment[1], block_size, block_size])
pygame.display.update()
# Check if food eaten
if x == food_x and y == food_y:
food_x = round(random.randrange(0, width - block_size) / 20.0) * 20.0
food_y = round(random.randrange(0, height - block_size) / 20.0) * 20.0
snake_length += 1
clock.tick(snake_speed)
pygame.quit()
quit()
# Run the game
game_loop()Editor is loading...
Leave a Comment