五子棋小游戏-简单开发版

发布于:2025-03-17 ⋅ 阅读:(15) ⋅ 点赞:(0)

一、需求分析

开发一个基于 Pygame 库的五子棋小游戏,允许两名玩家在棋盘上轮流落子,当有一方达成五子连珠时游戏结束,显示获胜信息,并提供退出游戏和重新开始游戏的操作选项。

1.棋盘显示 :

        显示一个 15x15 的五子棋棋盘,棋盘背景为木头淡黄色,网格线为黑色。

2.落子操作 :

        玩家通过鼠标点击棋盘上的交叉点来落子,黑子和白子轮流交替落子。

        只有在空的交叉点上才能落子。

3.胜负判断 :

        每次落子后,检查是否有五子连珠的情况(横向、纵向、正斜向、反斜向)。

        如果有一方达成五子连珠,则判定该方获胜。

4.游戏结束处理 :

        游戏结束时,在屏幕中央显示获胜信息(如“Player 1 Win!” 或 “Player 2 Win!”)。

        同时显示操作提示,告知玩家可以按 “Q” 键退出游戏,按 “N” 键重新开始游戏。

        显示一个半透明的黑色提示框,将获胜信息和操作提示包含在内。

5.重新开始和退出 :

        游戏结束后,玩家可以按 “Q” 键退出游戏,按 “N” 键重新开始游戏。

        重新开始游戏时,清空棋盘,重置当前玩家为黑子先手。

二、关键模块

1. 常量定义

        定义游戏中使用的各种常量,如棋盘大小、网格大小、窗口尺寸、颜色、字体等。

2. 初始化

        初始化 Pygame 库。

        创建游戏窗口。

        初始化棋盘状态。

3. 绘制模块

        绘制棋盘:使用木头淡黄色填充屏幕,并绘制黑色的网格线。

        绘制棋子:根据棋盘状态,在相应位置绘制黑子和白子。

4. 胜负判断

        检查当前落子位置是否形成五子连珠,分别从横向、纵向、正斜向、反斜向四个方向进行检查。

5. 游戏控制

        处理鼠标点击事件,实现落子操作。

        处理键盘事件,实现退出游戏和重新开始游戏的功能。

        控制游戏的主循环,更新游戏状态。 6. 提示信息显示模块

        在游戏结束时,显示获胜信息和操作提示,并绘制半透明的提示框。

三、完整代码

import pygame
import sys

# 初始化 Pygame
pygame.init()

# 定义常量
BOARD_SIZE = 15
GRID_SIZE = 40
WINDOW_WIDTH = GRID_SIZE * (BOARD_SIZE + 1)
WINDOW_HEIGHT = GRID_SIZE * (BOARD_SIZE + 1)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 定义木头淡黄色
WOOD_COLOR = (205, 133, 63) 
BLUE = (0, 0, 255)
FONT = pygame.font.Font(None, 36)  

# 创建游戏窗口
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("五子棋小游戏")

# 初始化棋盘
board = [[0] * BOARD_SIZE for _ in range(BOARD_SIZE)]

# 绘制棋盘
def draw_board():
    # 使用木头淡黄色填充屏幕
    screen.fill(WOOD_COLOR)  
    for i in range(BOARD_SIZE):
        pygame.draw.line(screen, BLACK, (GRID_SIZE, GRID_SIZE * (i + 1)), (GRID_SIZE * BOARD_SIZE, GRID_SIZE * (i + 1)), 2)
        pygame.draw.line(screen, BLACK, (GRID_SIZE * (i + 1), GRID_SIZE), (GRID_SIZE * (i + 1), GRID_SIZE * BOARD_SIZE), 2)

# 绘制棋子
def draw_pieces():
    for i in range(BOARD_SIZE):
        for j in range(BOARD_SIZE):
            if board[i][j] == 1:
                pygame.draw.circle(screen, BLACK, (GRID_SIZE * (j + 1), GRID_SIZE * (i + 1)), 18)
            elif board[i][j] == 2:
                pygame.draw.circle(screen, WHITE, (GRID_SIZE * (j + 1), GRID_SIZE * (i + 1)), 18)

# 检查是否有五子连珠
def check_win(x, y, player):
    directions = [(1, 0), (0, 1), (1, 1), (1, -1)]
    for dx, dy in directions:
        count = 1
        # 正向检查
        for i in range(1, 5):
            new_x = x + i * dx
            new_y = y + i * dy
            if 0 <= new_x < BOARD_SIZE and 0 <= new_y < BOARD_SIZE and board[new_x][new_y] == player:
                count += 1
            else:
                break
        # 反向检查
        for i in range(1, 5):
            new_x = x - i * dx
            new_y = y - i * dy
            if 0 <= new_x < BOARD_SIZE and 0 <= new_y < BOARD_SIZE and board[new_x][new_y] == player:
                count += 1
            else:
                break
        if count >= 5:
            return True
    return False

# 重置游戏状态
def reset_game():
    global board, current_player, game_over
    board = [[0] * BOARD_SIZE for _ in range(BOARD_SIZE)]
    current_player = 1
    game_over = False

# 显示获胜信息和操作提示
def show_winner_info(player):
    winner_text = FONT.render(f"Player {player} Win!", True, WHITE)
    prompt_text = FONT.render("Press Q to Quit, Press N to Restart", True, WHITE)

    # 创建半透明的矩形框
    winner_rect = winner_text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 - 30))
    prompt_rect = prompt_text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 + 30))

    # 调整内边距以确保提示框足够大
    padding = 30
    combined_width = max(winner_rect.width, prompt_rect.width) + 2 * padding
    combined_height = winner_rect.height + prompt_rect.height + 3 * padding
    rect = pygame.Rect(winner_rect.x - padding, winner_rect.y - padding, combined_width, combined_height)
    rect.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)

    # 创建一个带有透明度的表面
    surface = pygame.Surface((rect.width, rect.height), pygame.SRCALPHA)
    surface.fill((0, 0, 0, 128))  # 半透明黑色

    screen.blit(surface, (rect.x, rect.y))
    screen.blit(winner_text, (rect.centerx - winner_rect.width // 2, rect.centery - winner_rect.height - padding // 2))
    screen.blit(prompt_text, (rect.centerx - prompt_rect.width // 2, rect.centery + padding // 2))
    pygame.display.flip()

# 主游戏循环
current_player = 1
game_over = False
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
            x, y = event.pos
            col = (x - GRID_SIZE // 2) // GRID_SIZE
            row = (y - GRID_SIZE // 2) // GRID_SIZE
            if 0 <= col < BOARD_SIZE and 0 <= row < BOARD_SIZE and board[row][col] == 0:
                board[row][col] = current_player
                if check_win(row, col, current_player):
                    print(f"Player {current_player} Win!")
                    # 先显示最后一个子
                    draw_board()
                    draw_pieces()
                    pygame.display.flip()
                    # 显示获胜信息和操作提示
                    show_winner_info(current_player)
                    game_over = True
                    # 进入等待状态,直到用户按下 Q 或者 N 键
                    while game_over:
                        for inner_event in pygame.event.get():
                            if inner_event.type == pygame.QUIT:
                                pygame.quit()
                                sys.exit()
                            elif inner_event.type == pygame.KEYDOWN:
                                if inner_event.key == pygame.K_q:
                                    pygame.quit()
                                    sys.exit()
                                elif inner_event.key == pygame.K_n:
                                    reset_game()
                                    game_over = False
                current_player = 3 - current_player  # 切换玩家
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_q:
                pygame.quit()
                sys.exit()
            elif event.key == pygame.K_n:
                reset_game()

    if not game_over:
        draw_board()
        draw_pieces()
        pygame.display.flip()

四、代码运行方式

1.代码运行环境

        Python 3.x

        Pygame 库

pip install pygame

2.运行代码

        将上述代码保存为 gobang_game.py 文件,然后在终端中运行以下命令:

python gobang_game.py

3.游戏操作说明

        游戏开始后,黑子先手,玩家通过鼠标点击棋盘上的交叉点落子。
        当有一方达成五子连珠时,游戏结束,屏幕中央会显示获胜信息和操作提示。
        按 “Q” 键退出游戏,按 “N” 键重新开始游戏。

4.游戏画面