pythonAI五子棋(二)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_37720172/article/details/78302943

以为第二篇很晚到来,主要是我的想法是等我把机器学习学个大概之后再回来优化。不过最近在深入的学习python,学到了一些pythonic的代码风格,所以决定回来重构一下我的五子棋代码

这次主要做了

1.优化了我的代码,使得代码更加简洁美观。可读性更高。

比如这段优化前的函数:

def robotChess(self):
        if self.player == 0:
            if len(self.bla_chessed) == 0 and len(self.whi_chessed) == 0:
                self.bla_chessed.append([25 + 30 * 7, 25 + 30 * 7, self.player % 2])
                self.can.create_oval(25 + 30 * 7 - 11, 25 + 30 * 7 - 11, 25 + 30 * 7 + 11, 25 + 30 * 7 + 11,
                                     fill="black")
                self.board[7][7] = 1
                return
            else:
                _x, _y, _ = self.robot.MaxValue_po(1, 0)
                #print([_x, _y], [x, y])
                newPoint = [_x * 30 + 25, _y * 30 + 25]
                self.can.create_oval(newPoint[0] - 11, newPoint[1] - 11, newPoint[0] + 11, newPoint[1] + 11,
                                     fill="black")
                self.bla_chessed.append([newPoint[0], newPoint[1], self.player % 2])
                self.board[_x][_y] = 0
        else:
            _x, _y, _ = self.robot.MaxValue_po(0, 1)
            newPoint = [_x * 30 + 25, _y * 30 + 25]
            self.can.create_oval(newPoint[0] - 11, newPoint[1] - 11, newPoint[0] + 11, newPoint[1] + 11,
                                 fill="white")
            self.whi_chessed.append([newPoint[0], newPoint[1], self.player % 2])
            self.board[_x][_y] = 1

优化后:

    def robotChess(self):
        """机器人下棋"""
        if self.player == 0:

            if len(self.bla_chessed) == 0 and len(self.whi_chessed) == 0:
                '''电脑执黑棋,开局优化'''
                self.draw_a_chess(*self.bla_start_pos, player=0)
                return

            else:
                _x, _y, _ = self.robot.MaxValue_po(0, 1)
                newPoint = pos_in_board(_x, _y)
                self.draw_a_chess(*newPoint, player=0)
        else:#白棋下
            _x, _y, _ = self.robot.MaxValue_po(1, 0)
            newPoint = pos_in_board(_x, _y)
            self.draw_a_chess(*newPoint, player=1)

很明显代码更加简洁,不会看起来很混乱


2.添加了注释,可以帮助阅读


3.运用了一些pythonic的写法,特别是大量运用拆包,使得代码可以很简洁,没有那么多看起来那么多的变量。还有将一些有重复性的功能模块化,减少了整体的代码量。

如果不知道拆包是什么,请看我的另一篇博文:Python进阶(一):python技巧

比如这一段代码就运用:

if len(self.whi_chessed) != 0:
    for tmp in self.whi_chessed:
    oval = pos_to_draw(*tmp[0:2])
    self.can.create_oval(oval, fill="white")

其中第三行:

oval = pos_to_draw(*tmp[0:2])

*temp[0:2]实际相当于tmp[0],tmp[1]

而pos_to_draw的原函数是:

def pos_to_draw(*args):
    """计算棋子在棋盘的顶,底,左,右的位置"""
    x, y = args
    return x - 11, y - 11, x + 11, y + 11

这里*arg运用到另一个知识点,请看: Python进阶(三):*args,**kwargs的使用


效果:
这里写图片描述


扫描下面二维码添加我的公众号回复:五子棋,即可获取五子棋源码
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_37720172/article/details/78302943