deepseek-r1-0528· DeepSeek LMArena Human Preference 140K
напиши змейку
- User
напиши змейку
- Assistant
Вот код игры "Змейка" на Python с использованием библиотеки Pygame. Этот вариант включает плавное управление, подсчет очков и визуальные улучшения:
import pygame import sys import random import time # Инициализация Pygame pygame.init() # Константы WIDTH, HEIGHT = 600, 600 GRID_SIZE = 20 GRID_WIDTH = WIDTH // GRID_SIZE GRID_HEIGHT = HEIGHT // GRID_SIZE FPS = 10 # Цвета BACKGROUND = (15, 15, 30) GRID_COLOR = (30, 30, 50) SNAKE_COLOR = (50, 205, 50) SNAKE_HEAD_COLOR = (0, 255, 0) FOOD_COLOR = (220, 60, 60) TEXT_COLOR = (200, 200, 255) SCORE_BG = (30, 30, 60, 180) # Направления UP = (0, -1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0) # Создание окна screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Змейка") clock = pygame.time.Clock() font = pygame.font.SysFont('Arial', 25) big_font = pygame.font.SysFont('Arial', 50) class Snake: def __init__(self): self.reset() def reset(self): self.length = 3 self.positions = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)] self.direction = random.choice([UP, DOWN, LEFT, RIGHT]) self.score = 0 self.grow_to = 3 self.last_move_time = time.time() self.speed = FPS def get_head_position(self): return self.positions[0] def update_direction(self, direction): # Запрет поворота на 180 градусов if (direction[0] * -1, direction[1] * -1) != self.direction: self.direction = direction def move(self): current = self.get_head_position() x, y = self.direction new = ((current[0] + x) % GRID_WIDTH, (current[1] + y) % GRID_HEIGHT) # Проверка столкновения с хвостом if new in self.positions[1:]: return False self.positions.insert(0, new) # Управление ростом змейки if len(self.positions) > self.grow_to: self.positions.pop() return True def grow(self): self.grow_to += 1 self.score += 10 # Постепенное увеличение скорости if self.score % 50 == 0: self.speed += 0.5 def draw(self, surface): for i, pos in enumerate(self.positions): color = SNAKE_HEAD_COLOR if i == 0 else SNAKE_COLOR rect = pygame.Rect(pos[0] * GRID_SIZE, pos[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE) pygame.draw.rect(surface, color, rect) pygame.draw.rect(surface, (30, 100, 30), rect, 1) # Рисуем глаза для головы if i == 0: eye_size = GRID_SIZE // 5 # Определяем направление для позиционирования глаз if self.direction == RIGHT: pygame.draw.circle(surface, (0, 0, 0), (rect.right - 5, rect.top + 6), eye_size) pygame.draw.circle(surface, (0, 0, 0), (rect.right - 5, rect.bottom - 6), eye_size) elif self.direction == LEFT: pygame.draw.circle(surface, (0, 0, 0), (rect.left + 5, rect.top + 6), eye_size) pygame.draw.circle(surface, (0, 0, 0), (rect.left + 5, rect.bottom - 6), eye_size) elif self.direction == UP: pygame.draw.circle(surface, (0, 0, 0), (rect.left + 6, rect.top + 5), eye_size) pygame.draw.circle(surface, (0, 0, 0), (rect.right - 6, rect.top + 5), eye_size) elif self.direction == DOWN: pygame.draw.circle(surface, (0, 0, 0), (rect.left + 6, rect.bottom - 5), eye_size) pygame.draw.circle(surface, (0, 0, 0), (rect.right - 6, rect.bottom - 5), eye_size) class Food: def __init__(self): self.position = (0, 0) self.randomize_position() def randomize_position(self): self.position = (random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1)) def draw(self, surface): rect = pygame.Rect(self.position[0] * GRID_SIZE, self.position[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE) pygame.draw.rect(surface, FOOD_COLOR, rect) pygame.draw.rect(surface, (180, 40, 40), rect, 1) # Создаем эффект яблока pygame.draw.rect(surface, (150, 30, 30), (rect.centerx - 2, rect.top + 2, 4, 5)) def draw_grid(surface): for y in range(0, HEIGHT, GRID_SIZE): for x in range(0, WIDTH, GRID_SIZE): rect = pygame.Rect(x, y, GRID_SIZE, GRID_SIZE) pygame.draw.rect(surface, GRID_COLOR, rect, 1) def draw_score(surface, score, speed): score_text = font.render(f'Очки: {score}', True, TEXT_COLOR) speed_text = font.render(f'Скорость: {speed:.1f}', True, TEXT_COLOR) # Фон для текста score_bg = pygame.Rect(10, 10, score_text.get_width() + 20, 50) pygame.draw.rect(surface, SCORE_BG, score_bg, border_radius=8) pygame.draw.rect(surface, (70, 70, 120), score_bg, 2, border_radius=8) surface.blit(score_text, (20, 15)) surface.blit(speed_text, (20, 40)) def game_over_screen(surface, score): surface.fill(BACKGROUND) game_over_text = big_font.render('Игра Окончена!', True, (220, 60, 60)) score_text = font.render(f'Ваш счет: {score}', True, TEXT_COLOR) restart_text = font.render('Нажмите SPACE для новой игры', True, TEXT_COLOR) surface.blit(game_over_text, (WIDTH // 2 - game_over_text.get_width() // 2, HEIGHT // 3)) surface.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, HEIGHT // 2)) surface.blit(restart_text, (WIDTH // 2 - restart_text.get_width() // 2, HEIGHT * 2 // 3)) pygame.display.update() def main(): snake = Snake() food = Food() game_active = True while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if game_active: if event.key == pygame.K_UP: snake.update_direction(UP) elif event.key == pygame.K_DOWN: snake.update_direction(DOWN) elif event.key == pygame.K_LEFT: snake.update_direction(LEFT) elif event.key == pygame.K_RIGHT: snake.update_direction(RIGHT) elif event.key == pygame.K_SPACE: snake.reset() food.randomize_position() game_active = True if game_active: # Движение змейки с учетом скорости if time.time() - snake.last_move_time > 1 / snake.speed: if not snake.move(): game_active = False snake.last_move_time = time.time() # Проверка съедания еды if snake.get_head_position() == food.position: snake.grow() food.randomize_position() # Убедимся, что еда не появляется на змейке while food.position in snake.positions: food.randomize_position() # Отрисовка screen.fill(BACKGROUND) draw_grid(screen) snake.draw(screen) food.draw(screen) draw_score(screen, snake.score, snake.speed) else: game_over_screen(screen, snake.score) pygame.display.update() clock.tick(FPS * 2) # Высокий FPS для плавности управления if __name__ == "__main__": main()Особенности этой реализации:
- Плавное управление - змейка двигается с заданной скоростью независимо от FPS
- Визуальные улучшения:
- Сетка игрового поля
- Стилизованная голова змейки с глазами
- Еда в виде яблока
- Полупрозрачная панель счета
- Динамическая сложность - скорость увеличивается по мере роста счета
- Система очков - +10 очков за каждую съеденную еду
- Экран завершения игры с возможностью рестарта
- Запрет поворота на 180° - нельзя развернуться в противоположном направлении
- Телепортация через границы - змейка появляется с противоположной стороны
Управление:
- Стрелки ← ↑ → ↓ для движения
- SPACE для рестарта после проигрыша
Требования:
- Python 3.x
- Библиотека Pygame (установка:
pip install pygame)
Запустите код и наслаждайтесь классической игрой "Змейка" с современной графикой и плавным управлением!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.