python:AI中国象棋、AI井字棋(人机对战,机器对战)

论坛 期权论坛 脚本     
匿名网站用户   2020-12-19 21:55   32   0

本人承接各种高校C语言、C++、Java语言、python等课程设计、数据采集、系统研发以及ppt等制造、科学上网等,以及常见的电脑故障有需要的私信我或者微信18476275715

这几年来,人工智能、大数据一直是一个大热门啊!但这些热门技术归根到底还是算法、数学的应用,本篇文章将讲解AI、大数据在一些具体应用的原理和解释!讲这些之前,先给大家普及一些井字棋、中国象棋的知识:井字棋是一个九格宫,棋子只有两种X、O,只要将其连成三个即可 获胜,规则简单,范围有限,所以我们可以将其赢得方式一一列举出来。

象棋相比而言就较为复杂的多,棋盘上有十条横线、九条竖线共分成90个交叉点;中国象棋的棋子共有32个,每种颜色16个棋子,分为7个兵种,摆放和活动在交叉点上。双方交替行棋,先把对方的将(帅)“将死”的一方获胜。如果模仿上面的井字棋一一人工列举出来,根本无法实现,只能通过机器学习去获得赢得方式,并保存下来。AlphaGo也应用到这一方面的知识,AlphaGo围棋会产生大量自我对弈棋局(最开始的阿尔法是以各种大型赛事等为基础数据的),为下一代的版本提供大量的基础数据,如此往复循环!所以AlphaGo可以说没有最强、只用更强!

总的来说,AI井字棋和AI中国象棋无非就是积累原始数据,然后进行训练,保存训练数据,为后面的更加智能做准备,循环往复。说起来简单,但如何对数据进行有效的处理呢?这一点便是AI的核心点。

井字棋:

#coding=utf-8
"""
[0,1,2]
[3,4,5]
[6,7,8]
"""

#胜利的走法
win_chess = [[0,4,8],[2,4,6],[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8]]
#最佳下棋顺序
best_way = [4,0,2,6,8,1,3,5,7]
#棋盘
chess = [0,0,0,0,0,0,0,0,0]

def is_win(now_chess,who):
    """
    判断游戏方(who)是否赢局
    """
    temp = now_chess[:]
    for w_c in win_chess:
        if temp[w_c[0]] == who and temp[w_c[1]] == who and temp[w_c[2]] == who :
            return who
    return 0

def count_zero(now_chess):
    """
    统计剩余格子
    返回个数
    """
    temp = now_chess[:]
    count = 0
    for te in temp:
        if te == 0:
            count = count + 1
    return count

def evaluation(now_chess):
    """
    估价函数(以X为对象)
    可以赢的行数 +1
    可以赢的行数上有自己的棋子 +2
    可导致自己赢 +2
    可导致对手赢 -2
    """
    temp = now_chess[:]
    count = 0
    for w_c in win_chess:
        if temp[w_c[0]] >= 0 and temp[w_c[1]] >= 0 and temp[w_c[2]] >= 0 :
            if temp[w_c[0]] == 1 or temp[w_c[1]] == 1 or temp[w_c[2]] == 1 :
                count += 1
            count += 1
    if is_win(temp,1) == 1:
        count = count + 2
    if is_win(temp,-1) == -1:
        count = count - 2
    return count

def all_go(now_chess,who):
    """
    遍历所有走法
    """
    temp = now_chess[:]
    tempp = []
    for i in best_way:
        if temp[i] == 0:
            temppp = temp[:]
            temppp[i]=who
            tempp.append([temppp,i])
    return tempp

def get_next_x(now_chess,who):
    """
    x获取下一个位置
    """
    temp = now_chess[:]
    best_list = None
    best_one = -1
    if count_zero(temp) <= 3 :
        for te in all_go(temp,who):
            if best_one == -1:
                best_list = te[0]
                best_one = te[1]
            else :
                if evaluation(te[0]) > evaluation(best_list):
                    best_list = te[0]
                    best_one = te[1]
        return best_one
    for te in all_go(temp,who):
        for tee in all_go(te[0],who*-1):
            for teee in all_go(tee[0],who):
                if best_list is None:
                    best_list = teee[0]
                    best_one = te[1]
                else:
                    if evaluation(teee[0]) > evaluation(best_list) :
                        best_list = teee[0]
                        best_one = te[1]
    return best_one

def get_next_o(now_chess,who):
    """
    o获取下一个位置
    """
    temp = now_chess[:]
    best_list = None
    best_one = -1
    if count_zero(temp) <= 2 :
        for te in all_go(temp,who):
            if best_one == -1:
                best_list = te[0]
                best_one = te[1]
            else :
                if evaluation(te[0]) < evaluation(best_list):
                    best_list = te[0]
                    best_one = te[1]
        return best_one
    for te in all_go(temp,who):
        for tee in all_go(te[0],who*-1):
            if best_list is None:
                best_list = tee[0]
                best_one = te[1]
            else:
                if evaluation(tee[0]) < evaluation(best_list) :
                    best_list = tee[0]
                    best_one = te[1]
    return best_one

def is_danger(now_chess,who=0):
    """
    判断自己是否处于危险状态(即 对手可能已经差一子赢局)
    """
    temp = now_chess[:]
    for te in all_go(temp,who*-1):
        if is_win(te[0],who*-1) == who*-1:
            return te[1]
    return -1

if __name__ == "__main__":
    """
    测试用
    """
    chess = [0,0,0,\
            0,1,0,\
            0,0,0]
    #print(get_next_old(chess,-1,1))
    #print(all_go(chess,1))
    print(get_next_o(chess,-1))
#coding=utf-8
"""
"""
import tkinter as tk
import time
import threading
import random
import chess

init_chess = [0,0,0,0,0,0,0,0,0]    #原始棋盘
the_chess = [0,0,0,0,0,0,0,0,0]    #记录棋盘
show_chess = ''
flag = True
who = 1
count_x = 0
count_y = 0
count_z = 0

top = tk.Tk()
top.title('井字棋 -> Fighting')
top.geometry("300x300")
top.resizable()
show_str = tk.StringVar(top)
tips = tk.StringVar(top)    #提示信息

#初始化棋盘信息
ch = []
for i in range(9):
    ch.append(tk.StringVar(top))

#初始化提示信息
tips.set("")

frame_top = tk.Frame(top)
frame_cont = tk.Frame(top)
frame_bot = tk.Frame(top)
frame_cont1 = tk.Frame(frame_cont)
frame_cont2 = tk.Frame(frame_cont)
frame_cont3 = tk.Frame(frame_cont)

label1 = tk.Label(frame_cont,justify=tk.CENTER,textvariable=show_str,font=("幼圆",30))

# 棋盘显示label 0~9
l0 = tk.Label(frame_cont1,textvariable=ch[0],font=("幼圆",30),padx=0)
l1 = tk.Label(frame_cont1,textvariable=ch[1],font=("幼圆",30),padx=0)
l2 = tk.Label(frame_cont1,textvariable=ch[2],font=("幼圆",30),padx=0)

l3 = tk.Label(frame_cont2,textvariable=ch[3],font=("幼圆",30),padx=0)
l4 = tk.Label(frame_cont2,textvariable=ch[4],font=("幼圆",30),padx=0)
l5 = tk.Label(frame_cont2,textvariable=ch[5],font=("幼圆",30),padx=0)

l6 = tk.Label(frame_cont3,textvariable=ch[6],font=("幼圆",30),padx=0)
l7 = tk.Label(frame_cont3,textvariable=ch[7],font=("幼圆",30),padx=0)
l8 = tk.Label(frame_cont3,textvariable=ch[8],font=("幼圆",30),padx=0)

label_bottom = tk.Label(frame_bot,justify=tk.CENTER,textvariable=tips,font=("幼圆",20),padx=0)

def update_chess():
    for i in range(9):
        if the_chess[i] == 1 :
            ch[i].set('|X|')
        elif the_chess[i] == -1 :
            ch[i].set('|O|')
        else :
            ch[i].set('| |')
        #print(i)

def init_ch():
    """
    初始化棋盘
    """
    for i in range(9):
        the_chess[i] = init_chess[i]
    update_chess()
    return the_chess

def ai_go_first():
    if chess.count_zero(the_chess) == 9:
        the_chess[random.randint(0,8)] = -1
    update_chess()
    forget()

ai_go_fir_b = tk.Button(frame_cont,text='机器先下',command=ai_go_first)

def forget():
    ai_go_fir_b.pack_forget()

def but1():
    """
    人机对战
    """
    flag = True
    init_ch()
    tips.set("人机对战模式")
    l0.bind("<Button-1>", touch_l0)
    l1.bind("<Button-1>", touch_l1)
    l2.bind("<Button-1>", touch_l2)
    l3.bind("<Button-1>", touch_l3)
    l4.bind("<Button-1>", touch_l4)
    l5.bind("<Button-1>", touch_l5)
    l6.bind("<Button-1>", touch_l6)
    l7.bind("<Button-1>", touch_l7)
    l8.bind("<Button-1>", touch_l8)
    ai_go_fir_b.pack(side=tk.TOP)

def run(i,id):
    new_chess = init_chess[:]
    global count_x
    global count_y
    global count_z
    if id == 1 :
        new_chess[random.randint(0,8)] = -1
    else :
        new_chess[random.randint(0,8)] = 1
    x = 0
    for x in range(10):
        if chess.count_zero(new_chess) > 0 :
            #print(chess.count_zero(new_chess))
            if id == 1:
                #print('*****')
                #print(chess.get_next_x(new_chess,id))
                pos = chess.get_next_x(new_chess,id)
                if pos != -1 :
                    new_chess[int(chess.get_next_x(new_chess,id))] = id
                else :
                    for xx in range(9):
                        if new_chess[xx] == 0 :
                            new_chess[xx] = id
            else :
                pos = chess.get_next_o(new_chess,id)
                if pos != -1 :
                    new_chess[int(chess.get_next_o(new_chess,id))] = id
                else :
                    for xx in range(9):
                        if new_chess[xx] == 0 :
                            new_chess[xx] = id
            id = id * -1
            if chess.is_win(new_chess,id) == id :
                name = ''
                if id == 1 :
                    name = 'X'
                    update_chess()
                    print("第 {} 局 : {} 赢了!".format(i+1,name) + ' ' + str(new_chess))
                    tips.set("第 {} 局 : {} 赢了!".format(i+1,name))
                    threading.Lock()
                    count_x = count_x + 1
                    threading.RLock()
                    time.sleep(3)
                    break
                else :
                    name = 'O'
                    update_chess()
                    print("第 {} 局 : {} 赢了!".format(i+1,name) + ' ' + str(new_chess))
                    tips.set("第 {} 局 : {} 赢了!".format(i+1,name))
                    threading.Lock()
                    count_y = count_y + 1
                    threading.RLock()
                    time.sleep(3)
                    break
            elif chess.is_win(new_chess,id*-1) == id*-1 :
                id = id * -1
                name = ''
                if id == 1 :
                    name = 'X'
                    print("第 {} 局 : {} 赢了!".format(i+1,name) + ' ' + str(new_chess))
                    tips.set("第 {} 局 : {} 赢了!".format(i+1,name))
                    threading.Lock()
                    count_x = count_x + 1
                    threading.RLock()
                    break
                else :
                    name = 'O'
                    print("第 {} 局 : {} 赢了!".format(i+1,name) + ' ' + str(new_chess))
                    tips.set("第 {} 局 : {} 赢了!".format(i+1,name))
                    threading.Lock()
                    count_y = count_y + 1
                    threading.RLock()
                    break
            elif chess.count_zero(new_chess) == 0:
                print("第 {} 局 : 平局".format(i+1) + ' ' + str(new_chess))
                tips.set("第 {} 局 : 平局".format(i+1))
                threading.Lock()
                count_z = count_z + 1
                threading.RLock()
                break
            else :
                pass
        else :
            print("第 {} 局 : 平局".format(i+1) + ' ' + str(new_chess))
            tips.set("第 {} 局 : 平局".format(i+1))
            threading.Lock()
            count_z = count_z + 1
            threading.RLock()
            break
    #print(str(i + 1) + ' ' + str(new_chess))
    '''if i == 9:
        print("第 {} 局 : 平局".format(i+1) + ' ' + str(new_chess))
        tips.set("第 {} 局 : 平局".format(i+1))
        threading.Lock()
        count_z = count_z + 1
        threading.RLock()'''
    time.sleep(3)
    for i in range(9):
        the_chess[i] = new_chess[i]
    update_chess()
    threading.Lock()
    tips.set("50局已经结束!\nX 共赢 {}次\nO 共赢 {}次\n平局 {} 次".format(count_x,count_y,count_z))
    threading.RLock()

def but2():
    """
    机器对战
    """
    print(" ")
    ai_go_fir_b.pack_forget()
    flag = False
    global count_x
    global count_y
    global count_z
    count_x = 0
    count_y = 0
    count_z = 0
    init_ch()
    tips.set("机器对战模式")
    l0.unbind("<Button-1>")
    l1.unbind("<Button-1>")
    l2.unbind("<Button-1>")
    l3.unbind("<Button-1>")
    l4.unbind("<Button-1>")
    l5.unbind("<Button-1>")
    l6.unbind("<Button-1>")
    l7.unbind("<Button-1>")
    l8.unbind("<Button-1>")
    id = 1
    th = []
    for i in range(50):
        id = id * -1
        try:
            th.append(threading.Thread(target=run,args=(i,id)))
            th[i].start()
        except Exception as e:
            print(e)
            i = i - 1
    #tips.set("50 局已经结束! X 共赢 {}次, O 共赢 {}次, 平局 {} 次".format(count_x,count_y,count_z))
        

def ai_go(w):
    """
    机器走棋 O
    """
    if chess.count_zero(the_chess) < 9:   
        po = chess.is_danger(the_chess,1)
        if po != -1 :
            the_chess[po] = w
            update_chess()
        elif constraint(w) == False:
            pass
        else :
            the_chess[chess.get_next_o(the_chess,-1)] = w
            update_chess()
        if chess.is_win(the_chess,-1) == -1:
            tips.set("你输了!")
    if chess.count_zero(the_chess) == 0:
        tips.set("平局!")

def constraint(w):
    """
    判断是否处于危险状态
    """
    po = chess.is_danger(the_chess,-1)
    if po != -1:
        the_chess[po] = w
        update_chess()
        return False
    return True

def peo_go(po):
    """
    获取人们按键,并下棋
    """
    if the_chess[po] == 0 :
        the_chess[po] = who
        update_chess()
        if chess.is_win(the_chess,who) == who:
            tips.set('你赢了!')
        elif chess.count_zero(the_chess) == 0:
            tips.set("平局!")
        else :
            ai_go(who*-1)

def touch_l0(e):
    peo_go(0)

def touch_l1(e):
    peo_go(1)

def touch_l2(e):
    peo_go(2)

def touch_l3(e):
    peo_go(3)

def touch_l4(e):
    peo_go(4)

def touch_l5(e):
    peo_go(5)

def touch_l6(e):
    peo_go(6)

def touch_l7(e):
    peo_go(7)

def touch_l8(e):
    peo_go(8)
        

tk.Button(frame_top,text='人机对决',command=but1).pack(side=tk.LEFT)
tk.Button(frame_top,text='机器对决',command=but2).pack(side=tk.RIGHT)

update_chess()

l0.pack(side=tk.LEFT)
l1.pack(side=tk.LEFT)
l2.pack(side=tk.LEFT)
l3.pack(side=tk.LEFT)
l4.pack(side=tk.LEFT)
l5.pack(side=tk.LEFT)
l6.pack(side=tk.LEFT)
l7.pack(side=tk.LEFT)
l8.pack(side=tk.LEFT)

label_bottom.pack()

frame_cont1.pack()
frame_cont2.pack()
frame_cont3.pack()

frame_top.pack()
frame_cont.pack()
frame_bot.pack()

top.mainloop()

井字棋相对简单就没有太多的分析,代码已经给出如果还有小伙伴不明白可以加我联系!

AI中国象棋:

AI中国象棋就不展示了,有需要的小伙伴可以找我,这里主要展示象棋的核心部分。

一般来说AI在做出决策需要有三个条件,第一:AI会找出所有允许象棋规则的走法。第二:根据这些走法生成一个树来决定最佳的一步;树的大小随深度指数增长,但是树的深度可以是任意的。假设每次有20种走法,那深度为1对应20,深度为2对应400,以此类推。第三:遍历这个树,选择出某一种走法对应的结果最佳的走法。

python爬虫实战开发

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP