脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 我用Python做个AI出牌器斗地主把把赢

我用Python做个AI出牌器斗地主把把赢

2021-12-25 00:35Dragon少年 Python

这篇文章主要介绍了我是如何用Python做的AI出牌器,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

前言

最近在网上看到一个有意思的开源项目,基于快手团队开发的开源ai斗地主——douzero做的一个“成熟”的ai,项目开源地址【https://github.com/tianqiraf/douzero_for_happydoudizhu – tianqiraf】。

今天我们就一起来学习下是如何制作一个基于douzero的出牌器,看看ai是如何来帮助斗地主的!

一、核心功能设计

首先这款出牌器是基于douzero开发的,核心是需要利用训练好的ai模型来帮住我们,给出最优出牌方案。

其次关于出牌器,先要需要确认一个ai出牌角色,代表我们玩家自己。我们只要给这个ai输入玩家手牌和三张底牌。确认好地主和农民的各个角色,告诉它三个人对应的关系,这样就可以确定队友和对手。

我们还要将每一轮其他两人的出牌输入,这样出牌器就可以根据出牌数据,及时提供给我们最优出牌决策,带领我们取得胜利!

那么如何获取三者之间的关系呢?谁是地主?谁是农民?是自己一人作战还是农民合作?自己玩家的手牌是什么?三张底牌是什么?这些也都需要在开局后确认好。

大致可以整理出要实现的核心功能如下:

ui设计排版布局

  • 显示三张底牌
  • 显示ai角色出牌数据区域,上家出牌数据区域,下家出牌数据区域,本局胜率区域
  • ai玩家手牌区域
  • ai出牌器开始停止

手牌和出牌数据识别

  • 游戏刚开始根据屏幕位置,截图识别ai玩家手牌及三张底牌
  • 确认三者之间的关系,识别地主和农民角色,确认队友及对手关系
  • 识别每轮三位玩家依次出了什么牌,刷新显示对应区域

ai出牌方案输出

  • 加载训练好的ai模型,初始化游戏环境
  • 每轮出牌判断,根据上家出牌数据给出最优出牌决策
  • 自动刷新玩家剩余手牌和本局胜率预测

二、实现步骤

1. ui设计排版布局

根据上述功能,首先考虑进行简单的ui布局设计,使用的是pyqt5。核心设计代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
def setupui(self, form):
    form.setobjectname("form")
    form.resize(440, 395)
    font = qtgui.qfont()
    font.setfamily("arial")
    font.setpointsize(9)
    font.setbold(true)
    font.setitalic(false)
    font.setweight(75)
    form.setfont(font)
    self.winrate = qtwidgets.qlabel(form)
    self.winrate.setgeometry(qtcore.qrect(240, 180, 171, 61))
    font = qtgui.qfont()
    font.setpointsize(14)
    self.winrate.setfont(font)
    self.winrate.setalignment(qtcore.qt.aligncenter)
    self.winrate.setobjectname("winrate")
    self.initcard = qtwidgets.qpushbutton(form)
    self.initcard.setgeometry(qtcore.qrect(60, 330, 121, 41))
    font = qtgui.qfont()
    font.setfamily("arial")
    font.setpointsize(14)
    font.setbold(true)
    font.setweight(75)
    self.initcard.setfont(font)
    self.initcard.setstylesheet("")
    self.initcard.setobjectname("initcard")
    self.userhandcards = qtwidgets.qlabel(form)
    self.userhandcards.setgeometry(qtcore.qrect(10, 260, 421, 41))
    font = qtgui.qfont()
    font.setpointsize(14)
    self.userhandcards.setfont(font)
    self.userhandcards.setalignment(qtcore.qt.aligncenter)
    self.userhandcards.setobjectname("userhandcards")
    self.lplayer = qtwidgets.qframe(form)
    self.lplayer.setgeometry(qtcore.qrect(10, 80, 201, 61))
    self.lplayer.setframeshape(qtwidgets.qframe.styledpanel)
    self.lplayer.setframeshadow(qtwidgets.qframe.raised)
    self.lplayer.setobjectname("lplayer")
    self.lplayedcard = qtwidgets.qlabel(self.lplayer)
    self.lplayedcard.setgeometry(qtcore.qrect(0, 0, 201, 61))
    font = qtgui.qfont()
    font.setpointsize(14)
    self.lplayedcard.setfont(font)
    self.lplayedcard.setalignment(qtcore.qt.aligncenter)
    self.lplayedcard.setobjectname("lplayedcard")
    self.rplayer = qtwidgets.qframe(form)
    self.rplayer.setgeometry(qtcore.qrect(230, 80, 201, 61))
    font = qtgui.qfont()
    font.setpointsize(16)
    self.rplayer.setfont(font)
    self.rplayer.setframeshape(qtwidgets.qframe.styledpanel)
    self.rplayer.setframeshadow(qtwidgets.qframe.raised)
    self.rplayer.setobjectname("rplayer")
    self.rplayedcard = qtwidgets.qlabel(self.rplayer)
    self.rplayedcard.setgeometry(qtcore.qrect(0, 0, 201, 61))
    font = qtgui.qfont()
    font.setpointsize(14)
    self.rplayedcard.setfont(font)
    self.rplayedcard.setalignment(qtcore.qt.aligncenter)
    self.rplayedcard.setobjectname("rplayedcard")
    self.player = qtwidgets.qframe(form)
    self.player.setgeometry(qtcore.qrect(40, 180, 171, 61))
    self.player.setframeshape(qtwidgets.qframe.styledpanel)
    self.player.setframeshadow(qtwidgets.qframe.raised)
    self.player.setobjectname("player")
    self.predictedcard = qtwidgets.qlabel(self.player)
    self.predictedcard.setgeometry(qtcore.qrect(0, 0, 171, 61))
    font = qtgui.qfont()
    font.setpointsize(14)
    self.predictedcard.setfont(font)
    self.predictedcard.setalignment(qtcore.qt.aligncenter)
    self.predictedcard.setobjectname("predictedcard")
    self.threelandlordcards = qtwidgets.qlabel(form)
    self.threelandlordcards.setgeometry(qtcore.qrect(140, 10, 161, 41))
    font = qtgui.qfont()
    font.setpointsize(16)
    self.threelandlordcards.setfont(font)
    self.threelandlordcards.setalignment(qtcore.qt.aligncenter)
    self.threelandlordcards.setobjectname("threelandlordcards")
    self.stop = qtwidgets.qpushbutton(form)
    self.stop.setgeometry(qtcore.qrect(260, 330, 111, 41))
    font = qtgui.qfont()
    font.setfamily("arial")
    font.setpointsize(14)
    font.setbold(true)
    font.setweight(75)
    self.stop.setfont(font)
    self.stop.setstylesheet("")
    self.stop.setobjectname("stop")
 
    self.retranslateui(form)
    self.initcard.clicked.connect(form.init_cards)
    self.stop.clicked.connect(form.stop)
    qtcore.qmetaobject.connectslotsbyname(form)
 
def retranslateui(self, form):
    _translate = qtcore.qcoreapplication.translate
    form.setwindowtitle(_translate("form", "ai欢乐斗地主--dragon少年"))
    self.winrate.settext(_translate("form", "胜率:--%"))
    self.initcard.settext(_translate("form", "开始"))
    self.userhandcards.settext(_translate("form", "手牌"))
    self.lplayedcard.settext(_translate("form", "上家出牌区域"))
    self.rplayedcard.settext(_translate("form", "下家出牌区域"))
    self.predictedcard.settext(_translate("form", "ai出牌区域"))
    self.threelandlordcards.settext(_translate("form", "三张底牌"))
    self.stop.settext(_translate("form", "停止"))

2. 手牌和出牌数据识别

接下来需要所有扑克牌的模板图片与游戏屏幕特定区域的截图进行对比,这样才能获取ai玩家手牌、底牌、每一轮出牌、三者关系(地主、地主上家、地主下家)。

识别ai玩家手牌及三张底牌:

我们可以截取游戏屏幕,根据固定位置来识别当前ai玩家的手牌和三张底牌。核心代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 牌检测结果滤波
def cards_filter(self, location, distance): 
    if len(location) == 0:
        return 0
    loclist = [location[0][0]]
    count = 1
    for e in location:
        flag = 1  # “是新的”标志
        for have in loclist:
            if abs(e[0] - have) <= distance:
                flag = 0
                break
        if flag:
            count += 1
            loclist.append(e[0])
    return count
 
# 获取玩家ai手牌
def find_my_cards(self, pos):
    user_hand_cards_real = ""
    img = pyautogui.screenshot(region=pos)
    for card in allcards:
        result = pyautogui.locateall(needleimage='pics/m' + card + '.png', haystackimage=img, confidence=self.myconfidence)
        user_hand_cards_real += card[1] * self.cards_filter(list(result), self.myfilter)
    return user_hand_cards_real
 
# 获取地主三张底牌
def find_three_landlord_cards(self, pos):
    three_landlord_cards_real = ""
    img = pyautogui.screenshot(region=pos)
    img = img.resize((349, 168))
    for card in allcards:
        result = pyautogui.locateall(needleimage='pics/o' + card + '.png', haystackimage=img,
                                     confidence=self.threelandlordcardsconfidence)
        three_landlord_cards_real += card[1] * self.cards_filter(list(result), self.otherfilter)
    return three_landlord_cards_real

效果如下所示:

我用Python做个AI出牌器斗地主把把赢

地主、地主上家、地主下家:

同理我们可以根据游戏屏幕截图,识别地主的图标,确认地主角色。核心代码如下:

?
1
2
3
4
5
6
7
# 查找地主角色
def find_landlord(self, landlord_flag_pos):
    for pos in landlord_flag_pos:
        result = pyautogui.locateonscreen('pics/landlord_words.png', region=pos, confidence=self.landlordflagconfidence)
        if result is not none:
            return landlord_flag_pos.index(pos)
    return none

这样我们就可以得到玩家ai手牌,其他玩家手牌(预测),地主三张底牌,三者角色关系,出牌顺序。核心代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# 坐标
self.myhandcardspos = (414, 804, 1041, 59# ai玩家截图区域
self.lplayedcardspos = (530, 470, 380, 160# 左侧玩家截图区域
self.rplayedcardspos = (1010, 470, 380, 160# 右侧玩家截图区域
self.landlordflagpos = [(1320, 300, 110, 140), (320, 720, 110, 140), (500, 300, 110, 140)]  # 地主标志截图区域(右-我-左)
self.threelandlordcardspos = (817, 36, 287, 136)      # 地主底牌截图区域,resize成349x168
 
def init_cards(self):
    # 玩家手牌
    self.user_hand_cards_real = ""
    self.user_hand_cards_env = []
    # 其他玩家出牌
    self.other_played_cards_real = ""
    self.other_played_cards_env = []
    # 其他玩家手牌(整副牌减去玩家手牌,后续再减掉历史出牌)
    self.other_hand_cards = []
    # 三张底牌
    self.three_landlord_cards_real = ""
    self.three_landlord_cards_env = []
    # 玩家角色代码:0-地主上家, 1-地主, 2-地主下家
    self.user_position_code = none
    self.user_position = ""
    # 开局时三个玩家的手牌
    self.card_play_data_list = {}
    # 出牌顺序:0-玩家出牌, 1-玩家下家出牌, 2-玩家上家出牌
    self.play_order = 0
    self.env = none
    # 识别玩家手牌
    self.user_hand_cards_real = self.find_my_cards(self.myhandcardspos)
    self.userhandcards.settext(self.user_hand_cards_real)
    self.user_hand_cards_env = [realcard2envcard[c] for c in list(self.user_hand_cards_real)]
    # 识别三张底牌
    self.three_landlord_cards_real = self.find_three_landlord_cards(self.threelandlordcardspos)
    self.threelandlordcards.settext("底牌:" + self.three_landlord_cards_real)
    self.three_landlord_cards_env = [realcard2envcard[c] for c in list(self.three_landlord_cards_real)]
    # 识别玩家的角色
    self.user_position_code = self.find_landlord(self.landlordflagpos)
    if self.user_position_code is none:
        items = ("地主上家", "地主", "地主下家")
        item, okpressed = qinputdialog.getitem(self, "选择角色", "未识别到地主,请手动选择角色:", items, 0, false)
        if okpressed and item:
            self.user_position_code = items.index(item)
        else:
            return
    self.user_position = ['landlord_up', 'landlord', 'landlord_down'][self.user_position_code]
    for player in self.players:
        player.setstylesheet('background-color: rgba(255, 0, 0, 0);')
    self.players[self.user_position_code].setstylesheet('background-color: rgba(255, 0, 0, 0.1);')
 
    # 整副牌减去玩家手上的牌,就是其他人的手牌,再分配给另外两个角色(如何分配对ai判断没有影响)
    for i in set(allenvcard):
        self.other_hand_cards.extend([i] * (allenvcard.count(i) - self.user_hand_cards_env.count(i)))
    self.card_play_data_list.update({
        'three_landlord_cards': self.three_landlord_cards_env,
        ['landlord_up', 'landlord', 'landlord_down'][(self.user_position_code + 0) % 3]:
            self.user_hand_cards_env,
        ['landlord_up', 'landlord', 'landlord_down'][(self.user_position_code + 1) % 3]:
            self.other_hand_cards[0:17] if (self.user_position_code + 1) % 3 != 1 else self.other_hand_cards[17:],
        ['landlord_up', 'landlord', 'landlord_down'][(self.user_position_code + 2) % 3]:
            self.other_hand_cards[0:17] if (self.user_position_code + 1) % 3 == 1 else self.other_hand_cards[17:]
    })
    print(self.card_play_data_list)
    # 生成手牌结束,校验手牌数量
    if len(self.card_play_data_list["three_landlord_cards"]) != 3:
        qmessagebox.critical(self, "底牌识别出错", "底牌必须是3张!", qmessagebox.yes, qmessagebox.yes)
        self.init_display()
        return
    if len(self.card_play_data_list["landlord_up"]) != 17 or \
        len(self.card_play_data_list["landlord_down"]) != 17 or \
        len(self.card_play_data_list["landlord"]) != 20:
        qmessagebox.critical(self, "手牌识别出错", "初始手牌数目有误", qmessagebox.yes, qmessagebox.yes)
        self.init_display()
        return
    # 得到出牌顺序
    self.play_order = 0 if self.user_position == "landlord" else 1 if self.user_position == "landlord_up" else 2

效果如下:

我用Python做个AI出牌器斗地主把把赢

3. ai出牌方案输出

下面我们就需要用到douzero开源的ai斗地主了。douzero项目地址:https://github.com/kwai/douzero。我们需要将该开源项目下载并导入项目中。

创建一个ai玩家角色,初始化游戏环境,加载模型,进行每轮的出牌判断,控制一局游戏流程的进行和结束。核心代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# 创建一个代表玩家的ai
ai_players = [0, 0]
ai_players[0] = self.user_position
ai_players[1] = deepagent(self.user_position, self.card_play_model_path_dict[self.user_position])
# 初始化游戏环境
self.env = gameenv(ai_players)
# 游戏开始
self.start()
 
def start(self):
    self.env.card_play_init(self.card_play_data_list)
    print("开始出牌\n")
    while not self.env.game_over:
        # 玩家出牌时就通过智能体获取action,否则通过识别获取其他玩家出牌
        if self.play_order == 0:
            self.predictedcard.settext("...")
            action_message = self.env.step(self.user_position)
            # 更新界面
            self.userhandcards.settext("手牌:" + str(''.join(
                [envcard2realcard[c] for c in self.env.info_sets[self.user_position].player_hand_cards]))[::-1])
 
            self.predictedcard.settext(action_message["action"] if action_message["action"] else "不出")
            self.winrate.settext("胜率:" + action_message["win_rate"])
            print("\n手牌:", str(''.join(
                    [envcard2realcard[c] for c in self.env.info_sets[self.user_position].player_hand_cards])))
            print("出牌:", action_message["action"] if action_message["action"] else "不出", ", 胜率:",
                  action_message["win_rate"])
            while self.have_white(self.rplayedcardspos) == 1 or \
                    pyautogui.locateonscreen('pics/pass.png',
                                             region=self.rplayedcardspos,
                                             confidence=self.landlordflagconfidence):
                print("等待玩家出牌")
                self.counter.restart()
                while self.counter.elapsed() < 100:
                    qtwidgets.qapplication.processevents(qeventloop.allevents, 50)
            self.play_order = 1
        elif self.play_order == 1:
            self.rplayedcard.settext("...")
            pass_flag = none
            while self.have_white(self.rplayedcardspos) == 0 and \
                    not pyautogui.locateonscreen('pics/pass.png',
                                                 region=self.rplayedcardspos,
                                                 confidence=self.landlordflagconfidence):
                print("等待下家出牌")
                self.counter.restart()
                while self.counter.elapsed() < 500:
                    qtwidgets.qapplication.processevents(qeventloop.allevents, 50)
            self.counter.restart()
            while self.counter.elapsed() < 500:
                qtwidgets.qapplication.processevents(qeventloop.allevents, 50)
            # 不出
            pass_flag = pyautogui.locateonscreen('pics/pass.png',
                                                 region=self.rplayedcardspos,
                                                 confidence=self.landlordflagconfidence)
            # 未找到"不出"
            if pass_flag is none:
                # 识别下家出牌
                self.other_played_cards_real = self.find_other_cards(self.rplayedcardspos)
            # 找到"不出"
            else:
                self.other_played_cards_real = ""
            print("\n下家出牌:", self.other_played_cards_real)
            self.other_played_cards_env = [realcard2envcard[c] for c in list(self.other_played_cards_real)]
            self.env.step(self.user_position, self.other_played_cards_env)
            # 更新界面
            self.rplayedcard.settext(self.other_played_cards_real if self.other_played_cards_real else "不出")
            self.play_order = 2
        elif self.play_order == 2:
            self.lplayedcard.settext("...")
            while self.have_white(self.lplayedcardspos) == 0 and \
                    not pyautogui.locateonscreen('pics/pass.png',
                                                region=self.lplayedcardspos,
                                                confidence=self.landlordflagconfidence):
                print("等待上家出牌")
                self.counter.restart()
                while self.counter.elapsed() < 500:
                    qtwidgets.qapplication.processevents(qeventloop.allevents, 50)
            self.counter.restart()
            while self.counter.elapsed() < 500:
                qtwidgets.qapplication.processevents(qeventloop.allevents, 50)
            # 不出
            pass_flag = pyautogui.locateonscreen('pics/pass.png',
                                                 region=self.lplayedcardspos,
                                                 confidence=self.landlordflagconfidence)
            # 未找到"不出"
            if pass_flag is none:
                # 识别上家出牌
                self.other_played_cards_real = self.find_other_cards(self.lplayedcardspos)
            # 找到"不出"
            else:
                self.other_played_cards_real = ""
            print("\n上家出牌:", self.other_played_cards_real)
            self.other_played_cards_env = [realcard2envcard[c] for c in list(self.other_played_cards_real)]
            self.env.step(self.user_position, self.other_played_cards_env)
            self.play_order = 0
            # 更新界面
            self.lplayedcard.settext(self.other_played_cards_real if self.other_played_cards_real else "不出")
        else:
            pass
 
        self.counter.restart()
        while self.counter.elapsed() < 100:
            qtwidgets.qapplication.processevents(qeventloop.allevents, 50)
 
    print("{}胜,本局结束!\n".format("农民" if self.env.winner == "farmer" else "地主"))
    qmessagebox.information(self, "本局结束", "{}胜!".format("农民" if self.env.winner == "farmer" else "地主"),
                            qmessagebox.yes, qmessagebox.yes)
    self.env.reset()
    self.init_display()

到这里,整个ai斗地主出牌流程基本已经完成了。

我用Python做个AI出牌器斗地主把把赢

三、出牌器用法

按照上述过程,这款ai出牌器已经制作完成了。后面应该如何使用呢?如果不想研究源码,只想使用这款ai斗地主出牌器,验证下效果,该怎么配置环境运行这个ai出牌器呢?下面就开始介绍。

1. 环境配置

首先我们需要安装这些第三方库,配置相关环境,如下所示:

?
1
2
3
4
5
6
7
8
9
torch==1.9.0
gitpython==3.0.5
gitdb2==2.0.6
pyautogui==0.9.50
pyqt5==5.13.0
pyqt5-sip==12.8.1
pillow>=5.2.0
opencv-python
rlcard

2. 坐标调整确认

我们可以打开游戏界面,将游戏窗口模式下最大化运行,把ai出牌器程序窗口需要移至右下角,不能遮挡手牌、地主标志、底牌、历史出牌这些关键位置。

其次我们要确认屏幕截图获取的各个区域是否正确。如果有问题需要进行区域位置坐标调整。

?
1
2
3
4
5
6
# 坐标
self.myhandcardspos = (414, 804, 1041, 59# 我的截图区域
self.lplayedcardspos = (530, 470, 380, 160# 左边截图区域
self.rplayedcardspos = (1010, 470, 380, 160# 右边截图区域
self.landlordflagpos = [(1320, 300, 110, 140), (320, 720, 110, 140), (500, 300, 110, 140)]  # 地主标志截图区域(右-我-左)
self.threelandlordcardspos = (817, 36, 287, 136)      # 地主底牌截图区域,resize成349x168

我用Python做个AI出牌器斗地主把把赢

3. 运行测试

当所有环境配置完成,各区域坐标位置确认无误之后,下面我们就可以直接运行程序,测试效果啦~

首先我们运行ai出牌器程序,打开游戏界面,进入游戏。当玩家就位,手牌分发完毕,地主身份确认之后,我们就可以点击画面中开始按钮,让ai来帮助我们斗地主了。

基于这个douzero项目做一个“成熟”的ai,项目开源地址【https://github.com/tianqiraf/douzero_for_happydoudizhu – tianqiraf】。

今天我们就到这里,明天继续努力!

我用Python做个AI出牌器斗地主把把赢

如果本篇博客有任何错误,请批评指教,不胜感激 !

到此这篇关于我用python做个ai出牌器斗地主把把赢的文章就介绍到这了,更多相关python自动出牌器内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/hhladminhhl/article/details/119304504?spm=1001.2014.3001.5501

延伸 · 阅读

精彩推荐