1 #-*- coding:utf-8 -*-
2
3 importcurses4 from random importrandrange, choice5 from collections importdefaultdict6 #引入3个扩展包
7
8 letter_codes = [ord(ch) for ch in 'WASDRQwasdrq']9 actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']10 actions_dict = dict(zip(letter_codes, actions * 2))11 #创建我们将要用的键盘输入字典,这个字典将在后边通过第18行的
12 #keyboard.getch()
13 #而这个方法被封装成一个函数,调用函数以实现该方法。
14
15 defget_user_action(keyboard):16 char = "N"
17 while char not inactions_dict:18 char =keyboard.getch()19 returnactions_dict[char]20 #键盘输入以匹配字典的方法
21
22 deftranspose(field):23 return [list(row) for row in zip(*field)]24 #矩阵转置,
25 #这是一个数学方法,如望详细了解,请先了解矩阵
26 #对于初学者,比较推荐暂时忽略。
27
28 definvert(field):29 return [row[::-1] for row infield]30 #矩阵逆转,同上
31
32 classGameField(object):33 def __init__(self, height=4, width=4, win=2048):34 self.height =height35 self.width =width36 self.win_value = 2048
37 self.score =038 self.highscore =039 self.reset()40 #定义类的__init__方法,为初始化方法
41
42 defreset(self):43 if self.score >self.highscore:44 self.highscore =self.score45 self.score =046 self.field = [[0 for i in range(self.width)] for j inrange(self.height)]47 self.spawn()48 self.spawn()49 #重置方法,虽然命名为reset,但是初始化也同样使用该方法。
50 #如果你觉得命名为set更合适,请改为set。
51 #这个方法中使用了spawn()函数,这个函数放在了后边,
52 #spawn()函数的功能是生成新的数字,reset()需要生成两次。
53
54
55 defmove(self, direction):56 #最重要的3个函数之一
57 defmove_row_left(row):58 deftighten(row):59 new_row = [i for i in row if i !=0]60 new_row += [0 for i in range(len(row) -len(new_row))]61 returnnew_row62
63 defmerge(row):64 pair =False65 new_row =[]66 for i inrange(len(row)):67 ifpair:68 new_row.append(2 *row[i])69 self.score += 2 *row[i]70 pair =False71 else:72 if i + 1 < len(row) and row[i] == row[i + 1]:73 pair =True74 new_row.append(0)75 else:76 new_row.append(row[i])77 assert len(new_row) ==len(row)78 returnnew_row79 returntighten(merge(tighten(row)))80 #这里可以有不同的写法,就是tighten一次,merge一次。在merge的时候没必要加0了。
81 #欢迎大家把好的方法发给我,谢谢。http://www.cnblogs.com/danjawwi/
82 #def merge(row):
83 #pair = False
84 #new_row = []
85 #for i in range(len(row)):
86 #if pair:
87 #new_row.append(2 * row[i])
88 #self.score += 2 * row[i]
89 #pair = False
90 #else:
91 #if i + 1 < len(row) and row[i] == row[i + 1]:
92 #pair = True
93 #else:
94 #new_row.append(row[i])
95 #new_row += [0 for j in range(len(row) - len(new_row))]
96 #return new_row
97 #98 #return merge(tighten(row))
99
100 moves ={}101 moves['Left'] = lambdafield: \102 [move_row_left(row) for row infield]103 moves['Right'] = lambdafield: \104 invert(moves['Left'](invert(field)))105 moves['Up'] = lambdafield: \106 transpose(moves['Left'](transpose(field)))107 moves['Down'] = lambdafield: \108 transpose(moves['Right'](transpose(field)))109 #这里把row的迭代放在了方法外边,在对应字典值这里实现了。也可以放在方法里边
110
111
112 if direction inmoves:113 ifself.move_is_possible(direction):114 self.field =moves[direction](self.field)115 self.spawn()116 returnTrue117 else:118 returnFalse119
120 defis_win(self):121 return any(any(i >= self.win_value for i in row) for row inself.field)122 #判断是否赢
123
124 defis_gameover(self):125 return not any(self.move_is_possible(move) for move inactions)126 #判断是否输
127
128 defdraw(self, screen):129 #最重要的3个函数之一
130 help_string1 = '(W)Up (S)Down (A)Left (D)Right'
131 help_string2 = '(R)Restart (Q)Exit'
132 gameover_string = 'GAME OVER'
133 win_string = 'YOU WIN!'
134 defcast(string):135 screen.addstr(string + '\n')136
137 defdraw_hor_separator():138 line = '+' + ('+------' * self.width + '+')[1:]139 #不明白为什么这里要这样写
140 #直接line = '+------' * self.width + '+' 不行吗?
141 #http://www.cnblogs.com/danjawwi/
142
143 separator = defaultdict(lambda: line)144 if not hasattr(draw_hor_separator, "counter"):145 draw_hor_separator.counter =0146 cast(separator[draw_hor_separator.counter])147 draw_hor_separator.counter += 1
148 #这里我也不明白,直接根据self.height输出不就行了?
149
150 defdraw_row(row):151 cast(''.join('|{: ^5}'.format(num) if num > 0 else '|' for num in row) + '|')152 #用到了join 和 format这两种方法。
153 screen.clear()154 cast('SCORE:' +str(self.score))155 if 0 !=self.highscore:156 cast('HGHSCORE:' +str(self.highscore))157 for row inself.field:158 draw_hor_separator()159 draw_row(row)160 draw_hor_separator()161 ifself.is_win():162 cast(win_string)163 else:164 ifself.is_gameover():165 cast(gameover_string)166 else:167 cast(help_string1)168 cast(help_string2)169
170 defspawn(self):171 new_element = 4 if randrange(100) > 89 else 2
172 (i,j) = choice([(i,j) for i in range(self.width) for j in range(self.height) if self.field[i][j] ==0])173 self.field[i][j] =new_element174 #迭代器既可以根据层级来进行迭代,也可以在同层中迭代两次
175
176 defmove_is_possible(self, direction):177 #最重要的3个函数之一
178 defrow_is_left_movable(row):179 defchange(i):180 if row[i] == 0 and row[i + 1] !=0:181 #这里是不是在说None != 0 ?
182 returnTrue183 if row[i] != 0 and row[i + 1] ==row[i]:184 returnTrue185 returnFalse186 return any(change(i) for i in range(len(row) - 1))187
188 check ={}189 check['Left'] = lambdafield: \190 any(row_is_left_movable(row) for row infield)191
192 check['Right'] = lambdafield: \193 check['Left'](invert(field))194
195 check['Up'] = lambdafield: \196 check['Left'](transpose(field))197
198 check['Down'] = lambdafield: \199 check['Right'](transpose(field))200
201 if direction incheck:202 returncheck[direction](self.field)203 else:204 returnFalse205
206 defmain(stdscr):207 definit():208 game_field.reset()209 return 'Game'
210
211 defnot_game(state):212 game_field.draw(stdscr)213 action =get_user_action(stdscr)214 responses = defaultdict(lambda: state)215 responses['Restart'], responses['Exit'] = 'Init', 'Exit'
216 returnresponses[action]217
218 defgame():219 game_field.draw(stdscr)220 action =get_user_action(stdscr)221
222 if action == 'Restart':223 return 'Init'
224 if action == 'Exit':225 return 'Exit'
226 ifgame_field.move(action):227 ifgame_field.is_win():228 return 'Win'
229 ifgame_field.is_gameover():230 return 'Gameover'
231 return 'Game'
232
233
234 state_actions ={235 'Init': init,236 'Win': lambda: not_game('Win'),237 'Gameover': lambda: not_game('Gameover'),238 'Game': game239 }240
241 curses.use_default_colors()242 game_field = GameField(win=32)243
244 state = 'Init'
245
246 while state != 'Exit':247 state =state_actions[state]()248
249 curses.wrapper(main)