pythonAI五子棋(二)
来源:互联网 发布:js入门教程视频 编辑:程序博客网 时间:2024/06/05 18:48
以为第二篇很晚到来,主要是我的想法是等我把机器学习学个大概之后再回来优化。不过最近在深入的学习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的使用
效果:
扫描下面二维码添加我的公众号回复:五子棋,即可获取五子棋源码
阅读全文
0 0
- pythonAI五子棋(二)
- pythonAI五子棋
- SDL 实现五子棋 GUI (二)
- 五子棋(二)联网版
- 用javascript实现五子棋(二)
- QT项目二:五子棋游戏
- 自定义view(二)五子棋
- 五子棋
- 五子棋
- 五子棋
- 五子棋
- 五子棋
- 五子棋
- 五子棋
- 五子棋
- 五子棋
- 五子棋
- 五子棋
- Android Activity的4种启动模式详解(代码+截图)
- 普通网站的访问过程
- U3d经典必考面试题#持续更新##欢迎讨论交流#
- Java面试题集(51-70)
- impala 创建kudu表报错
- pythonAI五子棋(二)
- xinetd 托管服务:(超级守护进程服务)
- 八皇后问题——列出所有的解,可推至N皇后
- 【转】计算机视觉,计算机图形学和数字图像处理,三者之间的联系和区别
- Java网络编程知识-笔记四
- python-代码。遇到的错误集锦
- flume数据采集
- 栈和队列判断回文数
- 匿名函数、嵌套函数、闭包是怎么回事?