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

server/2025/3/18 9:23:53/

一、需求分析

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

1.棋盘显示 :

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

2.落子操作 :

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

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

3.胜负判断 :

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

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

4.游戏结束处理 :

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

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

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

5.重新开始和退出 :

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

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

二、关键模块

1. 常量定义

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

2. 初始化

        初始化 Pygame 库。

        创建游戏窗口。

        初始化棋盘状态。

3. 绘制模块

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

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

4. 胜负判断

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

5. 游戏控制

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

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

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

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

三、完整代码

python">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 * dxnew_y = y + i * dyif 0 <= new_x < BOARD_SIZE and 0 <= new_y < BOARD_SIZE and board[new_x][new_y] == player:count += 1else:break# 反向检查for i in range(1, 5):new_x = x - i * dxnew_y = y - i * dyif 0 <= new_x < BOARD_SIZE and 0 <= new_y < BOARD_SIZE and board[new_x][new_y] == player:count += 1else:breakif count >= 5:return Truereturn False# 重置游戏状态
def reset_game():global board, current_player, game_overboard = [[0] * BOARD_SIZE for _ in range(BOARD_SIZE)]current_player = 1game_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 = 30combined_width = max(winner_rect.width, prompt_rect.width) + 2 * paddingcombined_height = winner_rect.height + prompt_rect.height + 3 * paddingrect = 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.poscol = (x - GRID_SIZE // 2) // GRID_SIZErow = (y - GRID_SIZE // 2) // GRID_SIZEif 0 <= col < BOARD_SIZE and 0 <= row < BOARD_SIZE and board[row][col] == 0:board[row][col] = current_playerif 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 = Falsecurrent_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 库

python">pip install pygame

2.运行代码

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

python">python gobang_game.py

3.游戏操作说明

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

4.游戏画面


http://www.ppmy.cn/server/175925.html

相关文章

【AI学习从零至壹】Pytorch神经⽹络

Pytorch神经⽹络 神经网络简介神经元激活函数 神经网络神经⽹络的⼯作过程前向传播(forward) 反向传播(backward)训练神经⽹络 Pytorch搭建并训练神经⽹络神经⽹络构建和训练过程数据预处理构建模型优化器&提取训练数据训练样本 神经网络简介 神经元 在深度学习中&#x…

uniapp+Vue3 开发小程序功能(下载文件)

代码如下&#xff0c;复制粘贴即可食用&#xff1a; <template><view class"container-detail"><view class"example-body" click"openFile(item.url)" v-for"(item, index) in fileList" :key"index">&…

AtCoder Beginner Contest 397 A - D题解

Tasks - OMRON Corporation Programming Contest 2025 (AtCoder Beginner Contest 397) 本文为 AtCoder Beginner Contest 397 A - D题解 题目A: 代码(C): #include <bits/stdc.h>int main() {double n;std::cin >> n;if (n > 38.0) {std::cout << 1;}…

学习threejs,使用MeshLambertMaterial漫反射材质

&#x1f468;‍⚕️ 主页&#xff1a; gis分享者 &#x1f468;‍⚕️ 感谢各位大佬 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍⚕️ 收录于专栏&#xff1a;threejs gis工程师 文章目录 一、&#x1f340;前言1.1 ☘️THREE.MeshLambertMaterial…

计算机网络基础:网络配置与管理

计算机网络基础&#xff1a;网络配置与管理 一、前言二、网络设备配置基础2.1 路由器配置2.1.1 路由器的基本概念2.1.2 路由器的初始配置2.1.3 路由器的接口配置2.1.4 路由配置 2.2 交换机配置2.2.1 交换机的基本概念2.2.2 交换机的初始配置2.2.3 交换机的端口配置2.2.4 VLAN 配…

盘库吧--搜索

网站介绍 网盘资源搜索&#xff0c;包含了百度、夸克、阿里、迅雷、115、天翼、UC 等网盘&#xff0c;支持链接有效性检测。 网站地址 https://panku8.com

如何进行技术选型?

前端技术发展速度快的看法 前端技术的更新换代确实非常快&#xff0c;几乎每年都会有新的框架、工具和最佳实践涌现。从 Vue 2 到 Vue 3、从 Webpack 到 Rspack/Vite、从 Redux 到 Zustand/Recoil&#xff0c;甚至前端工程化、微前端、Server Components 等方向也在快速演进。…

小程序网络大文件缓存方案

分享一个小程序网络大图加载慢的解决方案 用到的相关api getSavedFileList 获取已保存的文件列表&#xff1b;getStorageSync 获取本地缓存&#xff1b;downloadFile 下载网络图片&#xff1b;saveFile 保存文件到本地&#xff1b;setStorage 将数据储存到小程序本地缓存&…