import pygame import random pygame.init() # Constants WIDTH, HEIGHT = 800, 600 TILE_SIZE = 10 FPS = 60 # Colors WHITE = (255, 255, 255) RED = (255, 0, 0) BLACK = (0,0,0) class Snake: def __init__(self): self.length = 1 self.positions = [((WIDTH // 2), (HEIGHT // 2))] self.direction = random.choice([UP, DOWN, LEFT, RIGHT]) self.color = (0, 255, 0) self.score = 0 self.start_time = pygame.time.get_ticks() def get_head_position(self): return self.positions[0] def turn(self, point): if self.length > 1 and (point[0] * -1, point[1] * -1) == self.direction: return else: self.direction = point def move(self): cur = self.get_head_position() x, y = self.direction new = (((cur[0] + (x * TILE_SIZE)) % WIDTH), (cur[1] + (y * TILE_SIZE)) % HEIGHT) if len(self.positions) > 2 and new in self.positions[2:]: self.reset() else: self.positions.insert(0, new) if len(self.positions) > self.length: self.positions.pop() def reset(self): self.length = 1 self.positions = [((WIDTH // 2), (HEIGHT // 2))] self.direction = random.choice([UP, DOWN, LEFT, RIGHT]) self.score = 0 self.start_time = pygame.time.get_ticks() class Food: def __init__(self): self.position = (0, 0) self.color = (255, 0, 0) self.randomize_position() def randomize_position(self): self.position = (random.randint(0, (WIDTH // TILE_SIZE) - 1) * TILE_SIZE, random.randint(0, (HEIGHT // TILE_SIZE) - 1) * TILE_SIZE) UP = (0, -1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0) def draw_objects(snake, food, surface): surface.fill(BLACK) for pos in snake.positions: pygame.draw.rect(surface, snake.color, pygame.Rect(pos[0], pos[1], TILE_SIZE, TILE_SIZE)) pygame.draw.rect(surface, food.color, pygame.Rect(food.position[0], food.position[1], TILE_SIZE, TILE_SIZE)) def main(): snake = Snake() food = Food() clock = pygame.time.Clock() screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) pygame.display.set_caption('Snake Game') while True: 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: snake.turn(UP) elif event.key == pygame.K_DOWN: snake.turn(DOWN) elif event.key == pygame.K_LEFT: snake.turn(LEFT) elif event.key == pygame.K_RIGHT: snake.turn(RIGHT) snake.move() if snake.get_head_position() == food.position: snake.length += 1 snake.score += 1 food.randomize_position() draw_objects(snake, food, screen) # Calculate and display elapsed time elapsed_time = (pygame.time.get_ticks() - snake.start_time) / 1000 # Convert to seconds font = pygame.font.SysFont(None, 24) text = font.render(f"Time: {elapsed_time:.2f} sec", True, WHITE) screen.blit(text, (10, 10)) pygame.display.update() clock.tick(FPS) if __name__ == "__main__": main()