G

snake

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