突然奇想,什么时候可以自己实现一个机器对战的小游戏,但一直不敢去尝试,直到偶尔发现了重力四子棋的规则,有限的空间棋盘正好可以拿来练手。

有关下棋AI的算法,说来说去也就那么几种,随机蒙特卡罗方法、UCT信心上限树、博弈论(Alpha−Beta剪枝)...

这个小游戏我时间更多的花在ui界面和游戏逻辑的实现,可以切换先后手顺序,添加了重置游戏和暂停游戏的规则,可落子节点辅助提示,以及对应的文字提示信息。

算法采用了无忧化的蒙特卡罗方法,模拟当前棋盘状态可落子节点扩展的胜利可能性,模拟的次数越多,时间自然也就越久,但智能度相应着也会提高。

源代码:https://download.csdn.net/download/qq_40204582/11212878

代码开源了,如果有复制过去的朋友,可以顺手点个赞吗^_^

import pygame, sys
from pygame.locals import *
import time
import random
import copy# game parameters
pygame.init()
win_width, win_height = 930, 700
displaysurf = pygame.display.set_mode((win_width, win_height), 0, 32)
pygame.display.set_caption('Connect_4')# color parameters
backgroundcolor_chess = (244, 171, 102)
color_white = (255, 255, 255)
color_black = (0, 0, 0)
color_tip_white = (225, 225, 225)
color_tip_black = (25, 25, 25)
color_green = (0, 255, 0)# chess parameters
chess_grid_row, chess_grid_col = 6, 8
chess_list = []
for i in range(chess_grid_row):new_line = [0 for j in range(chess_grid_col)]chess_list.append(new_line)
player = True
play_flag = False# draw chessboard
def draw_chessboard():displaysurf.fill(color_white)fontobj = pygame.font.SysFont('SimHei',70)text = fontobj.render("重力四子棋", True, color_black, color_white)textrect = text.get_rect()textrect.center = (430, 70)displaysurf.blit(text, textrect)pygame.draw.rect(displaysurf, backgroundcolor_chess, (50, 170, 640, 480))for pix_row in range(7):pygame.draw.line(displaysurf, color_black, (50, 170 + pix_row * 80), (690, 170 + pix_row * 80))for pix_col in range(9):pygame.draw.line(displaysurf, color_black, (50 + pix_col * 80, 170), (50 + pix_col * 80, 650))def draw_tip_chess(mousex, mousey, type):for row in range(chess_grid_row):for col in range(chess_grid_col):if chess_list[row][col] in [3, 4]:chess_list[row][col] = 0col = int((mousex - 50) / 80)row = int((mousey - 170) / 80)if row == chess_grid_row:row -= 1if col == chess_grid_col:col -= 1if row < chess_grid_row - 1:if chess_list[row + 1][col] == 0:returnif chess_list[row][col] == 0:chess_list[row][col] = typedef clear_tip_chess():for row in range(chess_grid_row):for col in range(chess_grid_col):if chess_list[row][col] in [3, 4]:chess_list[row][col] = 0def draw_check_chess(mousex, mousey, type):for row in range(chess_grid_row):for col in range(chess_grid_col):if chess_list[row][col] in [3, 4]:chess_list[row][col] = 0col = int((mousex - 50) / 80)row = int((mousey - 170) / 80)if row == chess_grid_row:row -= 1if col == chess_grid_col:col -= 1if row < chess_grid_row - 1:if chess_list[row + 1][col] == 0:returnif chess_list[row][col] in [1, 2]:return Falseelse:chess_list[row][col] = typereturn Truedef draw_chess():for row in range(chess_grid_row):for col in range(chess_grid_col):if chess_list[row][col] == 0:pygame.draw.circle(displaysurf, backgroundcolor_chess, (90 + col * 80, 210 + row * 80), 38)elif chess_list[row][col] == 1:pygame.draw.circle(displaysurf, color_black, (90 + col * 80, 210 + row * 80), 38)elif chess_list[row][col] == 2:pygame.draw.circle(displaysurf, color_white, (90 + col * 80, 210 + row * 80), 38)elif chess_list[row][col] == 3:pygame.draw.circle(displaysurf, color_tip_black, (90 + col * 80, 210 + row * 80), 38)elif chess_list[row][col] == 4:pygame.draw.circle(displaysurf, color_tip_white, (90 + col * 80, 210 + row * 80), 38)def is_win(temp_chess_list):not_null_sum = 0for row in range(chess_grid_row):for col in range(chess_grid_col):if temp_chess_list[row][col] in [3, 4]:temp_chess_list[row][col] = 0if temp_chess_list[row][col] != 0:not_null_sum += 1# horizontalif col < chess_grid_col - 3:if temp_chess_list[row][col] == temp_chess_list[row][col + 1] == temp_chess_list[row][col + 2] == \temp_chess_list[row][col + 3] and temp_chess_list[row][col] != 0:return temp_chess_list[row][col]# verticalif row < chess_grid_row - 3:if temp_chess_list[row][col] == temp_chess_list[row + 1][col] == temp_chess_list[row + 2][col] == \temp_chess_list[row + 3][col] and temp_chess_list[row][col] != 0:return temp_chess_list[row][col]# right slantif col < chess_grid_col - 3 and row < chess_grid_row - 3:if temp_chess_list[row][col] == temp_chess_list[row + 1][col + 1] == temp_chess_list[row + 2][col + 2] == \temp_chess_list[row + 3][col + 3] and temp_chess_list[row][col] != 0:return temp_chess_list[row][col]# left slantif col >= 3 and row < chess_grid_row - 3:if temp_chess_list[row][col] == temp_chess_list[row + 1][col - 1] == temp_chess_list[row + 2][col - 2] == \temp_chess_list[row + 3][col - 3] and temp_chess_list[row][col] != 0:return temp_chess_list[row][col]if not_null_sum == chess_grid_row*chess_grid_col:return 3return 0def AI(chess_list, type):node_list = []chess_null_sum = 0for col in range(chess_grid_col):for row in range(chess_grid_row):if chess_list[row][col] == 0:chess_null_sum += 1if row == chess_grid_row -1:temp_chess_list = copy.deepcopy(chess_list)temp_chess_list[row][col] = typenode_list.append([row, col])flag = is_win(temp_chess_list)if flag != 0:chess_list[row][col] = typereturn row, colelif chess_list[row+1][col] != 0:temp_chess_list = copy.deepcopy(chess_list)temp_chess_list[row][col] = typenode_list.append([row, col])flag = is_win(temp_chess_list)if flag != 0:chess_list[row][col] = typereturn row, colprint(node_list)range_sum = 500 + int((chess_grid_row*chess_grid_col-chess_null_sum)/(chess_grid_row*chess_grid_col)*100)print(range_sum)win_list = [0 for j in range(chess_grid_col)]tip_list = [0 for j in range(chess_grid_col)]start = time.clock()for i in range(len(node_list)):for j in range(100):temp_type = typetemp_chess_list = copy.deepcopy(chess_list)temp_node_list = copy.deepcopy(node_list)temp_chess_list[temp_node_list[i][0]][temp_node_list[i][1]] = temp_typeflag_win = is_win(temp_chess_list)if flag_win != 0:if flag_win == type:win_list[i] += 1continueelif flag_win == 3:tip_list[i] += 1if temp_node_list[i][0] == 0:del temp_node_list[i]else:temp_node_list[i][0] -= 1while True:if temp_type == 1:temp_type = 2else:temp_type = 1try:temp_index = random.randint(0, len(temp_node_list)-1)except:breaktemp_chess_list[temp_node_list[temp_index][0]][temp_node_list[temp_index][1]] = temp_typeflag_win = is_win(temp_chess_list)if flag_win != 0:if flag_win == type:win_list[i] += 1elif flag_win == 3:tip_list[i] += 1breakif temp_node_list[temp_index][0] == 0:del temp_node_list[temp_index]else:temp_node_list[temp_index][0] -= 1end = time.clock()print(end - start)if max(win_list) > range_sum*0.1:print(win_list)check = win_list.index(max(win_list))print(node_list)print(check)else:check = tip_list.index(max(tip_list))print("选择平局")chess_list[node_list[check][0]][node_list[check][1]] = typedef draw_player(player):fontobj = pygame.font.SysFont('SimHei', 25)if player:text = fontobj.render("先手: 电脑    棋色: 黑色", True, color_black, color_white)else:text = fontobj.render("先手: 玩家    棋色: 黑色", True, color_black, color_white)textrect = text.get_rect()textrect.center = (260, 140)displaysurf.blit(text, textrect)def button():pygame.draw.rect(displaysurf, color_green, (730, 200, 160, 80))fontobj1 = pygame.font.SysFont('SimHei', 30)text1 = fontobj1.render("切换先手", True, color_white, color_green)textrect1 = text1.get_rect()textrect1.center = (810, 240)displaysurf.blit(text1, textrect1)pygame.draw.rect(displaysurf, color_green, (730, 360, 160, 80))fontobj2 = pygame.font.SysFont('SimHei', 30)if play_flag == False:text2 = fontobj2.render("开始游戏", True, color_white, color_green)else:text2 = fontobj2.render("暂停游戏", True, color_white, color_green)textrect2 = text2.get_rect()textrect2.center = (810, 400)displaysurf.blit(text2, textrect2)pygame.draw.rect(displaysurf, color_green, (730, 520, 160, 80))fontobj3 = pygame.font.SysFont('SimHei', 30)text3 = fontobj3.render("重置游戏", True, color_white, color_green)textrect3 = text3.get_rect()textrect3.center = (810, 560)displaysurf.blit(text3, textrect3)def play_type():fontobj = pygame.font.SysFont('SimHei', 25)if play_flag == False:win_flag = is_win(chess_list)pygame.draw.rect(displaysurf, color_white, (400, 120, 300, 45))if win_flag == 0:text = fontobj.render("状态: 未开始游戏", True, color_black, color_white)elif win_flag == 1:if player:text = fontobj.render("状态: 电脑胜利", True, color_black, color_white)else:text = fontobj.render("状态: 玩家胜利", True, color_black, color_white)elif win_flag == 2:if player:text = fontobj.render("状态: 玩家胜利", True, color_black, color_white)else:text = fontobj.render("状态: 电脑胜利", True, color_black, color_white)elif win_flag == 3:text = fontobj.render("状态: 平局", True, color_black, color_white)else:null_sum = 0for row in range(chess_grid_row):for col in range(chess_grid_col):if chess_list[row][col] in [0, 3, 4]:null_sum += 1if player:if (chess_grid_row*chess_grid_col-null_sum) % 2 == 0:text = fontobj.render("状态: 请电脑落子", True, color_black, color_white)else:text = fontobj.render("状态: 请玩家落子", True, color_black, color_white)else:if (chess_grid_row*chess_grid_col-null_sum) % 2 == 1:text = fontobj.render("状态: 请电脑落子", True, color_black, color_white)else:text = fontobj.render("状态: 请玩家落子", True, color_black, color_white)textrect = text.get_rect()textrect.center = (570, 140)displaysurf.blit(text, textrect)def new_play():global player, play_flagdraw_chessboard()# AI(chess_list, 1)# main game loopwhile True:for event in pygame.event.get():# close gameif event.type == QUIT:pygame.quit()sys.exit()elif event.type == MOUSEMOTION:mousex, mousey = event.posif play_flag:if mousex > 50 and mousex < 690 and mousey > 170 and mousey < 730:if player:draw_tip_chess(mousex, mousey, 4)else:draw_tip_chess(mousex, mousey, 3)else:clear_tip_chess()elif event.type == MOUSEBUTTONUP:mousex, mousey = event.posif play_flag:if mousex > 50 and mousex < 690 and mousey > 170 and mousey < 730:if player:flag = draw_check_chess(mousex, mousey, 2)draw_chess()pygame.display.update()if flag:if is_win(chess_list) != 0:play_flag = Falseplay_type()pygame.display.update()if play_flag:AI(chess_list, 1)if is_win(chess_list) != 0:play_flag = Falseelse:flag = draw_check_chess(mousex, mousey, 1)draw_chess()pygame.display.update()if flag:if is_win(chess_list) != 0:play_flag = Falseplay_type()pygame.display.update()if play_flag:AI(chess_list, 2)if is_win(chess_list) != 0:play_flag = Falseelse:if mousex > 730 and mousex < 890 and mousey > 200 and mousey < 280:if is_win(chess_list) == 0:if player:player = Falseelse:player = Truedraw_player(player)if mousex > 730 and mousex < 890 and mousey > 360 and mousey < 440:if play_flag:play_flag = Falseelse:if is_win(chess_list) == 0:play_flag = Trueplay_type()button()pygame.display.update()if player and sum(chess_list[-1]) == 0:AI(chess_list, 1)elif mousex > 730 and mousex < 890 and mousey > 520 and mousey < 600:play_flag = Falsefor row in range(chess_grid_row):for col in range(chess_grid_col):chess_list[row][col] = 0draw_player(player)button()draw_chess()play_type()pygame.display.update()def main():new_play()main()

Pygame——AI重力四子棋相关推荐

  1. java四子棋实验报告_Python 实现劳拉游戏的实例代码(四连环、重力四子棋)

    游戏规则:双方轮流选择棋盘的列号放进自己的棋子, 若棋盘上有四颗相同型号的棋子在一行.一列或一条斜线上连接起来, 则使用该型号棋子的玩家就赢了! 程序实现游戏,并将每局的数据保存到本地的文件中 首先我 ...

  2. Python 实现劳拉游戏(四连环、重力四子棋)

    游戏规则:双方轮流选择棋盘的列号放进自己的棋子, 若棋盘上有四颗相同型号的棋子在一行.一列或一条斜线上连接起来, 则使用该型号棋子的玩家就赢了! 程序实现游戏,并将每局的数据保存到本地的文件中 首先我 ...

  3. java四连环游戏编程_如何用C语言实现四连环游戏(重力四子棋)?

    正好我们老师也要做了这个作业!就来蹭个热闹~ 大概就是实现了要求的功能,然后能够自定义棋盘大小(目前是6行7列,通过修改Connect4::play()里面的对于rowNum和colNum的赋值来实现 ...

  4. 人机对战初体验:Python基于Pygame实现四子棋游戏

    人机对战初体验-四子棋游戏 继去年3月人机大战引发全球瞩目以来,围棋AI(人工智能)再度引发跨领域的关注:一个叫Master的围棋AI,几天时间,面对中日韩顶尖职业围棋选手,已取得60胜0败的恐怖战绩 ...

  5. python人机对战的实验步骤_人机对战初体验:Python实现四子棋游戏

    继去年3月人机大战引发全球瞩目以来,围棋AI(人工智能)再度引发跨领域的关注:一个叫Master的围棋AI,几天时间,面对中日韩顶尖职业围棋选手,已取得60胜0败的恐怖战绩,展现出的围棋技艺已经到了人 ...

  6. 四子棋 freepython

    四子棋,是黑白棋的一种.是一种益智的棋类游戏.黑白两方(也有其它颜色的棋子)在8*8的格子内依次落子.黑方为先手,白方为后手.落子规则为,每一列必须从最底下的一格开始.依此可向上一格落子.一方落子后另 ...

  7. 深圳大学计系汇编语言实验--四子棋游戏

    题面 四子棋是个双人游戏,两人轮流下棋,棋盘由行和列组成的网格,每个选手每次下一个子直到两人中有一人的棋子连成一条水平线.垂直线或者是对角线. 本实验需要在LC-3中实现简易版四子棋的游戏,两位选手通 ...

  8. 四子棋游戏--bingo game

    最近自己编了一个四子棋的游戏.说明如下: 游戏简介: 一种常见的四子棋游戏,可以是人机对战,两人对战,或者网上对战. 游戏的双方轮流落子,每人持有21颗子.棋子共有6*7个位置,玩家的棋子总是落到 当 ...

  9. 基于LC3模拟器的简单游戏设计:简易四子棋

    一.实验目的 分析和理解指定的需解决问题. 利用LC-3的汇编代码设计实现相关程序. 通过LC-3仿真器调试和运行相关程序并得到正确的结果. 二.实验内容 四子棋是一款普遍流行的简易型桌面游戏,据说, ...

  10. vb四环棋的实现,平面四子棋,四连环游戏

    vb四环棋的实现,平面四子棋 首先我们百度一下,什么是平面四子棋 相信很多小伙伴见到这幅图片都不陌生. 那么在代码中怎么实现呢?我们用vb代码为例子. 先看效果图 我们设计o和x是需要下的棋子,如果没 ...

最新文章

  1. 关闭iptables和SELINUX
  2. Hadoop 中文编码相关问题 -- mapreduce程序处理GBK编码数据并输出GBK编码数据
  3. ECMAScript Query实例
  4. tensorflow2.2.0安装_Zabbix5.0安装部署
  5. 高级指令——top指令【作用:查看服务器的进程占的资源】、du -sh指令【作用:查看目录的真实大小】、find指令【作用:用于查找文件】、service指令
  6. 【Python应用】Python+Kepler.gl轻松制作酷炫路径动画
  7. 转:高效代码审查的八条准则和十个经验
  8. Redis 单例、主从模式、sentinel 以及集群的配置方式及优缺点对比(转)
  9. 开课啦 dubbo-go 微服务升级实战
  10. 服务器上在哪修改my.in,wordpress plugin的SVN使用方法
  11. 查看及修改当前数据库的所支持的数据库引擎以及默认数据库引擎
  12. mysql只能导入2m_如何解决phpMyAdmin导入mysql数据库超过2M的问题
  13. extjs fieldset 和 radio
  14. git21天打卡Day1-linux下安装git
  15. c语言double型小数点后几位_程序的数据要放到哪里呢?|C语言第二篇
  16. ClickHouse原理及使用
  17. elementui二维表动态渲染
  18. 最彻底的健身补剂——肌酸!
  19. 岛田庄司《占星术杀人魔法》读后感
  20. 知识产权与标准规范: 著作权法、计算机软件保护条例、商标权、不正当竞争法、招投标法、采购法、合同法

热门文章

  1. 计算机专业定向选调,兄弟们,关于定向选调和找工作,JR们能不能给小弟一些建议...
  2. DSP与广告位之间的关系
  3. 估值择时对ETF基金定投的影响
  4. 常用的数学基础知识集锦
  5. oppo手机linux模式,OPPO工程模式怎么进 OPPO手机指令有哪些
  6. android基带版本,Android - 基带版本为未知时自动隐藏
  7. execl 多线程 linux,MyExcel 3.7.0 发布,屏蔽多线程处理细节
  8. Linux的常用命令就是记不住,还在百度找?于是推出了这套教程,
  9. IT十年人生过客-七-眉毛与恶名
  10. 阿里TPP图化框架技术实践 — 打造算法在线服务领域极致开发体验与性能