Untitled
unknown
plain_text
10 months ago
2.6 kB
3
Indexable
```
import pygame
import random
import math
Window size
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
Snake properties
SNAKE_SIZE = 10
SNAKE_SPEED = 10
3D projection properties
FOV = math.pi / 3
VIEW_DISTANCE = 10
class SnakeGame:
def __init__(self):
pygame.init()
self.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("3D Snake Game")
self.clock = pygame.time.Clock()
self.snake = [(200, 200), (220, 200), (240, 200)]
self.direction = (1, 0)
self.apple = self.generate_apple()
def generate_apple(self):
return (random.randint(0, WINDOW_WIDTH - SNAKE_SIZE) // SNAKE_SIZE * SNAKE_SIZE,
random.randint(0, WINDOW_HEIGHT - SNAKE_SIZE) // SNAKE_SIZE * SNAKE_SIZE)
def project_3d(self, x, y):
# Simple perspective projection
factor = FOV / (FOV + y)
return x * factor, y * factor
def draw_snake(self):
for x, y in self.snake:
x, y = self.project_3d(x, y)
pygame.draw.rect(self.window, GREEN, (x, y, SNAKE_SIZE, SNAKE_SIZE))
def draw_apple(self):
x, y = self.apple
x, y = self.project_3d(x, y)
pygame.draw.rect(self.window, RED, (x, y, SNAKE_SIZE, SNAKE_SIZE))
def update_snake(self):
new_head = (self.snake[-1][0] + self.direction[0] * SNAKE_SIZE,
self.snake[-1][1] + self.direction[1] * SNAKE_SIZE)
self.snake.append(new_head)
if self.snake[-1] == self.apple:
self.apple = self.generate_apple()
else:
self.snake.pop(0)
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.direction = (0, -1)
elif event.key == pygame.K_DOWN:
self.direction = (0, 1)
elif event.key == pygame.K_LEFT:
self.direction = (-1, 0)
elif event.key == pygame.K_RIGHT:
self.direction = (1, 0)
def run(self):
while True:
self.handle_events()
self.update_snake()
self.window.fill(BLACK)
self.draw_snake()
self.draw_apple()
pygame.display.update()
self.clock.tick(SNAKE_SPEED)
if __name__ == "__main__":
game = SnakeGame()
game.run()
```
Editor is loading...
Leave a Comment