Pygame开发五子棋之人机对战游戏

devtools/2024/10/20 8:49:26/
引言

Pygame是一个基于Python的开源游戏开发库,它包含了丰富的多媒体功能,尤其是针对游戏开发所需的各种组件。如果你对游戏开发感兴趣,但又不想从底层开始编写所有东西,Pygame可以成为一个理想的起点。本文将介绍Pygame的基本概念,安装步骤,以及如何通过一个简单的入门案例开始你的游戏开发之旅。

一、Pygame简介

Pygame建立在SDL(Simple DirectMedia Layer)之上,提供了对视频、音频、键盘和鼠标事件的支持。它包含了一系列模块,如pygame.display用于显示窗口,pygame.sprite用于处理游戏中的精灵和碰撞检测,pygame.mixer用于音效和音乐播放,等等。这些模块大大简化了游戏开发流程,让开发者能够专注于游戏逻辑而不是底层细节。

二、Pygame的安装

确保你已经安装了Python环境。Pygame可以通过Python的包管理器pip来安装。在命令行中执行以下命令:

pip install pygame

如果你使用的是Python 3,你可能需要使用pip3代替pip

三、基本使用

Pygame的基本使用涉及初始化、事件循环、更新屏幕和退出处理四个主要步骤。下面是一个简单的例子,展示如何使用Pygame创建一个空白的游戏窗口。

python">import pygame
import sys# 初始化Pygame
pygame.init()# 设置窗口大小
screen = pygame.display.set_mode((800, 600))# 设置窗口标题
pygame.display.set_caption("My First Pygame Window")# 游戏主循环
running = True
while running:for event in pygame.event.get():if event.type == pygame.QUIT:running = False# 更新屏幕screen.fill((255, 255, 255))  # 填充白色背景pygame.display.flip()# 退出Pygame
pygame.quit()
sys.exit()
四、五子棋游戏案例

以下为五子棋游戏案例的完整代码:

python">"""五子棋之人机对战"""
import sys
import random
import pygame
from pygame.locals import *
import pygame.gfxdraw
from collections import namedtupleChessman = namedtuple('Chessman', 'Name Value Color')
Point = namedtuple('Point', 'X Y')BLACK_CHESSMAN = Chessman('黑子', 1, (45, 45, 45))
WHITE_CHESSMAN = Chessman('白子', 2, (219, 219, 219))offset = [(1, 0), (0, 1), (1, 1), (1, -1)]class Checkerboard:def __init__(self, line_points):self._line_points = line_pointsself._checkerboard = [[0] * line_points for _ in range(line_points)]def _get_checkerboard(self):return self._checkerboardcheckerboard = property(_get_checkerboard)# 判断是否可落子def can_drop(self, point):return self._checkerboard[point.Y][point.X] == 0def drop(self, chessman, point):"""落子:param chessman::param point:落子位置:return:若该子落下之后即可获胜,则返回获胜方,否则返回 None"""print(f'{chessman.Name} ({point.X}, {point.Y})')self._checkerboard[point.Y][point.X] = chessman.Valueif self._win(point):print(f'{chessman.Name}获胜')return chessman# 判断是否赢了def _win(self, point):cur_value = self._checkerboard[point.Y][point.X]for os in offset:if self._get_count_on_direction(point, cur_value, os[0], os[1]):return Truedef _get_count_on_direction(self, point, value, x_offset, y_offset):count = 1for step in range(1, 5):x = point.X + step * x_offsety = point.Y + step * y_offsetif 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:count += 1else:breakfor step in range(1, 5):x = point.X - step * x_offsety = point.Y - step * y_offsetif 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:count += 1else:breakreturn count >= 5SIZE = 30  # 棋盘每个点时间的间隔
Line_Points = 19  # 棋盘每行/每列点数
Outer_Width = 20  # 棋盘外宽度
Border_Width = 4  # 边框宽度
Inside_Width = 4  # 边框跟实际的棋盘之间的间隔
Border_Length = SIZE * (Line_Points - 1) + Inside_Width * 2 + Border_Width  # 边框线的长度
Start_X = Start_Y = Outer_Width + int(Border_Width / 2) + Inside_Width  # 网格线起点(左上角)坐标
SCREEN_HEIGHT = SIZE * (Line_Points - 1) + Outer_Width * 2 + Border_Width + Inside_Width * 2  # 游戏屏幕的高
SCREEN_WIDTH = SCREEN_HEIGHT + 200  # 游戏屏幕的宽Stone_Radius = SIZE // 2 - 3  # 棋子半径
Stone_Radius2 = SIZE // 2 + 3
Checkerboard_Color = (0xE3, 0x92, 0x65)  # 棋盘颜色
BLACK_COLOR = (0, 0, 0)
WHITE_COLOR = (255, 255, 255)
RED_COLOR = (200, 30, 30)
BLUE_COLOR = (30, 30, 200)RIGHT_INFO_POS_X = SCREEN_HEIGHT + Stone_Radius2 * 2 + 10def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):imgText = font.render(text, True, fcolor)screen.blit(imgText, (x, y))def main():pygame.init()screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))pygame.display.set_caption('五子棋')font1 = pygame.font.SysFont('SimHei', 32)font2 = pygame.font.SysFont('SimHei', 72)fwidth, fheight = font2.size('黑方获胜')checkerboard = Checkerboard(Line_Points)cur_runner = BLACK_CHESSMANwinner = Nonecomputer = AI(Line_Points, WHITE_CHESSMAN)black_win_count = 0white_win_count = 0while True:for event in pygame.event.get():if event.type == QUIT:sys.exit()elif event.type == KEYDOWN:if event.key == K_RETURN:if winner is not None:winner = Nonecur_runner = BLACK_CHESSMANcheckerboard = Checkerboard(Line_Points)computer = AI(Line_Points, WHITE_CHESSMAN)elif event.type == MOUSEBUTTONDOWN:if winner is None:pressed_array = pygame.mouse.get_pressed()if pressed_array[0]:mouse_pos = pygame.mouse.get_pos()click_point = _get_clickpoint(mouse_pos)if click_point is not None:if checkerboard.can_drop(click_point):winner = checkerboard.drop(cur_runner, click_point)if winner is None:cur_runner = _get_next(cur_runner)computer.get_opponent_drop(click_point)AI_point = computer.AI_drop()winner = checkerboard.drop(cur_runner, AI_point)if winner is not None:white_win_count += 1cur_runner = _get_next(cur_runner)else:black_win_count += 1else:print('超出棋盘区域')# 画棋盘_draw_checkerboard(screen)# 画棋盘上已有的棋子for i, row in enumerate(checkerboard.checkerboard):for j, cell in enumerate(row):if cell == BLACK_CHESSMAN.Value:_draw_chessman(screen, Point(j, i), BLACK_CHESSMAN.Color)elif cell == WHITE_CHESSMAN.Value:_draw_chessman(screen, Point(j, i), WHITE_CHESSMAN.Color)_draw_left_info(screen, font1, cur_runner, black_win_count, white_win_count)if winner:print_text(screen, font2, (SCREEN_WIDTH - fwidth)//2, (SCREEN_HEIGHT - fheight)//2, winner.Name + '获胜', RED_COLOR)pygame.display.flip()def _get_next(cur_runner):if cur_runner == BLACK_CHESSMAN:return WHITE_CHESSMANelse:return BLACK_CHESSMAN# 画棋盘
def _draw_checkerboard(screen):# 填充棋盘背景色screen.fill(Checkerboard_Color)# 画棋盘网格线外的边框pygame.draw.rect(screen, BLACK_COLOR, (Outer_Width, Outer_Width, Border_Length, Border_Length), Border_Width)# 画网格线for i in range(Line_Points):pygame.draw.line(screen, BLACK_COLOR,(Start_Y, Start_Y + SIZE * i),(Start_Y + SIZE * (Line_Points - 1), Start_Y + SIZE * i),1)for j in range(Line_Points):pygame.draw.line(screen, BLACK_COLOR,(Start_X + SIZE * j, Start_X),(Start_X + SIZE * j, Start_X + SIZE * (Line_Points - 1)),1)# 画星位和天元for i in (3, 9, 15):for j in (3, 9, 15):if i == j == 9:radius = 5else:radius = 3# pygame.draw.circle(screen, BLACK, (Start_X + SIZE * i, Start_Y + SIZE * j), radius)pygame.gfxdraw.aacircle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR)pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR)# 画棋子
def _draw_chessman(screen, point, stone_color):# pygame.draw.circle(screen, stone_color, (Start_X + SIZE * point.X, Start_Y + SIZE * point.Y), Stone_Radius)pygame.gfxdraw.aacircle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color)pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color)# 画左侧信息显示
def _draw_left_info(screen, font, cur_runner, black_win_count, white_win_count):_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + Stone_Radius2), BLACK_CHESSMAN.Color)_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + Stone_Radius2 * 4), WHITE_CHESSMAN.Color)print_text(screen, font, RIGHT_INFO_POS_X, Start_X + 3, '玩家', BLUE_COLOR)print_text(screen, font, RIGHT_INFO_POS_X, Start_X + Stone_Radius2 * 3 + 3, '电脑', BLUE_COLOR)print_text(screen, font, SCREEN_HEIGHT, SCREEN_HEIGHT - Stone_Radius2 * 8, '战况:', BLUE_COLOR)_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, SCREEN_HEIGHT - int(Stone_Radius2 * 4.5)), BLACK_CHESSMAN.Color)_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, SCREEN_HEIGHT - Stone_Radius2 * 2), WHITE_CHESSMAN.Color)print_text(screen, font, RIGHT_INFO_POS_X, SCREEN_HEIGHT - int(Stone_Radius2 * 5.5) + 3, f'{black_win_count} 胜', BLUE_COLOR)print_text(screen, font, RIGHT_INFO_POS_X, SCREEN_HEIGHT - Stone_Radius2 * 3 + 3, f'{white_win_count} 胜', BLUE_COLOR)def _draw_chessman_pos(screen, pos, stone_color):pygame.gfxdraw.aacircle(screen, pos[0], pos[1], Stone_Radius2, stone_color)pygame.gfxdraw.filled_circle(screen, pos[0], pos[1], Stone_Radius2, stone_color)# 根据鼠标点击位置,返回游戏区坐标
def _get_clickpoint(click_pos):pos_x = click_pos[0] - Start_Xpos_y = click_pos[1] - Start_Yif pos_x < -Inside_Width or pos_y < -Inside_Width:return Nonex = pos_x // SIZEy = pos_y // SIZEif pos_x % SIZE > Stone_Radius:x += 1if pos_y % SIZE > Stone_Radius:y += 1if x >= Line_Points or y >= Line_Points:return Nonereturn Point(x, y)class AI:def __init__(self, line_points, chessman):self._line_points = line_pointsself._my = chessmanself._opponent = BLACK_CHESSMAN if chessman == WHITE_CHESSMAN else WHITE_CHESSMANself._checkerboard = [[0] * line_points for _ in range(line_points)]def get_opponent_drop(self, point):self._checkerboard[point.Y][point.X] = self._opponent.Valuedef AI_drop(self):point = Nonescore = 0for i in range(self._line_points):for j in range(self._line_points):if self._checkerboard[j][i] == 0:_score = self._get_point_score(Point(i, j))if _score > score:score = _scorepoint = Point(i, j)elif _score == score and _score > 0:r = random.randint(0, 100)if r % 2 == 0:point = Point(i, j)self._checkerboard[point.Y][point.X] = self._my.Valuereturn pointdef _get_point_score(self, point):score = 0for os in offset:score += self._get_direction_score(point, os[0], os[1])return scoredef _get_direction_score(self, point, x_offset, y_offset):count = 0   # 落子处我方连续子数_count = 0  # 落子处对方连续子数space = None   # 我方连续子中有无空格_space = None  # 对方连续子中有无空格both = 0    # 我方连续子两端有无阻挡_both = 0   # 对方连续子两端有无阻挡# 如果是 1 表示是边上是我方子,2 表示敌方子flag = self._get_stone_color(point, x_offset, y_offset, True)if flag != 0:for step in range(1, 6):x = point.X + step * x_offsety = point.Y + step * y_offsetif 0 <= x < self._line_points and 0 <= y < self._line_points:if flag == 1:if self._checkerboard[y][x] == self._my.Value:count += 1if space is False:space = Trueelif self._checkerboard[y][x] == self._opponent.Value:_both += 1breakelse:if space is None:space = Falseelse:break   # 遇到第二个空格退出elif flag == 2:if self._checkerboard[y][x] == self._my.Value:_both += 1breakelif self._checkerboard[y][x] == self._opponent.Value:_count += 1if _space is False:_space = Trueelse:if _space is None:_space = Falseelse:breakelse:# 遇到边也就是阻挡if flag == 1:both += 1elif flag == 2:_both += 1if space is False:space = Noneif _space is False:_space = None_flag = self._get_stone_color(point, -x_offset, -y_offset, True)if _flag != 0:for step in range(1, 6):x = point.X - step * x_offsety = point.Y - step * y_offsetif 0 <= x < self._line_points and 0 <= y < self._line_points:if _flag == 1:if self._checkerboard[y][x] == self._my.Value:count += 1if space is False:space = Trueelif self._checkerboard[y][x] == self._opponent.Value:_both += 1breakelse:if space is None:space = Falseelse:break   # 遇到第二个空格退出elif _flag == 2:if self._checkerboard[y][x] == self._my.Value:_both += 1breakelif self._checkerboard[y][x] == self._opponent.Value:_count += 1if _space is False:_space = Trueelse:if _space is None:_space = Falseelse:breakelse:# 遇到边也就是阻挡if _flag == 1:both += 1elif _flag == 2:_both += 1score = 0if count == 4:score = 10000elif _count == 4:score = 9000elif count == 3:if both == 0:score = 1000elif both == 1:score = 100else:score = 0elif _count == 3:if _both == 0:score = 900elif _both == 1:score = 90else:score = 0elif count == 2:if both == 0:score = 100elif both == 1:score = 10else:score = 0elif _count == 2:if _both == 0:score = 90elif _both == 1:score = 9else:score = 0elif count == 1:score = 10elif _count == 1:score = 9else:score = 0if space or _space:score /= 2return score# 判断指定位置处在指定方向上是我方子、对方子、空def _get_stone_color(self, point, x_offset, y_offset, next):x = point.X + x_offsety = point.Y + y_offsetif 0 <= x < self._line_points and 0 <= y < self._line_points:if self._checkerboard[y][x] == self._my.Value:return 1elif self._checkerboard[y][x] == self._opponent.Value:return 2else:if next:return self._get_stone_color(Point(x, y), x_offset, y_offset, False)else:return 0else:return 0
if __name__ == '__main__':main()
五、游戏代码运行效果图

在这里插入图片描述

结语

Pygame是一个强大的游戏开发库,适合初学者和有经验的开发者。通过本文,你已经了解了Pygame的基本安装和使用方法,以及如何创建一个简单的游戏。希望这能激发你进一步探索游戏开发的兴趣,创造出属于自己的游戏作品!


http://www.ppmy.cn/devtools/59357.html

相关文章

Classifier-Free Guidance (CFG) Scale in Stable Diffusion

1.Classifier-Free Guidance Scale in Stable Diffusion 笔记来源&#xff1a; 1.How does Stable Diffusion work? 2.Classifier-Free Diffusion Guidance 3.Guide to Stable Diffusion CFG scale (guidance scale) parameter 1.1 Classifier Guidance Scale 分类器引导是…

“解锁物流新纪元:深入探索‘沂路畅通‘分布式协作平台“

"解锁物流新纪元&#xff1a;深入探索沂路畅通分布式协作平台" 在21世纪的数字浪潮中&#xff0c;物流行业作为连接生产与消费的关键纽带&#xff0c;其重要性不言而喻。然而&#xff0c;随着市场规模的持续扩大和消费者需求的日益多样化&#xff0c;传统物流模式已…

Kithara与OpenCV (二)

Kithara使用OpenCV QT 进行特征检测 目录 Kithara使用OpenCV QT 进行特征检测OpenCV 特征检测简介Qt应用框架简介项目说明关键代码抖动测试测试平台&#xff1a;测试结果&#xff1a; 开源源码 OpenCV 特征检测简介 OpenCV是一个开源的计算机视觉库&#xff0c;提供了各种图…

深入探索Element UI中el-input与el-select的非空校验艺术

在前端开发的浩瀚星空中&#xff0c;Element UI犹如一颗璀璨的明星&#xff0c;以其丰富的组件库和优雅的设计赢得了广大开发者的青睐。其中&#xff0c;el-input与el-select作为用户输入信息的两大基石&#xff0c;其非空校验功能更是确保数据完整性和用户体验的重要一环。今天…

Memcached负载均衡:揭秘高效缓存分发策略

标题&#xff1a;Memcached负载均衡&#xff1a;揭秘高效缓存分发策略 在分布式缓存系统中&#xff0c;Memcached通过负载均衡技术来提高缓存效率和系统吞吐量。负载均衡确保了缓存请求能够均匀地分配到多个缓存节点上&#xff0c;从而防止任何一个节点过载。本文将深入探讨Me…

Okhttp实现原理

OkHttp 是一个高效的 HTTP 客户端库&#xff0c;广泛应用于 Android 和 Java 应用中。它提供了简洁的 API&#xff0c;支持多种协议&#xff0c;如 HTTP/1.x 和 HTTP/2&#xff0c;并且内置了缓存和重试机制。下面是结合源码分析的 OkHttp 的实现原理&#xff1a; 核心组件 O…

C语言-分支与循环(2)

目录 1、while循环 1.1 if 和 while 的对比 1.2 while 语句的执行流程 6.3 while循环简单例题 2、for 循环 2.1 语法形式 2.2 for循环与while循环对比 2.3 for循环的执行流程 2.4 for循环的简单例题 2.5 扩展&#xff1a;for循环的初始化&#xff0c;判断&#xff0c;…

图数据库 - Neo4j简介

深入理解 Neo4j 与 Cypher 语法 什么是 Neo4j Neo4j 是一个基于图的数据库管理系统&#xff0c;它使用图形理论来表示数据关系。这种数据库与传统的关系型数据库不同&#xff0c;它更适合处理高度互联的数据结构。 基本概念 图&#xff1a;在 Neo4j 中&#xff0c;数据以图的…