Задача Задача №122177
А
А
Я могу вам помочь написать змейку на языке Python. Вот необходимый код для создания простой змейки:
import pygame
import time
pygame.init()
# Определение цветов
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Определение размеров экрана
width, height = 640, 480
cell_size = 20
rows, cols = height // cell_size, width // cell_size
# Создание экрана
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Змейка")
clock = pygame.time.Clock()
class Snake:
def __init__(self):
self.body = [(cols // 2, rows // 2)]
self.direction = "RIGHT"
def move(self):
x, y = self.body[0]
if self.direction == "UP":
y -= 1
elif self.direction == "DOWN":
y += 1
elif self.direction == "LEFT":
x -= 1
elif self.direction == "RIGHT":
x += 1
self.body.insert(0, (x, y))
def change_direction(self, new_direction):
if new_direction in ["UP", "DOWN", "LEFT", "RIGHT"]:
if new_direction == "UP" and self.direction != "DOWN":
self.direction = new_direction
elif new_direction == "DOWN" and self.direction != "UP":
self.direction = new_direction
elif new_direction == "LEFT" and self.direction != "RIGHT":
self.direction = new_direction
elif new_direction == "RIGHT" and self.direction != "LEFT":
self.direction = new_direction
def draw(self):
for x, y in self.body:
pygame.draw.rect(screen, GREEN, (x * cell_size, y * cell_size, cell_size, cell_size))
def check_collision(self):
x, y = self.body[0]
if x < 0 or x >= cols or y < 0 or y >= rows or (x, y) in self.body[1:]:
return True
return False
snake = Snake()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.change_direction("UP")
elif event.key == pygame.K_DOWN:
snake.change_direction("DOWN")
elif event.key == pygame.K_LEFT:
snake.change_direction("LEFT")
elif event.key == pygame.K_RIGHT:
snake.change_direction("RIGHT")
snake.move()
if snake.check_collision():
running = False
screen.fill(BLACK)
snake.draw()
pygame.display.flip()
clock.tick(10)
pygame.quit()
После запуска этого кода вы увидите простую игру "Змейка". Управление змейкой осуществляется с помощью стрелочек. Удачи в игре и в учёбе! Если у вас есть ещё вопросы, не стесняйтесь задавать.
