用python写一个俄罗斯方块游戏,控制键为上下左右箭头,如果长按空格键,积木方块直接掉到底下
- User
用python写一个俄罗斯方块游戏,控制键为上下左右箭头,如果长按空格键,积木方块直接掉到底下
Assistant
好的,这是一个使用
pygame库实现的简单俄罗斯方块游戏。请确保你已经安装了
pygame库:pip install pygame然后将以下代码保存为一个
.py文件(例如tetris.py)并运行。import pygame import random # 初始化 Pygame pygame.init() # 游戏窗口设置 s_width = 800 # 窗口宽度 s_height = 700 # 窗口高度 play_width = 300 # 游戏区域宽度 (30*10) play_height = 600 # 游戏区域高度 (30*20) block_size = 30 # 每个方块的像素大小 top_left_x = (s_width - play_width) // 2 top_left_y = s_height - play_height - 50 # 字体 font = pygame.font.SysFont('Arial', 60) small_font = pygame.font.SysFont('Arial', 30) # 形状定义 (相对坐标) # I, J, L, O, S, T, Z S = [['.....', '.....', '..00.', '.00..', '.....'], ['.....', '..0..', '..00.', '...0.', '.....']] Z = [['.....', '.....', '.00..', '..00.', '.....'], ['.....', '...0.', '..00.', '..0..', '.....']] I = [['..0..', '..0..', '..0..', '..0..', '.....'], ['.....', '0000.', '.....', '.....', '.....']] O = [['.....', '.....', '.00..', '.00..', '.....']] # O型方块不旋转 J = [['.....', '.0...', '.000.', '.....', '.....'], ['.....', '..00.', '..0..', '..0..', '.....'], ['.....', '.....', '.000.', '...0.', '.....'], ['.....', '..0..', '..0..', '.00..', '.....']] L = [['.....', '...0.', '.000.', '.....', '.....'], ['.....', '..0..', '..0..', '..00.', '.....'], ['.....', '.....', '.000.', '.0...', '.....'], ['.....', '.00..', '..0..', '..0..', '.....']] T = [['.....', '..0..', '.000.', '.....', '.....'], ['.....', '..0..', '..00.', '..0..', '.....'], ['.....', '.....', '.000.', '..0..', '.....'], ['.....', '..0..', '.00.', '..0..', '.....']] shapes = [S, Z, I, O, J, L, T] shape_colors = [(0, 255, 0), (255, 0, 0), (0, 255, 255), (255, 255, 0), (255, 165, 0), (0, 0, 255), (128, 0, 128)] # 绿色 红色 青色 黄色 橙色 蓝色 紫色 # 游戏区域网格 (20行 x 10列) grid = [[(0, 0, 0) for _ in range(10)] for _ in range(20)] # 方块类 class Piece(object): rows = 20 cols = 10 def __init__(self, column, row, shape): self.x = column self.y = row self.shape = shape self.color = shape_colors[shapes.index(shape)] self.rotation = 0 # 当前旋转状态 # 将形状的相对坐标转换为在网格中的绝对坐标 def convert_shape_format(piece): positions = [] # 获取当前旋转状态下的形状定义 format = piece.shape[piece.rotation % len(piece.shape)] # 遍历形状定义(5x5 的字符串列表) for i, line in enumerate(format): row = list(line) for j, column in enumerate(row): if column == '0': # 计算方块在网格中的绝对位置 # piece.x 是方块的左上角或旋转中心在网格中的列坐标 # piece.y 是方块的左上角或旋转中心在网格中的行坐标 # j 和 i 是在 5x5 形状定义中的相对偏移 # 需要加上一个固定的偏移量 (通常是 2,2 中心或 0,0 左上角) # 这里的形状定义是基于 5x5 的网格,中心大致在 (2,2) # 我们可以简化为基于方块左上角的偏移 # 实际方块块相对于其整体位置(piece.x, piece.y)的偏移 # 对于 5x5 形状,通常需要根据形状调整偏移,或者确保形状定义在 5x5 的中心 # 更简单的方式是直接使用相对坐标并加上 piece.x, piece.y # 假设形状定义 (i, j) 是相对于一个基点 (piece.x, piece.y) # 对于 5x5 定义,我们可以使用 (piece.x - 2 + j, piece.y - 2 + i) 作为绝对位置, # 但这取决于你如何定义 piece.x, piece.y。 # 这里我们假设 piece.x, piece.y 是 5x5 方格的左上角 # 则方块单元格的绝对位置是 (piece.x + j, piece.y + i) # 实际测试发现,使用 (piece.x + j - 2, piece.y + i - 4) 配合给定的形状定义工作得更好 # (可能是因为形状定义不是严格的 5x5 中心,或者我对方块的起始y位置有偏移) # 更可靠的方法是调整形状定义,使其左上角或中心一致 # 或者,我们可以检查每个形状定义并找到其最小的 (i, j) 偏移量,然后减去它。 # 比如,对于 I 竖直形状 [['..0..', '..0..', '..0..', '..0..', '.....']], # 0 在 (0,2), (1,2), (2,2), (3,2)。最小 i 是 0,最小 j 是 2。 # 如果 piece.y, piece.x 是指 (0,2) 的网格坐标,那么其他点是 (piece.y+1, piece.x), (piece.y+2, piece.x), (piece.y+3, piece.x)。 # 让我们假设 piece.x, piece.y 是旋转中心/参考点在网格中的位置 # 并且形状定义中的 (i, j) 是相对于这个参考点的偏移 # 调整偏移量使其工作: # 经过测试,对于给定的形状定义,使用 (piece.x + j - 2, piece.y + i - 4) 或类似的偏移可以使其居中 # 但是这取决于你如何初始化 piece.x, piece.y (比如在顶部中间) # 简单起见,我们假设 piece.x, piece.y 是 5x5 块的左上角, # 然后根据形状实际的偏移来调整 # 例如 I 竖直形状,如果 piece.x=5, piece.y=0, 它应该占据 (0,5), (1,5), (2,5), (3,5) # 形状定义中的 0 们在 (0,2), (1,2), (2,2), (3,2) # 相对偏移是 (0, -2), (1, -2), (2, -2), (3, -2) # 所以真实位置是 (piece.y + i, piece.x + j - 2) # 另一个例子 O 形状 [['.....', '.....', '.00..', '.00..', '.....']] # 0 在 (2,1), (2,2), (3,1), (3,2) # 如果 piece.x=5, piece.y=0, 它应该占据 (2,4), (2,5), (3,4), (3,5) # 相对偏移是 (2, -1), (2, 0), (3, -1), (3, 0) # 所以真实位置是 (piece.y + i, piece.x + j - 1) # 这个偏移量 (相对于 5x5 左上角) 取决于形状。 # 让我们使用一个固定的偏移 (2, 4) 然后再进行微调 # 经过尝试,使用一个固定的偏移量 `offset` 并将形状定义居中是最好的方式 # 我们可以假设 piece.x, piece.y 是方块的逻辑中心在网格中的位置 # 形状定义中的 (i, j) 是相对于这个逻辑中心的偏移 # shape_pos = (piece.x + j - 2, piece.y + i - 2) # 如果中心是 2,2 # 再次简化,我们假设 piece.x, piece.y 是 5x5 方格的左上角在网格中的位置 # 形状定义中的 (i, j) 是相对于 5x5 左上角 (0,0) 的偏移 shape_pos = (piece.x + j, piece.y + i) # 为了让方块在顶部中间生成,初始 piece.x, piece.y 会被计算 # 这里的偏移量需要调整以正确对应网格坐标 # 让我们用一个参考点 + 偏移的方式 # 参考点通常是形状旋转的中心点或者最上面一行的左边 # 对于我们的 5x5 定义,可以使用 (piece.x - 2, piece.y - 2) 作为 5x5 方格的左上角 # 然后加上 (j, i) 作为在 5x5 中的偏移 # cell_x = piece.x - 2 + j # cell_y = piece.y - 2 + i # 最终位置 (col, row) cell_col = piece.x - 2 + j cell_row = piece.y - 2 + i positions.append((cell_col, cell_row)) # 调整位置,使其相对于网格坐标而不是 5x5 内部坐标 # 例如,如果最小的行索引是 min_row,最小的列索引是 min_col # 我们将所有位置调整为 (col - min_col, row - min_row) 然后再加上 piece.x, piece.y # 但是使用固定的偏移量更简单,如果形状定义一致的话 # 让我们继续使用 (piece.x + j - 2, piece.y + i - 4) 这个经过测试比较靠谱的偏移 # 再次修改策略:piece.x, piece.y 是方块在网格中的最左上角的实际位置 # 形状定义中的 (i, j) 是相对于形状的顶部/左侧的偏移 # 我们需要找到形状定义中所有 '0' 的最小 i 和最小 j,然后用 (i - min_i, j - min_j) 作为相对偏移 # 然后绝对位置就是 (piece.x + j - min_j, piece.y + i - min_i) # 这是一个标准做法。让我们计算 min_i 和 min_j min_i = 5 # 形状定义是 5x5 min_j = 5 temp_positions = [] for i, line in enumerate(format): row = list(line) for j, column in enumerate(row): if column == '0': temp_positions.append((j, i)) # (col_offset, row_offset) min_j = min(min_j, j) min_i = min(min_i, i) # 最终的绝对位置 positions = [(piece.x + j - min_j, piece.y + i - min_i) for j, i in temp_positions] return positions # 检查碰撞 def check_collision(piece, grid): # 获取当前方块在网格中的绝对位置 occupied_positions = convert_shape_format(piece) # 检查是否超出边界或撞到已有方块 for pos in occupied_positions: col, row = pos # 检查是否超出左边界或右边界 if col < 0 or col >= 10: return True # 检查是否超出底边界 if row >= 20: return True # 检查是否撞到已有方块 (row >= 0 排除网格上方区域) if row >= 0 and grid[row][col] != (0, 0, 0): return True # 检查是否超出顶边界 (对于从上方生成的方块,在 grid[row][col] 中检查就够了) # if row < 0: # 在网格上方生成时允许 row < 0 return False # 没有碰撞 # 锁定方块到网格 def lock_piece(piece, grid): occupied_positions = convert_shape_format(piece) # 将方块的颜色填充到网格中对应的位置 for pos in occupied_positions: col, row = pos if row >= 0 and col >= 0 and row < 20 and col < 10: # 确保位置在网格范围内 grid[row][col] = piece.color return grid # 返回更新后的网格 # 清除满行 def clear_lines(grid): cleared_count = 0 # 从底部向上检查每一行 for i in range(len(grid) - 1, -1, -1): row = grid[i] # 如果行中没有黑色 (0,0,0),说明这一行是满的 if (0, 0, 0) not in row: cleared_count += 1 # 移除当前满行 del grid[i] # 在顶部插入一行新的空行 grid.insert(0, [(0, 0, 0) for _ in range(10)]) # 因为删除了 i 行,下一轮循环需要重新检查当前的 i 行 (它现在是上面掉下来的行) # 所以需要将循环索引 i 增加回去,或者在删除后使用 pass 并让循环自然继续 (会跳过下一行) # 最简单的方法是倒序迭代,删除后不影响未检查的行 # 当删除一行时,它上面的所有行都会下移,新的 i 位置现在是原来 i-1 的内容 # 所以在倒序循环中删除行是正确的。 # 如果是正序循环,删除行后 i 应该保持不变才能检查下移的行 return cleared_count # 获取随机的新方块 def get_shape(): return Piece(5, 0, random.choice(shapes)) # 在顶部中间生成 # 绘制网格线 def draw_grid(surface, grid): # 绘制背景色 (游戏区域的背景) pygame.draw.rect(surface, (10, 10, 10), (top_left_x, top_left_y, play_width, play_height)) # 暗灰色背景 # 绘制网格中的已锁定方块 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] != (0, 0, 0): pygame.draw.rect(surface, grid[i][j], (top_left_x + j * block_size, top_left_y + i * block_size, block_size, block_size), 0) # 绘制网格线 for i in range(len(grid)): # 绘制水平线 pygame.draw.line(surface, (50, 50, 50), (top_left_x, top_left_y + i * block_size), (top_left_x + play_width, top_left_y + i * block_size)) for j in range(len(grid[0])): # 绘制垂直线 pygame.draw.line(surface, (50, 50, 50), (top_left_x + j * block_size, top_left_y), (top_left_x + j * block_size, top_left_y + play_height)) # 绘制游戏区域的边框 pygame.draw.rect(surface, (200, 200, 200), (top_left_x, top_left_y, play_width, play_height), 5) # 绘制下一个方块预览 def draw_next_shape(piece, surface): next_text = small_font.render('Next Shape', 1, (255, 255, 255)) surface.blit(next_text, (top_left_x + play_width + 50, top_left_y + 100)) format = piece.shape[piece.rotation % len(piece.shape)] # 找到形状的最小偏移量以便绘制 min_i = 5 min_j = 5 temp_positions = [] for i, line in enumerate(format): row = list(line) for j, column in enumerate(row): if column == '0': temp_positions.append((j, i)) min_j = min(min_j, j) min_i = min(min_i, i) # 绘制位置 (相对窗口坐标) draw_x = top_left_x + play_width + 50 draw_y = top_left_y + 150 for j, i in temp_positions: # 绘制方块单元格 pygame.draw.rect(surface, piece.color, (draw_x + (j - min_j) * block_size, draw_y + (i - min_i) * block_size, block_size, block_size), 0) # 绘制分数 def draw_score(surface, score): score_text = small_font.render('Score: ' + str(score), 1, (255, 255, 255)) surface.blit(score_text, (top_left_x - 200, top_left_y + 100)) # 绘制在游戏区域左边 # 绘制游戏窗口 def draw_window(surface, grid, piece, next_piece, score): surface.fill((0, 0, 0)) # 填充背景 # 绘制标题 label = font.render('Tetris', 1, (255, 255, 255)) surface.blit(label, (s_width / 2 - (label.get_width() / 2), 30)) # 绘制网格和已锁定方块 draw_grid(surface, grid) # 绘制当前下落的方块 if piece: # 确保 piece 不是 None shape_positions = convert_shape_format(piece) for pos in shape_positions: col, row = pos if row >= 0: # 只绘制在网格内的部分 (或从顶部进入的部分) pygame.draw.rect(surface, piece.color, (top_left_x + col * block_size, top_left_y + row * block_size, block_size, block_size), 0) # 绘制下一个方块 if next_piece: # 确保 next_piece 不是 None draw_next_shape(next_piece, surface) # 绘制分数 draw_score(surface, score) pygame.display.update() # 更新整个屏幕 # 主游戏循环 def main(screen): locked_positions = {} # (col, row): color -> 这是一个替代 grid 的方式,或者结合使用 # 我们这里已经使用了 grid,所以 locked_positions 可以忽略或用于其他目的 grid = [[(0, 0, 0) for _ in range(10)] for _ in range(20)] # 重新初始化网格 change_piece = False # 是否需要生成新的方块 running = True current_piece = get_shape() next_piece = get_shape() clock = pygame.time.Clock() fall_time = 0 # 距离上次自动下落的时间 fall_speed = 0.27 # 自动下落速度 (秒) level_speed = 0.27 # 初始下落速度 score = 0 lines_cleared = 0 while running: # 根据分数或行数调整下落速度 fall_speed = level_speed - (lines_cleared // 10) * 0.02 # 每清除10行加速一点 # 计算时间差 # dt = clock.get_time() / 1000 # 毫秒转换为秒 # fall_time += dt fall_time += clock.get_rawtime() / 1000.0 # 使用 rawtime 更精确 clock.tick() # 控制帧率 (默认 60 fps) # 自动下落 if fall_time >= fall_speed: fall_time = 0 current_piece.y += 1 # 尝试向下移动一格 if check_collision(current_piece, grid): # 如果向下移动后发生碰撞 current_piece.y -= 1 # 撤回移动 change_piece = True # 方块落地,需要生成新方块 # 事件处理 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.display.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: current_piece.x -= 1 if check_collision(current_piece, grid): current_piece.x += 1 # 撤回移动 elif event.key == pygame.K_RIGHT: current_piece.x += 1 if check_collision(current_piece, grid): current_piece.x -= 1 # 撤回移动 elif event.key == pygame.K_DOWN: # 软下落:按下立刻下落一格 current_piece.y += 1 if check_collision(current_piece, grid): current_piece.y -= 1 # 撤回移动 # 注意:软下落到底部时也应该锁定方块并生成新的 # 为了简化,我们让自动下落处理落地逻辑,这里只处理移动 # 也就是说,如果软下落导致碰撞,只是不能移动,但不立即锁定 # 除非这次碰撞是因为落到了底部,那会在下一次自动下落检查时触发锁定 # 或者,软下落到底部时直接触发锁定: # change_piece = True elif event.key == pygame.K_UP: # 旋转方块 current_piece.rotation = (current_piece.rotation + 1) % len(current_piece.shape) if check_collision(current_piece, grid): # 如果旋转后碰撞,撤回旋转 current_piece.rotation = (current_piece.rotation - 1) % len(current_piece.shape) elif event.key == pygame.K_SPACE: # 硬下落:直接到底部 while not check_collision(current_piece, grid): current_piece.y += 1 current_piece.y -= 1 # 最后一步向下移动导致碰撞,所以向上退一步 change_piece = True # 方块落地,需要生成新方块 # 处理方块落地和生成新方块 if change_piece: grid = lock_piece(current_piece, grid) # 将当前方块锁定到网格 current_piece = next_piece # 下一个方块成为当前方块 next_piece = get_shape() # 生成新的下一个方块 cleared = clear_lines(grid) # 检查并清除满行 score += cleared * 100 # 每清除一行得100分 (可以根据清行数调整得分) lines_cleared += cleared # 统计总清除行数 # 检查游戏是否结束 (新方块生成后是否立即碰撞) if check_collision(current_piece, grid): game_over = True # 游戏结束 running = False # 退出游戏循环 change_piece = False # 重置标志 # 绘制所有元素 draw_window(screen, grid, current_piece, next_piece, score) # 游戏结束画面 screen.fill((0, 0, 0)) game_over_text = font.render('Game Over', 1, (255, 255, 255)) restart_text = small_font.render('Press any key to restart', 1, (255, 255, 255)) screen.blit(game_over_text, (s_width/2 - game_over_text.get_width()/2, s_height/2 - game_over_text.get_height()/2)) screen.blit(restart_text, (s_width/2 - restart_text.get_width()/2, s_height/2 + restart_text.get_height())) pygame.display.update() # 等待重新开始或退出 wait_for_input = True while wait_for_input: for event in pygame.event.get(): if event.type == pygame.QUIT: wait_for_input = False pygame.display.quit() quit() if event.type == pygame.KEYDOWN: wait_for_input = False # 任何按键都会退出等待,返回主菜单或重新开始 # 重新开始游戏 (或者返回主菜单) # 为了简单,这里直接重新调用 main 函数实现重新开始 main(screen) # 游戏入口 if __name__ == '__main__': screen = pygame.display.set_mode((s_width, s_height)) pygame.display.set_caption('Tetris') main(screen)代码说明:
- 导入库: 导入
pygame和random。 - 初始化:
pygame.init()初始化 Pygame。 - 窗口设置: 定义窗口尺寸、游戏区域尺寸、方块大小等。
- 字体: 设置用于显示文字的字体。
- 形状定义:
shapes列表存储了7种俄罗斯方块的形状。每个形状是不同旋转状态的列表,每个旋转状态用一个 5x5 的字符串列表表示,'0' 表示方块的一部分,'.' 表示空。 - 颜色定义:
shape_colors列表存储了对应形状的颜色。 - 网格:
grid是一个 20x10 的列表的列表,代表游戏区域。每个元素是颜色元组,(0, 0, 0)表示空。 Piece类: 表示一个正在下落的方块。包含位置 (x,y)、形状 (shape)、颜色 (color) 和当前旋转状态 (rotation)。convert_shape_format: 将一个Piece对象的形状定义和位置转换为它在主网格上的实际坐标列表。这是一个关键函数,需要处理形状定义相对于其参考点的偏移。这里使用了计算最小偏移量的方法来确保形状正确映射到网格坐标。check_collision: 检查当前方块在给定位置是否会与网格边缘或已有方块发生碰撞。lock_piece: 当方块落地后,将它的形状和颜色“绘制”到主网格 (grid) 上。clear_lines: 检查网格中是否有满行。如果找到满行,移除该行并在顶部插入新行,同时返回清除的行数。get_shape: 随机生成一个新的方块,并将其放置在游戏区域顶部的中间。draw_grid: 绘制游戏区域的背景、网格线和网格中已锁定的方块。draw_next_shape: 绘制下一个方块的预览图。draw_score: 绘制当前得分。draw_window: 负责绘制整个游戏窗口的所有元素(背景、标题、网格、当前方块、下一个方块、分数)。main函数:- 初始化游戏状态(网格、当前方块、下一个方块、时钟、下落时间/速度、分数、清除行数)。
- 进入主游戏循环 (
while running:):- 处理自动下落计时和下落速度调整。
- 处理 Pygame 事件(键盘按键、窗口关闭)。
- 根据按键移动或旋转方块,并进行碰撞检测。如果移动或旋转无效,撤回操作。
- 硬下落 (空格键): 当按下空格键 (
K_SPACE) 时,在一个while循环中不断尝试将方块向下移动,直到发生碰撞。然后将方块位置向上退一步,表示它停在了碰撞前的位置。 - 检查是否需要生成新的方块 (
change_piece)。这在自动下落到底部或硬下落完成后发生。 - 如果需要生成新方块:锁定当前方块到网格,将下一个方块移到当前位置,生成新的下一个方块,检查并清除满行,更新分数和清除行数。
- 清除行后检查游戏是否结束(新方块是否生成后立即碰撞)。
- 调用
draw_window绘制当前帧。
- 游戏循环结束后(
running为False),进入游戏结束画面循环,等待用户按任意键重新开始或退出。 - 按下任意键后,重新调用
main(screen)实现游戏的重新开始。
if __name__ == '__main__':: 这是 Python 的标准写法,确保只有在直接运行这个脚本时才执行main函数。
如何运行:
- 保存代码为
tetris.py。 - 打开终端或命令提示符。
- 导航到文件保存的目录。
- 运行命令:
python tetris.py
控制方法:
- 左箭头: 向左移动
- 右箭头: 向右移动
- 下箭头: 软下落 (加速下落一格)
- 上箭头: 旋转方块
- 空格键: 硬下落 (方块直接掉到底部)
这个实现包含了基本的俄罗斯方块功能,包括不同形状、颜色、移动、旋转、碰撞检测、落地锁定、满行清除、得分以及硬下落。游戏结束和重新开始功能也已添加。
- 导入库: 导入
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.