前言:
我这个五子棋作业是参考:
https://blog.csdn.net/wudingan/article/details/106812722
(实现了完整的人机对战,通俗易懂。)

我只是在此基础上做修改增加加入进入游戏界面,人人对战,回到主界面,重新开始游戏的一些小功能

使用pygame
主界面效果图
这个主界面是ps上去的,主要是为了好看,我们需要实现,点击,人机对战和人人对战两个按钮进入相应的界面,这个就需要在代码中添加这两个按钮对应的x,y范围。

1.导入必要库以及定义一些全局变量

导入必要库以及定义一些全局变量

import pygame
from pygame.locals import *
import pygame.gfxdraw
import traceback
import sys
import random
from collections import namedtuple
# 画棋盘
SIZE = 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 = (234, 215, 176)  # 棋盘颜色,RGB值
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 + 10Chessman = 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)]
pygame.init()
#背景音乐
pygame.mixer.init()
pygame.mixer_music.load('望江南.mp3')
pygame.mixer_music.play()

2.定义一些需要的函数

#画棋盘
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(19): # 画网格线pygame.draw.line(screen, BLACK_COLOR,(26, 26 + 30 * i),(26 + 30 * 18, 26 + 30 * i),1)for j in range(19):pygame.draw.line(screen, BLACK_COLOR, (26 + 30 * j, 26),(26 + 30 * j, 26 + 30 * 18),1)for i in (3, 9, 15): # 画星位和天元for j in (3, 9, 15):if i == j == 9:radius = 5else:radius = 3pygame.gfxdraw.aacircle(screen, 26 + 30 * i, 26 + 30 * j, radius, BLACK_COLOR)pygame.gfxdraw.filled_circle(screen, 26 + 30 * i, 26 + 30 * j, radius, BLACK_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 _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, 26 + 30 * point.X, 26 + 30 * point.Y, Stone_Radius, stone_color)pygame.gfxdraw.filled_circle(screen, 26 + 30 * point.X, 26 + 30 * point.Y, Stone_Radius, stone_color)
#文本信息提示
def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):imgText = font.render(text, True, fcolor)screen.blit(imgText, (x, y))
def _draw_left_info_begin(screen, font):    #右侧信息提示print_text(screen, font, 324, 170, '五子棋', BLUE_COLOR)print_text(screen, font, 310, 270, '人人对战', BLUE_COLOR)print_text(screen, font, 310, 370, '人机对战', BLUE_COLOR)
def _draw_left_info_every(screen, font): #人人对战print_text(screen, font, 610, 50, '当前状态', BLUE_COLOR)#print_text(screen, font, 630, 270, '悔棋', BLUE_COLOR)print_text(screen, font, 610, 333, '重新开始', BLUE_COLOR)print_text(screen, font, 600, 400, '回到主界面', BLUE_COLOR)
def _draw_left_info_computer(screen,font): #人机对战_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + Stone_Radius2), WHITE_CHESSMAN.Color)_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + Stone_Radius2 * 4), BLACK_CHESSMAN.Color)print_text(screen, font, 638, 29, '玩家', BLUE_COLOR)print_text(screen, font, 638, 83, '电脑', BLUE_COLOR)print_text(screen, font, 610, 333, '重新开始', BLUE_COLOR)print_text(screen, font, 600, 400, '回到主界面', BLUE_COLOR)
font1 = pygame.font.SysFont('SimHei', 32)  # 字体:黑体,32号
font2 = pygame.font.SysFont('SimHei', 72)  # 字体:黑体,72号
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))  # 游戏屏幕的高,宽
# 根据鼠标点击位置,返回游戏区坐标
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)
#提示当前是谁下棋 ,人人对战时需要
def remind_chess(cur_runner):if cur_runner == BLACK_CHESSMAN:pygame.draw.rect(screen, Checkerboard_Color, [630, 100, 150, 50])  # 先把上一次的类容用一个矩形覆盖print_text(screen, font1, 630, 100, '黑子', BLUE_COLOR)else:pygame.draw.rect(screen, Checkerboard_Color, [630, 100, 150, 50])print_text(screen, font1, 630, 100, '白子', BLUE_COLOR)#黑白棋轮流下
def _get_next(cur_runner):if cur_runner == BLACK_CHESSMAN:return WHITE_CHESSMANelse:return BLACK_CHESSMAN
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): #落子print(f'{chessman.Name} ({point.X}, {point.Y})') # 把黑棋/白棋落子的坐标打印出来self._checkerboard[point.Y][point.X] = chessman.Value   #point:落子位置# 打印获胜方出来if self._win(point):print(f'{chessman.Name}获胜')return chessman #return:若该子落下之后即可获胜,则返回获胜方,否则返回 None# 判断是否赢了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 True# 数步数def _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 >= 5

3.主界面实现

主界面实现

#初始状态,进入游戏界面
def enter_the_game():screen.fill(Checkerboard_Color)#_draw_left_info_begin(screen, font1)  #初始界面Background = pygame.image.load("new_backgroud_begin.jpg").convert_alpha()  #图片填充screen.blit(Background, (0, 0))pygame.display.flip()clock = pygame.time.Clock()while True:for event in pygame.event.get():# 点击x则关闭窗口if event.type == pygame.QUIT:pygame.quit()exit()# 点击窗口里面类容则完成相应指令elif event.type == MOUSEBUTTONDOWN:if event.button == 1:x, y = event.pos[0], event.pos[1]_draw_checkerboard(screen)  #画棋盘pygame.display.flip()  # 刷新屏幕显示出来# 如果点击‘人人对战’if 210 < x < 500 and 270 < y < 360:# 取消阻止running = True# 播放音效# button_sound.play(0)# 重新开始person_computer()person_person()print("人机对战")# 点击‘人机对战’elif 210 < x < 500 and 370 < y < 460:person_person()print("人人对战")clock.tick(60)

4.人人对战

人人对战

def person_person(): #人人对战fwidth, fheight = font2.size('黑子获胜')checkerboard = Checkerboard(Line_Points)cur_runner = WHITE_CHESSMAN    #玩家一#remind_chess(cur_runner)winner = None# 设置黑白双方初始连子为0black_win_count = 0white_win_count = 0while True:for event in pygame.event.get():if event.type == QUIT:sys.exit()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:  # 检测鼠标是否在棋盘内点击 #玩家1if checkerboard.can_drop(click_point):winner = checkerboard.drop(cur_runner, click_point)if winner is None:  # 再次判断是否有胜出# 每下一次检测一次cur_runner = _get_next(cur_runner)  #换成玩家2下棋if click_point is not None:  # 检测鼠标是否在棋盘内点击if checkerboard.can_drop(click_point):#落子winner = checkerboard.drop(cur_runner, click_point)if winner is not None:  #再次检测是否有胜出white_win_count += 1cur_runner = _get_next(cur_runner)else:black_win_count += 1x, y = event.pos[0], event.pos[1]if 610 < x < 800 and 333 < y < 360:  # 点击重新开始person_person()elif 600 < x < 800 and 400 < y < 500:  # 点击‘回到主界面’main()#elif 630 < x < 800 and 270 < y < 500:  # 点击‘悔棋’#main()_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)remind_chess(cur_runner)_draw_left_info_every(screen, font1)if winner:print_text(screen, font2, (SCREEN_WIDTH - fwidth) // 2, (SCREEN_HEIGHT - fheight) // 2, winner.Name + '获胜',RED_COLOR)pygame.display.flip()

5.人机对战

人机对战

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 += 1# 下面这一串score(分数)的含义:评估棋格获胜分数。# 使计算机计算获胜分值越高的棋格,就能确定能让自己的棋子最有可能达成联机的位置,也就是最佳进攻位置,# 而一旦计算机能确定自己的最高分值的位置,计算机就具备了进攻能力。# 同理,计算机能计算出玩家的最大分值位置,并抢先玩家获得该位置,这样计算机就具有了防御的能力。# 在计算机下棋之前,会计算空白棋格上的获胜分数,根据分数高低获取最佳位置。# 计算机会将棋子下在获胜分数最高的地方。# 当已放置4颗棋子时,必须在第五个空棋格上设置绝对高的分值。也就是10000# 当获胜组合上有部分位置已被对手的棋格占据而无法连成五子时,获胜组合上空棋格的获胜分数会直接设置为0。(四颗棋子,你把中间断了)# 当有两组及其以上的获胜组合位置交叉时,对该位置的分数进行叠加,形成分数比周围位置明显高。(五子棋中三三相连)score = 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 0def person_computer(): #人机对战fwidth, fheight = font2.size('黑子获胜')checkerboard = Checkerboard(Line_Points)cur_runner =  WHITE_CHESSMANwinner = Nonecomputer = AI(Line_Points, BLACK_CHESSMAN)# 设置黑白双方初始连子为0black_win_count = 0white_win_count = 0while True:for event in pygame.event.get():if event.type == QUIT:sys.exit()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 += 1x, y = event.pos[0], event.pos[1]if 610 < x < 800 and 333 < y < 360:  #点击重新开始person_computer()elif 600 < x < 800 and 400 < y < 500:  # 点击‘回到主界面’main()_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_computer(screen, font1)if winner:print_text(screen, font2, (SCREEN_WIDTH - fwidth) // 2, (SCREEN_HEIGHT - fheight) // 2, winner.Name + '获胜',RED_COLOR)pygame.display.flip()

6.主函数

主函数

def main():try:enter_the_game()except SystemExit:passexcept:traceback.print_exc()pygame.quit()input()
main()

人工智能大作业——五子棋相关推荐

  1. JavaFx/Java 大作业 五子棋 实验报告

    Java大作业五子棋实验报告 实验目的 通过此次实验,对这一学期学习的内容尤其是界面开发部分做了一个很好的回顾,看似简单的五子棋程序,设计好也确实费了我一点功夫 功能模块简介和系统结构图 ChessG ...

  2. Python语言 期末大作业 五子棋 (资源在博主资源拿)

      博主代码仅供参考,由于是边做边打补丁补功能,也没有时间去重构代码,所以质量不敢保证(doge)QAQ....         当然给大家给个参考,同样作为模板也能较好的去修改,怕麻烦的uu也可以直 ...

  3. 实现(手撕)遗传算法与集成学习-人工智能大作业(特征选择其实是乱选的,抄的别人的,,,)

    目录 题目 : 基于幸福度数据集的预测模型挖掘一.人工智能对研究问题的定义和说明二.结构框架技术和方法1.总体思想2.特征工程3.模型选择4.优化计算方法遗传算法4.1初始群体大小4.2适应度选择4. ...

  4. 人工智能大作业——人脸识别系统(最终)

    写在前面 时间过得飞快,时间已经距离我发第一篇文章过去2年多了,也不再从事代码工作,偶然间上到csdn翻看文章经过,看到还是有些人关注人脸识别系统的后续的,我猜大概率是学弟学妹们正在被期末实验折磨中, ...

  5. python大作业五子棋人人对战_简单的五子棋(人人对战)

    这是一个简单的五子棋游戏,目前只实现了简单的人人对战,就是自己跟自己下...具体效果如下: 实现这个效果也很简单,主要功能是: 1.点击棋盘能下棋子.棋子位置在棋盘点.点击点和下子点近似判断.黑白棋子 ...

  6. 【人工智能大作业】A*和IDA*搜索算法解决十五数码(15-puzzle)问题 (Python实现)(启发式搜索)

    Astar和IDAstar搜索算法解决十五数码(15-puzzle)问题 (文末附实现代码,此前为理论与具体问题分析) 文章目录 Astar和IDAstar搜索算法解决十五数码(15-puzzle)问 ...

  7. 人工智能大作业——A*算法迷宫寻路问题

    项目设计的目的 利用A*算法实现迷宫寻路功能,利用启发式函数的编写以及各类启发式函数效果的比较. 相关原理知识介绍 A*(A-Star)算法是一种静态路网中求解最短路最有效的方法.公式表示为:f(n) ...

  8. python之穿越火线游戏代码_Python 大作业之五子棋游戏(附代码)

    Python 大作业--五子棋游戏 姓名:吴欣 学号: 姓名:张雨清 学号: 一 游戏介绍: 我们设计的是五子棋游戏,支持两人一个鼠标对下,黑方用左 键单击,白方用右键单击,谁先下均可,落子无悔,下过 ...

  9. python五子棋大作业报告_Python 大作业之五子棋游戏(附代码)

    Python 大作业--五子棋游戏 姓名:吴欣学号: 姓名:张雨清学号: 一游戏介绍: 我们设计的是五子棋游戏,支持两人一个鼠标对下,黑方用左键单击,白方用右键单击,谁先下均可,落子无悔,下过的棋子对 ...

最新文章

  1. [Python从零到壹] 十一.数据分析之Numpy、Pandas、Matplotlib和Sklearn入门知识万字详解(1)
  2. 男子借款70万前后还了1600万仍未还清,如何避免套路贷?
  3. Android Studio目录结构分析
  4. 日常技术分享 : 一定要注意replcaceAll方法,有时候会如你所不愿!
  5. Shell 变量及函数讲解 [2]
  6. this super的用法
  7. Android 音频 OpenSL ES 录音 采集
  8. OceanBase架构介绍
  9. word批量打印助手_如何批量打印数十份甚至上百份Word文档
  10. VMPlayer Ubuntu 16.04 Copy and Paste with Host 主机与宿机之间的复制粘贴
  11. logging日志带颜色
  12. C#语法糖(Csharp Syntactic sugar)
  13. openwrt运行n2n服务器,Windows下使用N2N搭建局域网,全球局域网(重写)
  14. 远程桌面 android,Microsoft远程桌面
  15. 案例分析 | 优衣库DTC模式之全渠道零售
  16. Scaling Up Your Kernels to 31x31: Revisiting Large Kernel Design in CNNs
  17. 嵌入式系统学习-------1.什么是嵌入式系统?
  18. 系统未激活会影响到远程桌面连接和上网,是真的
  19. 小米盒子运行linux,小米盒子刷机成砖的解救措施攻略详解
  20. Python——字典的遍历

热门文章

  1. 李兴华内部JAVA培训视频 (难找啊)
  2. KMD驱动教程续-11
  3. mysql无法生成备份产生读锁_mydumper 备份原理和使用方法(备份mysql)
  4. 内蒙古最新八大员安全员模拟真题题库及答案
  5. 集群(1)---集群的概念
  6. 怎么用电脑修改图片尺寸?图片大小尺寸修改教程
  7. 需求预测模型分类与选择
  8. 基于张量的多元多阶马尔科夫多模态预测方法
  9. 什么是Word Embeddings
  10. PHP开发小技巧①⑥—提取富文本字符串中的文本内容