gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
Напиши мне игру Tetris в консоли на языке Python
- User
Напиши мне игру Tetris в консоли на языке Python
- Assistant
Напиши мне игру Tetris в консоли на языке Python
Конечно! Вот простой пример игры Tetris, написанной на Python с использованием библиотеки Pygame. Убедитесь, что у вас установлена библиотека Pygame. Если нет, вы можете установить его командой:
pip install pygame
После установки библиотеки вы можете использовать следующий код для создания игры Tetris:
import pygame
import random
# Инициализация Pygame
pygame.init()
# Определяем размеры игры
WIDTH, HEIGHT = 300, 600
BLOCK_SIZE = 30
# Задаем цвета
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
YELLOW = (255, 255, 0)
# Фигуры Тетриса
SHAPES = [
[[1, 1, 1, 1]], # I
[[1, 1], [1, 1]], # O
[[0, 1, 0], [1, 1, 1]], # T
[[1, 1, 0], [0, 1, 1]], # Z
[[0, 1, 1], [1, 1, 0]], # S
[[1, 1, 1], [1, 0, 0]], # L
[[1, 1, 1], [0, 0, 1]] # J
]
class Tetris:
def __init__(self):
self.board = [[0 for _ in range(WIDTH // BLOCK_SIZE)] for _ in range(HEIGHT // BLOCK_SIZE)]
self.current_shape = self.new_shape()
self.current_x = WIDTH // BLOCK_SIZE // 2 - 1
self.current_y = 0
def new_shape(self):
return random.choice(SHAPES)
def rotate_shape(self):
self.current_shape = [list(row) for row in zip(*self.current_shape[::-1])]
def is_valid_position(self, offset_x=0, offset_y=0):
for y, row in enumerate(self.current_shape):
for x, cell in enumerate(row):
if cell:
if (self.current_x + x + offset_x < 0 or
self.current_x + x + offset_x >= WIDTH // BLOCK_SIZE or
self.current_y + y + offset_y >= HEIGHT // BLOCK_SIZE or
self.board[self.current_y + y + offset_y][self.current_x + x + offset_x]):
return False
return True
def fix_shape(self):
for y, row in enumerate(self.current_shape):
for x, cell in enumerate(row):
if cell:
self.board[self.current_y + y][self.current_x + x] = 1
self.clear_lines()
self.current_shape = self.new_shape()
self.current_x = WIDTH // BLOCK_SIZE // 2 - 1
self.current_y = 0
def clear_lines(self):
new_board = [row for row in self.board if any(cell == 0 for cell in row)]
lines_cleared = HEIGHT // BLOCK_SIZE - len(new_board)
self.board = [[0 for _ in range(WIDTH // BLOCK_SIZE)] for _ in range(lines_cleared)] + new_board
def drop(self):
if self.is_valid_position(offset_y=1):
self.current_y += 1
else:
self.fix_shape()
def move(self, direction):
if self.is_valid_position(offset_x=direction):
self.current_x += direction
def update(self):
self.drop()
def draw(self, screen):
screen.fill(BLACK)
for y, row in enumerate(self.board):
for x, cell in enumerate(row):
if cell:
pygame.draw.rect(screen, WHITE, (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
for y, row in enumerate(self.current_shape):
for x, cell in enumerate(row):
if cell:
pygame.draw.rect(screen, WHITE, ((self.current_x + x) * BLOCK_SIZE, (self.current_y + y) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
pygame.display.flip()
def main():
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
game = Tetris()
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_LEFT:
game.move(-1)
elif event.key == pygame.K_RIGHT:
game.move(1)
elif event.key == pygame.K_DOWN:
game.drop()
elif event.key == pygame.K_UP:
game.rotate_shape()
game.update()
game.draw(screen)
clock.tick(10) # 10 FPS
pygame.quit()
if __name__ == "__main__":
main()
Сохраните этот код в файл с расширением .py и запустите его. Игрок может управлять фигурками с помощью стрелок на клавиатуре:
Это простая реализация Tetris, и ее можно дополнить улучшениями, такими как уровни сложности, отслеживание счета и добавление различных цветов фигур, если вы захотите. Enjoy!
Not yet included in a published release.