- 28
- 15
Приветствую всех! Сегодня простой код, увлекательной игры "Змейка", написанный на языке программирования Python с использованием библиотеки PyGame.
Python:
import sys
import random
import pygame
from pygame.locals import QUIT, KEYDOWN, K_UP, K_DOWN, K_LEFT, K_RIGHT, MOUSEBUTTONDOWN
class Snake:
def __init__(self, x, y, size):
self.size = size
self.body = [{'x': x, 'y': y}]
def draw(self, screen):
for segment in self.body:
pygame.draw.rect(screen, GREEN, (segment['x'], segment['y'], self.size, self.size))
def move(self, direction):
if direction == 'UP':
self.body[0]['y'] -= self.size
elif direction == 'DOWN':
self.body[0]['y'] += self.size
elif direction == 'LEFT':
self.body[0]['x'] -= self.size
elif direction == 'RIGHT':
self.body[0]['x'] += self.size
def check_collision(self, other):
return self.body[0]['x'] == other['x'] and self.body[0]['y'] == other['y']
def update(self):
for i in range(len(self.body) - 1, 0, -1):
self.body[i] = {'x': self.body[i - 1]['x'], 'y': self.body[i - 1]['y']}
class Fruit:
def __init__(self, size, width, height):
self.size = size
self.position = {'x': random.randrange(1, (width // size)) * size,
'y': random.randrange(1, (height // size)) * size}
def draw(self, screen):
pygame.draw.rect(screen, RED, (self.position['x'], self.position['y'], self.size, self.size))
class Game:
def __init__(self, width, height, snake_size, snake_speed):
self.width = width
self.height = height
self.snake_size = snake_size
self.snake_speed = snake_speed
self.snake = Snake(width // 2, height // 2, snake_size)
self.direction = 'RIGHT'
self.fruit = Fruit(snake_size, width, height)
self.score = 0
self.game_over = False
def draw_score(self, screen):
font = pygame.font.Font(None, 36)
score_text = font.render(f"Очки: {self.score}", True, (0, 0, 0))
screen.blit(score_text, (10, 10))
def draw_play_again(self, screen):
font = pygame.font.Font(None, 36)
play_again_text = font.render("Хотите ли сыграть ещё?", True, (0, 0, 0))
screen.blit(play_again_text, (150, 150))
button_yes = pygame.draw.rect(screen, GREEN, (200, 200, 100, 50))
button_no = pygame.draw.rect(screen, RED, (350, 200, 100, 50))
font = pygame.font.Font(None, 36)
text_yes = font.render("Да", True, (255, 255, 255))
text_no = font.render("Нет", True, (255, 255, 255))
screen.blit(text_yes, (225, 215))
screen.blit(text_no, (380, 215))
return button_yes, button_no
def handle_events(self, events):
for event in events:
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if not self.game_over:
if event.key == K_UP and self.direction != 'DOWN':
self.direction = 'UP'
elif event.key == K_DOWN and self.direction != 'UP':
self.direction = 'DOWN'
elif event.key == K_LEFT and self.direction != 'RIGHT':
self.direction = 'LEFT'
elif event.key == K_RIGHT and self.direction != 'LEFT':
self.direction = 'RIGHT'
elif event.type == MOUSEBUTTONDOWN:
if self.game_over:
button_yes, button_no = self.draw_play_again(screen)
mouse_x, mouse_y = event.pos
if button_yes.collidepoint(mouse_x, mouse_y):
self.reset_game()
elif button_no.collidepoint(mouse_x, mouse_y):
pygame.quit()
sys.exit()
def reset_game(self):
self.snake = Snake(self.width // 2, self.height // 2, self.snake_size)
self.direction = 'RIGHT'
self.score = 0
self.game_over = False
self.fruit = Fruit(self.snake_size, self.width, self.height)
def run(self):
while True:
events = pygame.event.get()
self.handle_events(events)
if not self.game_over:
self.snake.move(self.direction)
if self.snake.body[0]['x'] < 0:
self.snake.body[0]['x'] = self.width - self.snake_size
elif self.snake.body[0]['x'] >= self.width:
self.snake.body[0]['x'] = 0
if self.snake.body[0]['y'] < 0:
self.snake.body[0]['y'] = self.height - self.snake_size
elif self.snake.body[0]['y'] >= self.height:
self.snake.body[0]['y'] = 0
for segment in self.snake.body[1:]:
if self.snake.check_collision(segment):
self.game_over = True
if self.snake.check_collision(self.fruit.position):
self.score += 1
self.fruit = Fruit(self.snake_size, self.width, self.height)
self.snake.body.append({'x': self.snake.body[-1]['x'], 'y': self.snake.body[-1]['y']})
self.snake.update()
screen.fill(WHITE)
self.snake.draw(screen)
self.fruit.draw(screen)
self.draw_score(screen)
if self.game_over:
self.draw_play_again(screen)
pygame.display.update()
pygame.time.Clock().tick(self.snake_speed)
if __name__ == "__main__":
pygame.init()
WIDTH, HEIGHT = 800, 600
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Змейка")
game = Game(WIDTH, HEIGHT, 20, 12)
game.run()