G

snake

public
Guest Oct 29, 2024 Never 6
Clone
1
import pygame
2
import sys
3
import random
4
5
# Game constants
6
WIDTH, HEIGHT = 800, 600
7
BLOCK_SIZE = 20
8
SPEED = 5
9
WHITE = (255, 255, 255)
10
RED = (255, 0, 0)
11
GREEN = (0, 255, 0)
12
BLACK = (0, 0, 0)
13
# Initialize Pygame
14
pygame.init()
15
# Set up the display
16
screen = pygame.display.set_mode((WIDTH, HEIGHT))
17
pygame.display.set_caption("Snake Game")
18
class Snake:
19
def __init__(self):
20
self.x = WIDTH // 2
21
self.y = HEIGHT // 2
22
self.length = 1
23
self.direction = "right"
24
self.body = [(self.x, self.y)]
25
def move(self):
26
if self.direction == "right":
27
self.x += BLOCK_SIZE
28
elif self.direction == "left":
29
self.x -= BLOCK_SIZE
30
elif self.direction == "up":
31
self.y -= BLOCK_SIZE
32
elif self.direction == "down":
33
self.y += BLOCK_SIZE
34
self.body.append((self.x, self.y))
35
if len(self.body) > self.length:
36
self.body.pop(0)
37
def draw(self):
38
for pos in self.body:
39
pygame.draw.rect(screen, GREEN, (pos[0], pos[1], BLOCK_SIZE, BLOCK_SIZE))
40
class Food:
41
def __init__(self):
42
self.x = random.randint(0, WIDTH - BLOCK_SIZE) // BLOCK_SIZE * BLOCK_SIZE
43
self.y = random.randint(0, HEIGHT - BLOCK_SIZE) // BLOCK_SIZE * BLOCK_SIZE
44
def draw(self):
45
pygame.draw.rect(screen, RED, (self.x, self.y, BLOCK_SIZE, BLOCK_SIZE))
46
def main():
47
clock = pygame.time.Clock()
48
snake = Snake()
49
food = Food()
50
game_over = False
51
last_time = pygame.time.get_ticks()
52
while not game_over:
53
try:
54
for event in pygame.event.get():
55
if event.type == pygame.QUIT:
56
pygame.quit()
57
sys.exit()
58
elif event.type == pygame.KEYDOWN:
59
if event.key == pygame.K_UP and snake.direction!= "down":
60
snake.direction = "up"
61
elif event.key == pygame.K_DOWN and snake.direction!= "up":
62
snake.direction = "down"
63
elif event.key == pygame.K_LEFT and snake.direction!= "right":
64
snake.direction = "left"
65
elif event.key == pygame.K_RIGHT and snake.direction!= "left":
66
snake.direction = "right"
67
current_time = pygame.time.get_ticks()
68
if current_time - last_time >= 1000 // SPEED:
69
print("Moving snake...")
70
snake.move()
71
if (snake.x, snake.y) in snake.body[:-1]:
72
print("Game over: snake collided with itself")
73
game_over = True
74
if (snake.x, snake.y) == (food.x, food.y):
75
print("Snake ate food!")
76
snake.length += 1
77
food = Food()
78
last_time = current_time
79
screen.fill(BLACK)
80
snake.draw()
81
food.draw()
82
pygame.display.update()
83
except Exception as e:
84
print(f"Error: {e}")
85
game_over = True
86
print("Game Over")
87
pygame.quit()
88
sys.exit()
89
if __name__ == "__main__":
90
main()