您的位置:首页 > 编程语言 > Python开发

《200行Python代码实现2048》分析

2017-06-21 23:05 477 查看
实验地址:https://www.shiyanlou.com/courses/368

实验文档 https://www.shiyanlou.com/courses/368/labs/1172/document

1.有限状态机控制游戏逻辑

利用函数式编程,通过一个字典数据结构建立不同状态和函数之间的映射关系,不同的状态执行不同的函数并且获得新的状态。

while state != 'Exit':
state = state_actions[state]()


简要分析游戏运行过程:

程序的入口为

curses.wrapper(main)

然后从main开始执行

state = 'Init'

#状态机开始循环
while state != 'Exit':
state = state_actions[state]()


因为一开始是state = ‘Init’,所以执行
state_actions['Init']()
,获得新state“Game”

def init():
#重置游戏棋盘
game_field.reset()
return 'Game'


然后执行
state_actions[ 'Game']()
,获得新状态

def game():
#画出当前棋盘状态
game_field.draw(stdscr)
#读取用户输入得到action
action = get_user_action(stdscr)

if action == 'Restart':
return 'Init'
if action == 'Exit':
return 'Exit'
if game_field.move(action): # move successful
if game_field.is_win():
return 'Win'
if game_field.is_gameover():
return 'Gameover'
return 'Game'


2.defaultdict数据结构

defaultdict的产生背景是字典不能访问一个不存在的键。

参考:

http://blog.csdn.net/real_ray/article/details/17919289

例如:

separator = defaultdict(lambda: line)


defaultdict有多种初始化的方式,可以以一个匿名函数初始化,匿名函数的内容就是字典value的默认内容。

3.curses库

Linux的curses图形库,Python默认内置

http://www.cnblogs.com/starof/p/4703820.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: