目录
下面是一个用 Python 和 Pygame 库实现的简单俄罗斯方块(Tetris)小游戏程序。Pygame 是一个流行的 Python 库,用于创建视频游戏。确保你已经安装了 Pygame 库,可以使用以下命令安装:
pip install pygame
俄罗斯方块小游戏程序
import pygame
import random
# 初始化 Pygame
pygame.init()
# 屏幕尺寸
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 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)
ORANGE = (255, 165, 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
]
# 方块颜色
SHAPE_COLORS = [CYAN, YELLOW, PURPLE, GREEN, RED, BLUE, ORANGE]
# 游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
# 方块类
class Block:
def __init__(self, shape):
self.shape = shape
self.color = SHAPE_COLORS[SHAPES.index(shape)]
self.rotation = 0
self.x = SCREEN_WIDTH // 2 // BLOCK_SIZE - len(shape[0]) // 2
self.y = 0
def rotate(self):
self.shape = [list(row) for row in zip(*self.shape[::-1])]
# 游戏类
class Tetris:
def __init__(self):
self.grid = [[BLACK for _ in range(SCREEN_WIDTH // BLOCK_SIZE)] for _ in range(SCREEN_HEIGHT // BLOCK_SIZE)]
self.current_block = Block(random.choice(SHAPES))
self.next_block = Block(random.choice(SHAPES))
self.score = 0
self.game_over = False
def draw_grid(self):
for y in range(len(self.grid)):
for x in range(len(self.grid[y])):
pygame.draw.rect(screen, self.grid[y][x], (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
pygame.draw.rect(screen, WHITE, (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 1)
def draw_block(self, block, offset_x=0, offset_y=0):
for y in range(len(block.shape)):
for x in range(len(block.shape[y])):
if block.shape[y][x]:
pygame.draw.rect(screen, block.color, ((block.x + x + offset_x) * BLOCK_SIZE, (block.y + y + offset_y) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
pygame.draw.rect(screen, WHITE, ((block.x + x + offset_x) * BLOCK_SIZE, (block.y + y + offset_y) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 1)
def valid_move(self, block, offset_x=0, offset_y=0):
for y in range(len(block.shape)):
for x in range(len(block.shape[y])):
if block.shape[y][x]:
new_x = block.x + x + offset_x
new_y = block.y + y + offset_y
if new_x < 0 or new_x >= SCREEN_WIDTH // BLOCK_SIZE or new_y >= SCREEN_HEIGHT // BLOCK_SIZE:
return False
if new_y >= 0 and self.grid[new_y][new_x] != BLACK:
return False
return True
def merge_block(self):
for y in range(len(self.current_block.shape)):
for x in range(len(self.current_block.shape[y])):
if self.current_block.shape[y][x]:
self.grid[self.current_block.y + y][self.current_block.x + x] = self.current_block.color
self.clear_lines()
self.current_block = self.next_block
self.next_block = Block(random.choice(SHAPES))
if not self.valid_move(self.current_block):
self.game_over = True
def clear_lines(self):
new_grid = [row for row in self.grid if any(cell == BLACK for cell in row)]
lines_cleared = len(self.grid) - len(new_grid)
self.score += lines_cleared * 100
self.grid = [[BLACK for _ in range(SCREEN_WIDTH // BLOCK_SIZE)] for _ in range(lines_cleared)] + new_grid
def move_block(self, dx, dy):
if self.valid_move(self.current_block, dx, dy):
self.current_block.x += dx
self.current_block.y += dy
elif dy == 1:
self.merge_block()
def rotate_block(self):
self.current_block.rotate()
if not self.valid_move(self.current_block):
for _ in range(3):
self.current_block.rotate()
def run(self):
clock = pygame.time.Clock()
fall_time = 0
while not self.game_over:
screen.fill(BLACK)
fall_speed = 0.27 - (self.score // 10000) * 0.02
fall_time += clock.get_rawtime()
clock.tick()
if fall_time / 1000 >= fall_speed:
fall_time = 0
self.move_block(0, 1)
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.move_block(-1, 0)
elif event.key == pygame.K_RIGHT:
self.move_block(1, 0)
elif event.key == pygame.K_DOWN:
self.move_block(0, 1)
elif event.key == pygame.K_UP:
self.rotate_block()
self.draw_grid()
self.draw_block(self.current_block)
pygame.display.flip()
pygame.quit()
# 运行游戏
if __name__ == '__main__':
game = Tetris()
game.run()
代码说明
-
初始化 Pygame:
- 使用
pygame.init()
初始化 Pygame。 - 设置屏幕尺寸和颜色定义。
- 使用
-
方块形状和颜色:
- 定义了七种不同的方块形状和对应的颜色。
-
方块类:
Block
类表示一个方块,包含形状、颜色、旋转状态和位置。rotate
方法用于旋转方块。
-
游戏类:
Tetris
类表示游戏本身,包含网格、当前方块、下一个方块、得分和游戏结束标志。draw_grid
方法用于绘制网格。draw_block
方法用于绘制方块。valid_move
方法用于检查方块移动是否有效。merge_block
方法用于将方块合并到网格中。clear_lines
方法用于清除完整的行。move_block
方法用于移动方块。rotate_block
方法用于旋转方块。run
方法用于运行游戏主循环。
-
运行游戏:
- 创建
Tetris
对象并调用run
方法启动游戏。
- 创建
运行游戏
- 确保已经安装了 Pygame 库。
- 将上述代码保存为
tetris.py
。 - 在命令行中运行以下命令:
python tetris.py
游戏窗口将打开,你可以使用箭头键控制方块的移动和旋转。游戏结束时,窗口将自动关闭