本文主要是介绍python3.6 ai井字棋 alpha-beta剪枝3,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
所有代码:
import numpy as np
from tkinter import *class Game(object):def __init__(self):self.chess = np.zeros((3, 3), dtype=int) # 棋盘状态数组 0---空格 1---叉电脑 2---圈玩家self.iscircle = True # 当前圈下,默认玩家先手self.select_i, self.select_j = -1, -1self.root = Tk()self.root.title('井字棋')self.canvas = Canvas(self.root, width=230, height=230, bg="white")self.canvas.pack()self.canvas.create_rectangle(25, 25, 205, 205, fill="#CA9762")for i in range(1, 5):self.canvas.create_line(25, 25 + 60 * (i - 1), 205, 25 + 60 * (i - 1)) # 横线self.canvas.create_line(25 + 60 * (i - 1), 25, 25 + 60 * (i - 1), 205) # 竖线self.canvas.bind("<Button-1>", self.player)self.root.mainloop()def player(self, event):x = event.xy = event.yif self.iscircle and (25 <= x <= 205) and (25 <= y <= 205):i = int((y - 25) / 60)j = int((x - 25) / 60)if self.chess[i][j] == 0:self.chess[i][j] = 2# 画圈self.drawcircle(i, j)# 画完,判断是否结束游戏self.isGameOver(2)self.iscircle = False# 轮到电脑下self.computer()def win(self, chesstemp, who):t = chesstemp.copy()for i in range(3):if t[i][0] == who and t[i][1] == who and t[i][2] == who: # 竖直方向return Trueif t[0][i] == who and t[1][i] == who and t[2][i] == who: # 水平方向return Trueif t[0][0] == who and t[1][1] == who and t[2][2] == who:return Trueif t[0][2] == who and t[1][1] == who and t[2][0] == who:return Truereturn Falsedef isGameOver(self, who):# 游戏结束 1、满格平局 2、电脑胜 3、玩家胜t = self.chess.copy()empty_cells = [(i, j) for i in range(3) for j in range(3) if t[i][j] == 0]if self.win(t, who):return Trueelse:if len(empty_cells) == 0: # 没有人赢,但是没有空格了,游戏结束return Trueelse: # 游戏没有结束return Falsedef drawcircle(self, i, j):x = 25 + 60 * jy = 25 + 60 * iself.canvas.create_oval(x + 30 - 20, y + 30 - 20, x + 30 + 20, y + 30 + 20)def drawcha(self, i, j):x = 25 + 60 * jy = 25 + 60 * iself.canvas.create_line(x, y, x + 60, y + 60)self.canvas.create_line(x + 60, y, x, y + 60)def computer(self): ## 进行 a-b剪枝 ,返回下一步该下的坐标if not self.iscircle:i, j, score = self.alphabeta2(self.chess, -10000, 10000, True, 2000000000)if 0 <= i < 3 and 0 <= j < 3:print('Computer下棋的位置 ,i ,j ', i, j, score)self.drawcha(i, j)self.chess[i][j] = 1self.isGameOver(1)self.iscircle = True'''score = self.alphabeta3(self.chess, -10000, 10000, True, True, 6)print('Computer下棋的位置 ,i ,j ', self.select_i, self.select_j, score)if 0 <= self.select_i < 3 and 0 <= self.select_j < 3:self.drawcha(self.select_i
这篇关于python3.6 ai井字棋 alpha-beta剪枝3的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!