创建一个基本的俄罗斯方块游戏需要使用 pygame
库,它是一个专门用于开发图形界面和游戏的 Python 库。下面是一个简单的俄罗斯方块游戏的实现,包括了方块的生成、旋转、移动、消行等基本功能。
首先,你需要确保已经安装了 pygame
。如果还没有安装,可以运行:
pip install pygame
然后,你可以使用以下代码创建一个基本的俄罗斯方块游戏:
import pygame
import random
# 初始化pygame
pygame.init()
# 游戏设置
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
GAME_SPEED = 500 # 控制下落速度,单位是毫秒
# 定义游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("俄罗斯方块")
# 定义颜色
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]], # S形
[[0, 1, 1], [1, 1, 0]], # Z形
[[1, 0, 0], [1, 1, 1]], # L形
[[0, 0, 1], [1, 1, 1]], # J形
]
SHAPES_COLORS = [CYAN, YELLOW, MAGENTA, GREEN, RED, BLUE, WHITE]
# 初始化游戏数据
board = [[BLACK] * (SCREEN_WIDTH // BLOCK_SIZE) for _ in range(SCREEN_HEIGHT // BLOCK_SIZE)]
# 定义方块类
class Tetromino:
def __init__(self, shape, color):
self.shape = shape
self.color = color
self.x = SCREEN_WIDTH // BLOCK_SIZE // 2 - len(self.shape[0]) // 2
self.y = 0
def rotate(self):
self.shape = [list(row) for row in zip(*self.shape[::-1])]
# 检查方块是否能放置
def is_valid_move(tetromino, board):
for y in range(len(tetromino.shape)):
for x in range(len(tetromino.shape[y])):
if tetromino.shape[y][x]:
if x + tetromino.x < 0 or x + tetromino.x >= SCREEN_WIDTH // BLOCK_SIZE or y + tetromino.y >= SCREEN_HEIGHT // BLOCK_SIZE or board[y + tetromino.y][x + tetromino.x] != BLACK:
return False
return True
# 放置方块
def place_tetromino(tetromino, board):
for y in range(len(tetromino.shape)):
for x in range(len(tetromino.shape[y])):
if tetromino.shape[y][x]:
board[tetromino.y + y][tetromino.x + x] = tetromino.color
# 清除已满的行
def clear_lines(board):
new_board = [row for row in board if any(cell == BLACK for cell in row)]
lines_cleared = SCREEN_HEIGHT // BLOCK_SIZE - len(new_board)
new_board = [[BLACK] * (SCREEN_WIDTH // BLOCK_SIZE)] * lines_cleared + new_board
return new_board, lines_cleared
# 绘制游戏界面
def draw_board(screen, board):
for y in range(len(board)):
for x in range(len(board[y])):
pygame.draw.rect(screen, board[y][x], (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(screen, WHITE, (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 1)
# 主游戏循环
def main():
# 初始化棋盘
board = [[BLACK] * (SCREEN_WIDTH // BLOCK_SIZE) for _ in range(SCREEN_HEIGHT // BLOCK_SIZE)]
clock = pygame.time.Clock()
tetromino = Tetromino(random.choice(SHAPES), random.choice(SHAPES_COLORS))
game_over = False
score = 0
while not game_over:
screen.fill(BLACK)
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
tetromino.x -= 1
if not is_valid_move(tetromino, board):
tetromino.x += 1
if event.key == pygame.K_RIGHT:
tetromino.x += 1
if not is_valid_move(tetromino, board):
tetromino.x -= 1
if event.key == pygame.K_DOWN:
tetromino.y += 1
if not is_valid_move(tetromino, board):
tetromino.y -= 1
if event.key == pygame.K_UP:
tetromino.rotate()
if not is_valid_move(tetromino, board):
tetromino.rotate()
tetromino.rotate()
tetromino.rotate()
# 方块下落
tetromino.y += 1
if not is_valid_move(tetromino, board):
tetromino.y -= 1
place_tetromino(tetromino, board)
board, lines_cleared = clear_lines(board)
score += lines_cleared
tetromino = Tetromino(random.choice(SHAPES), random.choice(SHAPES_COLORS))
if not is_valid_move(tetromino, board):
game_over = True
# 绘制当前状态
draw_board(screen, board)
pygame.draw.rect(screen, WHITE, (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), 5)
# 显示分数
font = pygame.font.Font(None, 36)
score_text = font.render(f"Score: {score}", True, WHITE)
screen.blit(score_text, (10, 10))
pygame.display.update()
clock.tick(60)
if __name__ == "__main__":
main()
pygame.quit()
代码解释:
1. **游戏设置**:
- 游戏窗口大小为 `300x600` 像素,每个方块的大小为 `30x30` 像素。
- 方块的颜色、形状、下落速度都已经设定好。
2. **方块的形状**:
- 方块通过 2D 数组来表示不同的形状(如 I、O、T、S、Z、L、J)。
3. **方块的移动与旋转**:
- 通过键盘的左右箭头键来控制方块的左右移动。
- 上箭头键用于旋转方块。
- 下箭头键用于加速方块的下落。
4. **行消除**:
- 当一行填满时,这一行会被清除,剩下的方块会下移。
5. **游戏结束**:
- 如果新的方块不能放置,则游戏结束。
### 运行游戏:
1. 在运行该程序之前,确保你已安装 `pygame` 库。
2. 将代码保存为 `tetris.py` 文件,然后运行:
```bash
python tetris.py
你将看到一个基本的俄罗斯方块游戏,可以使用键盘的方向键控制方块的移动和旋转。