用Python做一个俄罗斯方块小游戏:手把手教学版(附详细图解)

B站影视 电影资讯 2025-02-04 02:39 1

摘要:即使你是刚学Python的新手,只要跟着本教程一步步操作,90分钟就能做出属于自己的俄罗斯方块!从安装环境到代码调试,每个步骤都配有详细图解,遇到问题随时看解决方法!

导语:即使你是刚学Python的新手,只要跟着本教程一步步操作,90分钟就能做出属于自己的俄罗斯方块!从安装环境到代码调试,每个步骤都配有详细图解,遇到问题随时看解决方法!

最终实现界面

打开命令提示符(Windows搜索cmd)输入以下命令回车:pip install pygame

新建 tetris.py 文件,输入以下代码:

import pygame# 初始化游戏引擎pygame.init# 窗口设置WIDTH = 300 # 窗口宽度HEIGHT = 600 # 窗口高度GRID_SIZE = 30 # 每个小方块边长# 创建窗口screen = pygame.display.set_mode((WIDTH, HEIGHT))pygame.display.set_caption("我的俄罗斯方块")# 游戏主循环running = Truewhile running:for event in pygame.event.get:if event.type == pygame.QUIT:running = Falsescreen.fill((0, 0, 0)) # 用黑色填充背景pygame.display.update # 更新画面pygame.quit

图2

# 7种经典形状(用0和1表示)SHAPES = [[[1, 1, 1, 1]], # I型[[1, 0, 0], [1, 1, 1]], # L型[[0, 0, 1], [1, 1, 1]], # J型 [[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型]# 经典颜色配置(与形状顺序对应)COLORS = [(0, 255, 255), # 青色(255, 165, 0), # 橙色(0, 0, 255), # 蓝色(255, 255, 0), # 黄色(0, 255, 0), # 绿色(255, 0, 255), # 紫色(255, 0, 0) # 红色]

在代码中添加类定义:

class Game:def __init__(self):self.board = [[0]*(WIDTH//GRID_SIZE) for _ in range(HEIGHT//GRID_SIZE)]self.new_piece # 创建新方块def new_piece(self):"""生成新方块"""self.current_shape = random.choice(SHAPES)self.current_color = random.choice(COLORS)self.x = (len(self.board[0]) - len(self.current_shape[0])) // 2 # 居中显示self.y = 0 # 从顶部开始

修改主循环中的绘制部分:

# 在while循环内添加:# 绘制当前方块for y, row in enumerate(game.current_shape):for x, cell in enumerate(row):if cell: # 只绘制值为1的格子pygame.draw.rect(screen, game.current_color,((game.x + x)*GRID_SIZE, (game.y + y)*GRID_SIZE,GRID_SIZE-1, GRID_SIZE-1)) # -1是为了显示网格线

在主循环的事件处理部分添加:

elif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:game.x -= 1 # 左移elif event.key == pygame.K_RIGHT:game.x += 1 # 右移elif event.key == pygame.K_DOWN:game.y += 1 # 加速下落

在Game类中添加方法:

def check_collision(self, dx=0, dy=0):"""检测是否碰撞 dx:水平偏移 dy:垂直偏移"""for y, row in enumerate(self.current_shape):for x, cell in enumerate(row):if cell:new_x = self.x + x + dxnew_y = self.y + y + dy# 边界检测if new_x = len(self.board[0]):return Trueif new_y >= len(self.board):return True# 已有方块检测if self.board[new_y][new_x]:return Truereturn False

修改键盘事件代码:

if event.key == pygame.K_LEFT and not game.check_collision(-1, 0):game.x -= 1elif event.key == pygame.K_RIGHT and not game.check_collision(1, 0):game.x += 1elif event.key == pygame.K_DOWN and not game.check_collision(0, 1):game.y += 1

在主循环前初始化计时器:

game = Gamefall_time = 0fall_speed = 500 # 下落间隔500msclock = pygame.time.Clock

在循环内添加:

delta_time = clock.get_timefall_time += delta_timeif fall_time >= fall_speed:if not game.check_collision(0, 1):game.y += 1fall_time = 0else:# 固定方块并生成新方块game.merge_piecegame.new_piece

在Game类中添加:

def merge_piece(self):"""将当前方块固定到棋盘"""for y, row in enumerate(self.current_shape):for x, cell in enumerate(row):if cell:self.board[self.y + y][self.x + x] = self.current_color

在Game类中添加:

def clear_lines(self):"""消除满行"""lines_to_clear = for i, row in enumerate(self.board):if all(row): # 所有格子都有颜色lines_to_clear.append(i)# 删除满行并添加新行for i in lines_to_clear:del self.board[i]self.board.insert(0, [0]*len(self.board[0]))if game.check_collision:print("游戏结束!")running = False

来源:杭州打工仔

相关推荐