俄罗斯方块游戏 - Python 实现
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (128, 128, 128)
COLORS = [
(0, 255, 255), # I - 浅蓝色
(0, 0, 255), # J - 蓝色
(255, 165, 0), # L - 橙色
(255, 255, 0), # O - 黄色
(0, 255, 0), # S - 绿色
(128, 0, 128), # T - 紫色
(255, 0, 0) # Z - 红色
]
# 游戏设置
BLOCK_SIZE = 30
GRID_WIDTH = 10
GRID_HEIGHT = 20
SCREEN_WIDTH = BLOCK_SIZE * (GRID_WIDTH + 6)
SCREEN_HEIGHT = BLOCK_SIZE * GRID_HEIGHT
GAME_AREA_LEFT = BLOCK_SIZE
# 方块形状
SHAPES = [
[[1, 1, 1, 1]], # I
[[1, 0, 0], [1, 1, 1]], # J
[[0, 0, 1], [1, 1, 1]], # L
[[1, 1], [1, 1]], # O
[[0, 1, 1], [1, 1, 0]], # S
[[0, 1, 0], [1, 1, 1]], # T
[[1, 1, 0], [0, 1, 1]] # Z
]
# 初始化屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("俄罗斯方块")
clock = pygame.time.Clock()
class Tetris:
def __init__(self):
self.grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
self.current_piece = self.new_piece()
self.next_piece = self.new_piece()
self.game_over = False
self.score = 0
self.level = 1
self.fall_speed = 0.5 # 初始下落速度(秒)
self.fall_time = 0
self.space_pressed = False
self.space_press_time = 0
def new_piece(self):
# 从SHAPES中随机选择一个形状
shape = random.choice(SHAPES)
# 随机选择颜色
color = random.choice(COLORS)
# 初始位置在顶部中间
piece = {
'shape': shape,
'color': color,
'x': GRID_WIDTH // 2 - len(shape[0]) // 2,
'y': 0
}
return piece
def valid_position(self, piece=None, x=None, y=None):
if piece is None:
piece = self.current_piece
if x is None:
x = piece['x']
if y is None:
y = piece['y']
for i, row in enumerate(piece['shape']):
for j, cell in enumerate(row):
if cell:
if (x + j < 0 or x + j >= GRID_WIDTH or
y + i >= GRID_HEIGHT or
(y + i >= 0 and self.grid[y + i][x + j])):
return False
return True
def rotate_piece(self):
# 旋转方块
rotated = list(zip(*self.current_piece['shape'][::-1]))
rotated = [list(row) for row in rotated]
old_shape = self.current_piece['shape']
self.current_piece['shape'] = rotated
# 如果旋转后位置无效,尝试向左或向右移动
if not self.valid_position():
if self.valid_position(x=self.current_piece['x'] - 1):
self.current_piece['x'] -= 1
elif self.valid_position(x=self.current_piece['x'] + 1):
self.current_piece['x'] += 1
else:
# 如果移动后仍然无效,恢复原形状
self.current_piece['shape'] = old_shape
def merge_piece(self):
# 将当前方块合并到网格中
for i, row in enumerate(self.current_piece['shape']):
for j, cell in enumerate(row):
if cell and self.current_piece['y'] + i >= 0:
self.grid[self.current_piece['y'] + i][self.current_piece['x'] + j] = self.current_piece['color']
def clear_lines(self):
# 检查并清除完成的行
lines_cleared = 0
for i in range(GRID_HEIGHT):
if all(self.grid[i]):
lines_cleared += 1
# 删除该行并插入新的空行
del self.grid[i]
self.grid.insert(0, [0 for _ in range(GRID_WIDTH)])
# 根据清除的行数更新分数
if lines_cleared == 1:
self.score += 100 * self.level
elif lines_cleared == 2:
self.score += 300 * self.level
elif lines_cleared == 3:
self.score += 500 * self.level
elif lines_cleared == 4:
self.score += 800 * self.level
# 每清除10行升一级
if self.score // 1000 > self.level - 1:
self.level = self.score // 1000 + 1
self.fall_speed = max(0.05, 0.5 - (self.level - 1) * 0.05)
def hard_drop(self):
# 硬降落 - 直接将方块放到底部
while self.valid_position(y=self.current_piece['y'] + 1):
self.current_piece['y'] += 1
self.merge_piece()
self.clear_lines()
self.current_piece = self.next_piece
self.next_piece = self.new_piece()
if not self.valid_position():
self.game_over = True
def update(self, dt):
if self.game_over:
return
# 处理空格键长按
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
if not self.space_pressed:
self.space_pressed = True
self.space_press_time = pygame.time.get_ticks()
elif pygame.time.get_ticks() - self.space_press_time > 200: # 长按200毫秒触发硬降落
self.hard_drop()
else:
self.space_pressed = False
# 正常下落逻辑
self.fall_time += dt
if self.fall_time >= self.fall_speed:
self.fall_time = 0
if self.valid_position(y=self.current_piece['y'] + 1):
self.current_piece['y'] += 1
else:
self.merge_piece()
self.clear_lines()
self.current_piece = self.next_piece
self.next_piece = self.new_piece()
if not self.valid_position():
self.game_over = True
def draw(self):
# 绘制游戏区域背景
screen.fill(BLACK)
# 绘制网格
for y in range(GRID_HEIGHT):
for x in range(GRID_WIDTH):
pygame.draw.rect(screen, GRAY,
(GAME_AREA_LEFT + x * BLOCK_SIZE, y * BLOCK_SIZE,
BLOCK_SIZE, BLOCK_SIZE), 1)
if self.grid[y][x]:
pygame.draw.rect(screen, self.grid[y][x],
(GAME_AREA_LEFT + x * BLOCK_SIZE + 1, y * BLOCK_SIZE + 1,
BLOCK_SIZE - 2, BLOCK_SIZE - 2))
# 绘制当前方块
for i, row in enumerate(self.current_piece['shape']):
for j, cell in enumerate(row):
if cell:
pygame.draw.rect(screen, self.current_piece['color'],
(GAME_AREA_LEFT + (self.current_piece['x'] + j) * BLOCK_SIZE + 1,
(self.current_piece['y'] + i) * BLOCK_SIZE + 1,
BLOCK_SIZE - 2, BLOCK_SIZE - 2))
# 绘制下一个方块预览
next_x = GAME_AREA_LEFT + GRID_WIDTH * BLOCK_SIZE + 20
next_y = 50
font = pygame.font.SysFont(None, 30)
text = font.render("Next:", True, WHITE)
screen.blit(text, (next_x, next_y - 30))
for i, row in enumerate(self.next_piece['shape']):
for j, cell in enumerate(row):
if cell:
pygame.draw.rect(screen, self.next_piece['color'],
(next_x + j * BLOCK_SIZE + 1,
next_y + i * BLOCK_SIZE + 1,
BLOCK_SIZE - 2, BLOCK_SIZE - 2))
# 绘制分数和等级
font = pygame.font.SysFont(None, 30)
score_text = font.render(f"Score: {self.score}", True, WHITE)
level_text = font.render(f"Level: {self.level}", True, WHITE)
screen.blit(score_text, (next_x, next_y + 100))
screen.blit(level_text, (next_x, next_y + 130))
# 绘制游戏结束信息
if self.game_over:
font = pygame.font.SysFont(None, 40)
game_over_text = font.render("GAME OVER", True, (255, 0, 0))
restart_text = font.render("Press R to Restart", True, WHITE)
screen.blit(game_over_text, (GAME_AREA_LEFT + GRID_WIDTH * BLOCK_SIZE // 2 - 100,
SCREEN_HEIGHT // 2 - 50))
screen.blit(restart_text, (GAME_AREA_LEFT + GRID_WIDTH * BLOCK_SIZE // 2 - 150,
SCREEN_HEIGHT // 2 + 10))
def main():
game = Tetris()
running = True
while running:
dt = clock.tick(60) / 1000 # 转换为秒
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if not game.game_over:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if game.valid_position(x=game.current_piece['x'] - 1):
game.current_piece['x'] -= 1
elif event.key == pygame.K_RIGHT:
if game.valid_position(x=game.current_piece['x'] + 1):
game.current_piece['x'] += 1
elif event.key == pygame.K_DOWN:
if game.valid_position(y=game.current_piece['y'] + 1):
game.current_piece['y'] += 1
elif event.key == pygame.K_UP:
game.rotate_piece()
elif event.key == pygame.K_SPACE:
# 短按空格键直接硬降落
game.hard_drop()
else:
if event.type == pygame.KEYDOWN and event.key == pygame.K_r:
game = Tetris() # 重新开始游戏
game.update(dt)
game.draw()
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()
这个代码实现了一个完整的俄罗斯方块游戏,包含以下功能:
- 使用上下左右箭头键控制方块移动和旋转
- 长按空格键可以让方块直接落到底部
- 短按空格键也可以触发硬降落
- 游戏结束后按R键重新开始
- 包含分数和等级系统
- 显示下一个方块预览
运行代码需要安装pygame库,可以通过pip install pygame安装。