如果你还没有安装pygame,可以通过运行pip install pygame来安装它。
- 代码如下:
python
import pygame
import random
# 初始化pygame
pygame.init()
# 屏幕尺寸
WIDTH, HEIGHT = 10, 20
TILE_SIZE = 40
WINDOW_SIZE = WIDTH * TILE_SIZE, HEIGHT * TILE_SIZE
WINDOW = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("Tetris")
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
YELLOW = (255, 255, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
ORANGE = (255, 165, 0)
# 形状定义
SHAPES = [
[[1, 1, 1, 1]], # I
[[1, 1], [1, 1]], # O
[[1, 1, 1], [0, 1, 0]], # T
[[1, 1, 0], [1, 1, 0]], # S
[[0, 1, 1], [1, 1, 0]], # Z
[[1, 1, 1], [1, 0, 0]], # J
[[1, 1, 1], [0, 0, 1]], # L
]
# 游戏变量
clock = pygame.time.Clock()
FPS = 15
board = [[0] * WIDTH for _ in range(HEIGHT)]
next_piece = random.choice(SHAPES)
current_piece = [[0] * WIDTH for _ in range(HEIGHT)]
piece_x, piece_y = WIDTH // 2 - len(next_piece[0]) // 2, 0
piece_color = random.choice([CYAN, MAGENTA, YELLOW, BLUE, GREEN, RED, ORANGE])
dropping = False
game_over = False
score = 0
# 检查是否消除行
def check_lines():
nonlocal score
lines_cleared = 0
for y in range(HEIGHT):
if all(board[y][x] != 0 for x in range(WIDTH)):
for y2 in range(y, 0, -1):
board[y2] = board[y2 - 1][:]
board[0] = [0] * WIDTH
lines_cleared += 1
score += 10 * (lines_cleared + 1)
return lines_cleared > 0
# 绘制游戏板
def draw_board():
WINDOW.fill(BLACK)
for y in range(HEIGHT):
for x in range(WIDTH):
if board[y][x] != 0:
color = (
YELLOW if board[y][x] == 1 else
MAGENTA if board[y][x] == 2 else
CYAN if board[y][x] == 3 else
BLUE if board[y][x] == 4 else
GREEN if board[y][x] == 5 else
RED if board[y][x] == 6 else
ORANGE
)
pygame.draw.rect(WINDOW, color, (x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE))
# 绘制当前下落中的形状
def draw_piece():
for y, row in enumerate(current_piece):
for x, cell in enumerate(row):
if cell != 0:
pygame.draw.rect(WINDOW, piece_color, ((piece_x + x) * TILE_SIZE, (piece_y + y) * TILE_SIZE, TILE_SIZE, TILE_SIZE))
# 主游戏循环
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 and piece_x > 0:
piece_x -= 1
elif event.key == pygame.K_RIGHT and piece_x < WIDTH - len(next_piece[0]):
piece_x += 1
elif event.key == pygame.K_DOWN or dropping:
dropping = True
piece_y += 1
if not all(all(board[piece_y + y][piece_x + x] == 0 or board[piece_y + y][piece_x + x] == piece_color for x, cell in enumerate(row)) for y, row in enumerate(next_piece)):
for y, row in enumerate(next_piece):
for x, cell in enumerate(row):
if cell != 0:
current_piece[y][x] = board[piece_y + y][piece_x + x]
board[piece_y + y][piece_x + x] = piece_color
piece_y = -1
dropping = False
next_piece = random.choice(SHAPES)
piece_color = random.choice([CYAN, MAGENTA, YELLOW, BLUE, GREEN, RED, ORANGE])
if not all(all(cell == 0 or (x >= piece_x and x < piece_x + len(next_piece[0]) and y >= 0 and y < len(next_piece)) and (next_piece[y - piece_y][x - piece_x] == 0 or next_piece[y - piece_y][x - piece_x] == piece_color) for x, cell in enumerate(row)) for y, row in enumerate(board[0:HEIGHT-piece_y])):
game_over = True
if check_lines():
dropping = True
if game_over:
running = False
# 更新当前形状位置
current_piece = [[0] * WIDTH for _ in range(HEIGHT)]
for y, row in enumerate(next_piece):
for x, cell in enumerate(row):
if cell != 0:
current_piece[y + piece_y][x + piece_x] = cell
# 绘制
draw_board()
draw_piece()
pygame.display.flip()
# 控制下落速度
clock.tick(FPS)
# 结束游戏
pygame.quit()
print(f"Game Over! Your score: {score}")
- 知识点总结:
一、关键类与功能
Brick类:表示游戏中的砖块,包括其位置、颜色以及图像。
Block(或Shape)类:表示游戏中的方块,包括其布局、方向、位置、砖块列表等。方块有7种基本形状:S、Z、T、L、反向L、直线、方块,每个形状都由4个砖块组成。
游戏区域与地图:使用二维数组表示游戏区域,其中0表示无砖块,1表示有砖块。定义游戏区域的宽度、高度以及方块的初始位置。
二、技术实现
使用pygame库:pygame是一个用于创建视频游戏的Python库,它提供了图形和声音库,使开发者能够轻松地创建游戏。
初始化pygame:在使用pygame库时,需要先进行初始化,保证pygame的代码块可以正常运行。
设置屏幕与刷新频率:使用pygame.display.set_mode()设置游戏窗口的大小和标题,使用pygame.time.Clock()创建时钟对象以控制游戏循环的频率。
绘制图形与文本:使用pygame的绘图函数绘制游戏区域、砖块、边框以及文本信息。
游戏循环:主游戏循环不断生成新方块,并更新和绘制游戏界面,直到游戏结束。