一、需求分析
????????實現了一個經典的俄羅斯方塊小游戲,主要滿足以下需求:
1.圖形界面
????????使用 pygame 庫創建一個可視化的游戲窗口,展示游戲的各種元素,如游戲區域、方塊、分數等信息。
2.游戲邏輯
????????實現方塊的生成、移動、旋轉、下落和鎖定等基本操作,同時檢測方塊是否超出邊界或與已有方塊重疊。
3.計分系統
????????根據玩家消除的行數來計算分數和等級,等級的提升會加快方塊的下落速度。
4.用戶交互
????????支持用戶通過鍵盤控制方塊的移動、旋轉和快速下落,游戲結束后可按 R 鍵重新開始。
5.提示信息
????????在游戲界面顯示下一個方塊預覽、分數、等級以及操作說明,游戲結束時給出相應提示。
二、關鍵模塊
1.初始化
import pygame
import random
import sys# 初始化pygame
pygame.init()# 顏色定義
BACKGROUND_COLOR = (214, 226, 251) # 背景色
# ... 其他顏色定義# 游戲設置
GRID_SIZE = 30
GRID_WIDTH = 10
GRID_HEIGHT = 20
SCREEN_WIDTH = GRID_WIDTH * GRID_SIZE + 200
SCREEN_HEIGHT = GRID_HEIGHT * GRID_SIZE# 創建游戲窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("俄羅斯方塊")# 使用系統自帶的中文字體
try:font = pygame.font.SysFont("PingFang", 20)large_font = pygame.font.SysFont("PingFang", 40)
except:font = pygame.font.SysFont(None, 20)large_font = pygame.font.SysFont(None, 40)
????????此模塊負責導入必要的庫,初始化 pygame ,定義游戲所需的顏色、尺寸等常量,創建游戲窗口并設置字體。
2.Tetris 類模塊
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 = Falseself.score = 0self.level = 1self.fall_speed = 0.5 # 初始下落速度(秒)self.fall_time = 0# ... 其他方法
????????Tetris 類封裝了游戲的核心邏輯,包括游戲狀態的初始化、方塊的生成、移動、旋轉、鎖定以及行消除和計分等功能。
3.主游戲循環模塊
def main():clock = pygame.time.Clock()game = Tetris()while True:# 處理事件for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()# ... 其他事件處理# 自動下落if not game.game_over:current_time = pygame.time.get_ticks() / 1000if current_time - game.fall_time > game.fall_speed:game.fall_time = current_timeif game.valid_move(game.current_piece, 0, 1):game.current_piece['y'] += 1else:game.lock_piece()# 繪制游戲game.draw()pygame.display.update()clock.tick(60)
????????該模塊是游戲的主循環,負責處理用戶輸入事件,控制方塊的自動下落,更新游戲狀態并繪制游戲界面。
三、完整代碼
import pygame
import random
import sys# 初始化pygame
pygame.init()# 顏色定義
BACKGROUND_COLOR = (214, 226, 251) # 背景色
GRID_COLOR = (255, 255, 255) # 游戲區域網格顏色
BLOCK_GRID_COLOR = (0, 0, 0) # 方塊網格顏色
TEXT_COLOR = (0, 0, 0) # 普通文字顏色
GAME_OVER_COLOR = (255, 0, 0) # 游戲結束文字顏色# 游戲設置
GRID_SIZE = 30
GRID_WIDTH = 10
GRID_HEIGHT = 20
SCREEN_WIDTH = GRID_WIDTH * GRID_SIZE + 200
SCREEN_HEIGHT = GRID_HEIGHT * GRID_SIZE# 方塊形狀
SHAPES = [[[1, 1, 1, 1]], # I[[1, 1], [1, 1]], # O[[1, 1, 1], [0, 1, 0]], # T[[1, 1, 1], [1, 0, 0]], # L[[1, 1, 1], [0, 0, 1]], # J[[0, 1, 1], [1, 1, 0]], # S[[1, 1, 0], [0, 1, 1]] # Z
]# 創建游戲窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("俄羅斯方塊")# 使用系統自帶的中文字體
try:font = pygame.font.SysFont("PingFang", 20)large_font = pygame.font.SysFont("PingFang", 40)
except:font = pygame.font.SysFont(None, 20)large_font = pygame.font.SysFont(None, 40)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 = Falseself.score = 0self.level = 1self.fall_speed = 0.5 # 初始下落速度(秒)self.fall_time = 0def new_piece(self):shape = random.choice(SHAPES)return {'shape': shape,'x': GRID_WIDTH // 2 - len(shape[0]) // 2,'y': 0}def valid_move(self, piece, x_offset=0, y_offset=0):for y, row in enumerate(piece['shape']):for x, cell in enumerate(row):if cell:new_x = piece['x'] + x + x_offsetnew_y = piece['y'] + y + y_offsetif (new_x < 0 or new_x >= GRID_WIDTH or new_y >= GRID_HEIGHT or (new_y >= 0 and self.grid[new_y][new_x])):return Falsereturn Truedef rotate_piece(self):# 旋轉方塊rotated = list(zip(*reversed(self.current_piece['shape'])))old_shape = self.current_piece['shape']self.current_piece['shape'] = rotatedif not self.valid_move(self.current_piece):self.current_piece['shape'] = old_shapedef lock_piece(self):# 鎖定當前方塊到網格for y, row in enumerate(self.current_piece['shape']):for x, cell in enumerate(row):if cell:self.grid[self.current_piece['y'] + y][self.current_piece['x'] + x] = 1# 檢查是否有完整的行self.clear_lines()# 生成新方塊self.current_piece = self.next_pieceself.next_piece = self.new_piece()# 檢查游戲是否結束if not self.valid_move(self.current_piece):self.game_over = Truedef clear_lines(self):lines_cleared = 0for y in range(GRID_HEIGHT):if all(self.grid[y]):lines_cleared += 1# 移動上面的行下來for y2 in range(y, 0, -1):self.grid[y2] = self.grid[y2-1][:]self.grid[0] = [0 for _ in range(GRID_WIDTH)]# 更新分數if lines_cleared > 0:self.score += lines_cleared * 100 * self.levelself.level = self.score // 1000 + 1self.fall_speed = max(0.1, 0.5 - (self.level - 1) * 0.05)def draw(self):# 繪制背景screen.fill(BACKGROUND_COLOR)# 繪制游戲區域網格for y in range(GRID_HEIGHT):for x in range(GRID_WIDTH):pygame.draw.rect(screen, GRID_COLOR, (x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE), 1)# 繪制已鎖定的方塊for y in range(GRID_HEIGHT):for x in range(GRID_WIDTH):if self.grid[y][x]:pygame.draw.rect(screen, (0, 100, 200), (x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE))pygame.draw.rect(screen, BLOCK_GRID_COLOR, (x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE), 1)# 繪制當前方塊if not self.game_over:for y, row in enumerate(self.current_piece['shape']):for x, cell in enumerate(row):if cell:pygame.draw.rect(screen, (200, 0, 0), ((self.current_piece['x'] + x) * GRID_SIZE, (self.current_piece['y'] + y) * GRID_SIZE, GRID_SIZE, GRID_SIZE))pygame.draw.rect(screen, BLOCK_GRID_COLOR, ((self.current_piece['x'] + x) * GRID_SIZE, (self.current_piece['y'] + y) * GRID_SIZE, GRID_SIZE, GRID_SIZE), 1)# 繪制信息面板info_x = GRID_WIDTH * GRID_SIZE + 10# 繪制下一個方塊預覽next_text = font.render("下一個:", True, TEXT_COLOR)screen.blit(next_text, (info_x, 20))for y, row in enumerate(self.next_piece['shape']):for x, cell in enumerate(row):if cell:pygame.draw.rect(screen, (200, 0, 0), (info_x + x * GRID_SIZE, 50 + y * GRID_SIZE, GRID_SIZE, GRID_SIZE))pygame.draw.rect(screen, BLOCK_GRID_COLOR, (info_x + x * GRID_SIZE, 50 + y * GRID_SIZE, GRID_SIZE, GRID_SIZE), 1)# 繪制分數和等級score_text = font.render(f"分數: {self.score}", True, TEXT_COLOR)level_text = font.render(f"等級: {self.level}", True, TEXT_COLOR)screen.blit(score_text, (info_x, 150))screen.blit(level_text, (info_x, 180))# 繪制操作說明controls = ["操作說明:","← → : 左右移動","↑ : 旋轉","↓ : 加速下落","空格: 直接落下"]for i, text in enumerate(controls):control_text = font.render(text, True, TEXT_COLOR)screen.blit(control_text, (info_x, 230 + i * 25))# 游戲結束提示if self.game_over:game_over_text = large_font.render("游戲結束!", True, GAME_OVER_COLOR)restart_text = font.render("按R鍵重新開始", True, GAME_OVER_COLOR)screen.blit(game_over_text, (GRID_WIDTH * GRID_SIZE // 2 - 80, GRID_HEIGHT * GRID_SIZE // 2 - 50))screen.blit(restart_text, (GRID_WIDTH * GRID_SIZE // 2 - 70, GRID_HEIGHT * GRID_SIZE // 2))# 主游戲循環
def main():clock = pygame.time.Clock()game = Tetris()while True:# 處理事件for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()if event.type == pygame.KEYDOWN:if game.game_over:if event.key == pygame.K_r:game = Tetris() # 重新開始游戲else:if event.key == pygame.K_LEFT and game.valid_move(game.current_piece, -1):game.current_piece['x'] -= 1elif event.key == pygame.K_RIGHT and game.valid_move(game.current_piece, 1):game.current_piece['x'] += 1elif event.key == pygame.K_DOWN and game.valid_move(game.current_piece, 0, 1):game.current_piece['y'] += 1elif event.key == pygame.K_UP:game.rotate_piece()elif event.key == pygame.K_SPACE:while game.valid_move(game.current_piece, 0, 1):game.current_piece['y'] += 1game.lock_piece()# 自動下落if not game.game_over:current_time = pygame.time.get_ticks() / 1000if current_time - game.fall_time > game.fall_speed:game.fall_time = current_timeif game.valid_move(game.current_piece, 0, 1):game.current_piece['y'] += 1else:game.lock_piece()# 繪制游戲game.draw()pygame.display.update()clock.tick(60)if __name__ == "__main__":main()
四、代碼運行方式
1.代碼運行環境
????????Python 環境 :建議使用 Python 3.6 及以上版本。
????????依賴庫 :需要安裝 pygame 庫,可以使用以下命令進行安裝:
pip install pygame
2.游戲操作
????????左右移動 :按下鍵盤的左箭頭 ← 或右箭頭 → 可以控制方塊左右移動。
????????旋轉 :按下上箭頭 ↑ 可以旋轉方塊。
????????加速下落 :按下下箭頭 ↓ 可以使方塊加速下落。
????????直接落下 :按下空格鍵 Space 可以讓方塊直接落到最底部。
????????重新開始 :游戲結束后,按下 R 鍵可以重新開始游戲。