Python 数独小游戏开发指南

我将指导你创建一个视觉精美的数独游戏,包含以下核心功能:

  1. 游戏界面组件
import pygame
import sys

# 初始化
pygame.init()
WIDTH, HEIGHT = 540, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("精美数独")

# 颜色方案
BG_COLOR = (240, 240, 240)  # 背景色
GRID_COLOR = (80, 80, 80)   # 网格线
CELL_COLOR = (255, 255, 255) # 单元格
SELECT_COLOR = (173, 216, 230) # 选中单元格
TEXT_COLOR = (50, 50, 150)   # 数字颜色

  1. 数独生成逻辑
import random

def generate_sudoku(difficulty=0.5):
    """生成数独谜题"""
    base = 3
    side = base*base
    
    # 生成完整解决方案
    def pattern(r, c): 
        return (base*(r%base) + r//base + c) % side
    
    def shuffle(s): 
        return random.sample(s, len(s))
    
    rBase = range(base)
    rows = [g*base + r for g in shuffle(rBase) for r in shuffle(rBase)]
    cols = [g*base + c for g in shuffle(rBase) for c in shuffle(rBase)]
    nums = shuffle(range(1, base*base+1))
    
    board = [[nums[pattern(r, c)] for c in cols] for r in rows]
    
    # 挖空部分格子
    squares = side*side
    empties = int(squares * difficulty)
    for p in random.sample(range(squares), empties):
        board[p//side][p%side] = 0
        
    return board

  1. 游戏核心逻辑
class SudokuGame:
    def __init__(self):
        self.board = generate_sudoku()
        self.selected = None
        self.font = pygame.font.SysFont("Arial", 40)
        self.small_font = pygame.font.SysFont("Arial", 20)
        
    def draw_board(self):
        """绘制数独棋盘"""
        # 绘制背景
        screen.fill(BG_COLOR)
        
        # 绘制网格
        for i in range(10):
            line_width = 3 if i % 3 == 0 else 1
            # 横线
            pygame.draw.line(screen, GRID_COLOR, 
                            (0, i*60), (540, i*60), line_width)
            # 竖线
            pygame.draw.line(screen, GRID_COLOR,
                            (i*60, 0), (i*60, 540), line_width)
        
        # 绘制数字
        for i in range(9):
            for j in range(9):
                if self.board[i][j] != 0:
                    num = self.font.render(str(self.board[i][j]), True, TEXT_COLOR)
                    screen.blit(num, (j*60 + 22, i*60 + 15))
        
        # 绘制选中框
        if self.selected:
            x, y = self.selected
            pygame.draw.rect(screen, SELECT_COLOR, (y*60, x*60, 60, 60), 3)
    
    def handle_click(self, pos):
        """处理鼠标点击"""
        x, y = pos
        if y < 540:  # 确保点击在棋盘范围内
            self.selected = (y // 60, x // 60)
    
    def place_number(self, num):
        """放置数字"""
        if self.selected:
            i, j = self.selected
            self.board[i][j] = num

  1. 主游戏循环
def main():
    game = SudokuGame()
    clock = pygame.time.Clock()
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            
            if event.type == pygame.MOUSEBUTTONDOWN:
                game.handle_click(pygame.mouse.get_pos())
            
            if event.type == pygame.KEYDOWN:
                if event.key in range(pygame.K_1, pygame.K_9+1):
                    game.place_number(event.key - pygame.K_0)
                elif event.key == pygame.K_DELETE:
                    game.place_number(0)
        
        game.draw_board()
        pygame.display.flip()
        clock.tick(30)

if __name__ == "__main__":
    main()

功能扩展建议

  1. 难度选择系统
def create_difficulty_buttons():
    buttons = [
        {"text": "简单", "rect": pygame.Rect(50, 550, 100, 40)},
        {"text": "中等", "rect": pygame.Rect(170, 550, 100, 40)},
        {"text": "困难", "rect": pygame.Rect(290, 550, 100, 40)},
        {"text": "专家", "rect": pygame.Rect(410, 550, 100, 40)}
    ]
    return buttons

  1. 验证与提示功能
def is_valid(board, num, pos):
    """检查数字放置是否有效"""
    # 检查行
    for i in range(9):
        if board[pos[0]][i] == num and pos[1] != i:
            return False
    
    # 检查列
    for i in range(9):
        if board[i][pos[1]] == num and pos[0] != i:
            return False
    
    # 检查3x3宫格
    box_x = pos[1] // 3
    box_y = pos[0] // 3
    
    for i in range(box_y*3, box_y*3 + 3):
        for j in range(box_x*3, box_x*3 + 3):
            if board[i][j] == num and (i,j) != pos:
                return False
                
    return True

视觉效果优化技巧

  1. 渐变背景
def draw_gradient_background():
    for i in range(HEIGHT):
        color_val = 200 + int(55 * i/HEIGHT)
        pygame.draw.line(screen, (color_val, color_val, color_val), (0, i), (WIDTH, i))

  1. 单元格动画效果
def animate_cell(cell_pos):
    """为单元格添加点击动画"""
    x, y = cell_pos[1]*60, cell_pos[0]*60
    for size in range(0, 30, 2):
        pygame.draw.rect(screen, (200, 230, 255), 
                        (x+15-size//2, y+15-size//2, 30+size, 30+size), 2)
        pygame.display.flip()
        pygame.time.delay(10)

  1. 数字输入效果
def draw_number_input_effect(num, pos):
    """数字输入动画"""
    x, y = pos[1]*60 + 22, pos[0]*60 + 15
    for size in range(10, 40, 2):
        temp_surf = pygame.Surface((size, size), pygame.SRCALPHA)
        text = pygame.font.SysFont("Arial", size).render(str(num), True, (*TEXT_COLOR, size*6))
        temp_surf.blit(text, (0,0))
        screen.blit(temp_surf, (x-size//2, y-size//2))
        pygame.display.flip()
        pygame.time.delay(5)

完整实现步骤

  1. 安装依赖:pip install pygame numpy
  2. 创建Python文件(如sudoku_game.py
  3. 复制上述代码片段并整合
  4. 添加游戏重置、胜利检测功能
  5. 实现计时器和错误计数功能
  6. 添加背景音乐和音效(使用pygame.mixer

这个实现包含:

  • 响应式界面设计
  • 智能数独生成算法
  • 视觉反馈系统
  • 用户友好交互
  • 可扩展的架构设计

你可以通过调整颜色方案、添加动画效果和优化算法来进一步提升游戏体验!

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐