用python创建桌面应用(二)
来源:互联网 发布:163邮箱注册软件 编辑:程序博客网 时间:2024/06/16 06:15
上一篇文章我们已经创建好了数据层,接下来我们创建核心逻辑层。在这里我们需要知道游戏是如何运行的,游戏的流程是什么样的。想一下我们玩游戏的时候,一开始有个登录界面,在这里不实现这个功能。然后有一些选择菜单,比如开始游戏,游戏难度,退出等等。对于这个井字棋游戏,首先向用户展示一个选项菜单,并包含开始一个游戏或继续一个被保存游戏的选项。无论哪种情况,一旦游戏被设置,就会展示主面板并且提示用户选择一个格子。然后计算分析这个移动并以它的移动作为应答。之后,面板被再次展示出来知道一方获胜。下面是原书的模块交互序列图:
''' This is the main logic for a Tic-tac-toe game.It is not optimised for a quality game it simplygenerates random moves and checks the results ofa move for a winning line. Exposed functions are:newGame()saveGame()restoreGame()userMove()computerMove()'''import os, randomimport oxo_datadef newGame():#返回一个拥有9个空格的新列表 ' return new empty game' return list(" " * 9)def saveGame(game): ' save game to disk ' oxo_data.saveGame(game) def restoreGame():#捕捉任何由于找不到数据文件所抛出的错误并验证保存游戏的长度 ''' restore previously saved game. If game not restored successfully return new game''' try: game = oxo_data.restoreGame() if len(game) == 9: return game else: return newGame() except IOError: return newGame() def _generateMove(game):#寻找当前游戏中没有被使用的格子,然后随机选择一个格子来防止计算机的移动 ''' generate a random cell from thiose available. If all cells are used return -1''' options = [i for i in range(len(game)) if game[i] == " "] if options: return random.choice(options) else: return -1 def _isWinningMove(game):#判断输赢 wins = ((0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6)) for a,b,c in wins: chars = game[a] + game[b] + game[c] if chars == 'XXX' or chars == 'OOO': return True return Falsedef userMove(game,cell):#用户移动 if game[cell] != ' ': raise ValueError('Invalid cell') else: game[cell] = 'X' if _isWinningMove(game): return 'X' else: return ""def computerMove(game):#计算机移动 cell = _generateMove(game) if cell == -1: return 'D' game[cell] = 'O' if _isWinningMove(game): return 'O' else: return ""def test(): #测试函数 result = "" game = newGame() while not result: print(game) try: result = userMove(game, _generateMove(game)) except ValueError: print("Oops, that shouldn't happen") if not result: result = computerMove(game) if not result: continue elif result == 'D': print("Its a draw") else: print("Winner is:", result) print(game)if __name__ == "__main__": test()
上面的文件名为:oxo_logic.py 0 0
- 用python创建桌面应用(二)
- 用python创建桌面应用(一)
- 用python创建桌面应用(三)
- 用python创建桌面应用(四)
- python-创建桌面应用--了解
- Electron 创建桌面应用
- HTML+CSS+python+qtwebkit打造跨平台桌面应用(二)
- python 创建桌面快捷方式
- android 应用创建桌面快捷方式
- 创建自身应用桌面快捷方式
- 创建应用快捷方式到桌面
- Electron创建一个桌面应用
- 探讨Java之桌面应用的可行性(二)
- 使用WPF创建一个Digg桌面应用
- Android为应用在桌面创建快捷方式
- Android 为应用创建、删除桌面快捷方式
- 2、ubuntu应用-创建软件桌面快捷方式
- 如何在Ubuntu桌面创建应用启动器
- 练习1
- 【2017/4/23】oracle之sql(二)
- 过拟合
- maven:资源过滤的介绍
- RabbitMQ消息队列知识点归纳
- 用python创建桌面应用(二)
- SVN简单概述
- (ZT)clear icon cache
- 颜色矩原理及C++实现
- 集合框架-泛型接口的概述和使用
- Android 人品计算器
- 第三十九讲项目一 判断n是否是完数
- 电商秒杀系统设计分析
- PPTP源码流程分析图