gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
сделай тетрис на python
- User
сделай тетрис на python
- Assistant
сделай тетрис на python
Создание простой версии Тетриса на Python можно реализовать с использованием библиотеки pygame. Вот пример реализации Тетриса:
import pygame
import random
# Размеры экрана
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
# Цвета
COLORS = [
(0, 0, 0), # Черный
(255, 0, 0), # Красный
(0, 255, 0), # Зеленый
(0, 0, 255), # Синий
(255, 255, 0), # Желтый
(0, 255, 255), # Циан
(255, 0, 255), # Магента
]
# Формы Тетромино
SHAPES = [
[[1, 1, 1, 1]],
[[1, 1, 1], [0, 1, 0]],
[[1, 1], [1, 1]],
[[0, 1, 1], [1, 1, 0]],
[[1, 1, 0], [0, 1, 1]],
[[1, 0, 0], [1, 1, 1]],
[[0, 0, 1], [1, 1, 1]],
]
class Tetris:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Tetris")
self.clock = pygame.time.Clock()
self.board = [[0] * (SCREEN_WIDTH // BLOCK_SIZE) for _ in range(SCREEN_HEIGHT // BLOCK_SIZE)]
self.current_piece = self.new_piece()
self.next_piece = self.new_piece()
self.game_over = False
self.score = 0
def new_piece(self):
shape = random.choice(SHAPES)
color = COLORS[random.randint(1, len(COLORS)-1)]
return {'shape': shape, 'color': color, 'x': SCREEN_WIDTH // BLOCK_SIZE // 2, 'y': 0}
def draw_board(self):
for y in range(len(self.board)):
for x in range(len(self.board[y])):
color = COLORS[self.board[y][x]]
pygame.draw.rect(self.screen, color, (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
pygame.draw.rect(self.screen, (200, 200, 200), (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 1)
def draw_piece(self, piece):
shape = piece['shape']
color = piece['color']
for y, row in enumerate(shape):
for x, block in enumerate(row):
if block:
pygame.draw.rect(self.screen, color, ((piece['x'] + x) * BLOCK_SIZE, (piece['y'] + y) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
def rotate_piece(self):
self.current_piece['shape'] = [list(row) for row in zip(*self.current_piece['shape'][::-1])]
def clear_lines(self):
for y in range(len(self.board)-1, -1, -1):
if all(self.board[y]):
del self.board[y]
self.board.insert(0, [0] * (SCREEN_WIDTH // BLOCK_SIZE))
self.score += 100
def move_piece(self, dx, dy):
self.current_piece['x'] += dx
self.current_piece['y'] += dy
if self.collision():
self.current_piece['x'] -= dx
self.current_piece['y'] -= dy
if dy > 0:
self.merge_piece()
self.current_piece = self.next_piece
self.next_piece = self.new_piece()
if self.collision():
self.game_over = True
self.clear_lines()
def collision(self):
shape = self.current_piece['shape']
for y, row in enumerate(shape):
for x, block in enumerate(row):
if block:
board_x = self.current_piece['x'] + x
board_y = self.current_piece['y'] + y
if board_x < 0 or board_x >= len(self.board[0]) or board_y < 0 or board_y >= len(self.board):
return True
if board_y >= 0 and self.board[board_y][board_x]:
return True
return False
def merge_piece(self):
shape = self.current_piece['shape']
for y, row in enumerate(shape):
for x, block in enumerate(row):
if block:
self.board[self.current_piece['y'] + y][self.current_piece['x'] + x] = COLORS.index(self.current_piece['color'])
def run(self):
while not self.game_over:
self.screen.fill((0, 0, 0))
self.draw_board()
self.draw_piece(self.current_piece)
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.game_over = True
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.move_piece(-1, 0)
if keys[pygame.K_RIGHT]:
self.move_piece(1, 0)
if keys[pygame.K_DOWN]:
self.move_piece(0, 1)
if keys[pygame.K_UP]:
self.rotate_piece()
self.move_piece(0, 1)
self.clock.tick(10)
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
game = Tetris()
game.run()
Убедитесь, что у вас установлен Python и библиотека pygame. Вы можете установить pygame, выполнив команду:
pip install pygame
Скопируйте код в файл, например, tetris.py.
Запустите программу:
python tetris.py
←) - перемещение влево→) - перемещение вправо↓) - ускоренное падение↑) - вращение фигурыЭто базовая версия Тетриса. Вы можете расширять функциональность, добавляя анимации, улучшая интерфейс и добавляя больше уровней сложности!
Not yet included in a published release.