2048 for Python

真是办公室偷闲小能手,嘿嘿。(下图右上角就是游戏运行界面)

python2048

一闪一闪的,是因为我使用全局热键唤出或者隐匿 iTerm2 ,这个软件的一些技巧和配色我之前有做过较为详细的说明

输入

1
2
3
letter_codes = [ord(ch) for ch in 'WASDRQwasdrq']
actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']
actions_dict = dict(zip(letter_codes, actions * 2))

考虑到大小写,所以用数组 WASDRQwasdrqact x 2 中的操作一一对应。

1
2
3
4
5
def get_user_action(keyboard):
char = "N"
while char not in actions_dict:
char = keyboard.getch()
return actions_dict[char]

除了 Nactions_dict 之外的字符输入都是无效的,阻塞循环等待。

矩阵的操作

1
2
3
4
5
def transpose(field):
return [list(row) for row in zip(*field)]

def invert(field):
return [row[::-1] for row in field]

分别是用来转置和逆转矩阵用的。(上下操作矩阵用转置,左右才做矩阵用逆转)

棋盘初始化

1
2
3
4
5
6
7
def __init__(self, height=4, width=4, win=2048):
self.height = height
self.width = width
self.win_value = win
self.score = 0
self.highscore = 0
self.reset()

绘制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def draw(self, screen):
help_string1 = '(W)Up (S)Down (A)Left (D)Right'
help_string2 = ' (R)Restart (Q)Exit'
gameover_string = ' GAME OVER'
win_string = ' YOU WIN!'
def cast(string):
screen.addstr(string + '\n')

def draw_hor_separator():
line = '+' + ('+------' * self.width + '+')[1:]
separator = defaultdict(lambda: line)
if not hasattr(draw_hor_separator, "counter"):
draw_hor_separator.counter = 0
cast(separator[draw_hor_separator.counter])
draw_hor_separator.counter += 1

def draw_row(row):
cast(''.join('|{: ^5} '.format(num) if num > 0 else '| ' for num in row) + '|')

screen.clear()
cast('SCORE: ' + str(self.score))
if 0 != self.highscore:
cast('HIGHSCORE: ' + str(self.highscore))
for row in self.field:
draw_hor_separator()
draw_row(row)
draw_hor_separator()
if self.is_win():
cast(win_string)
else:
if self.is_gameover():
cast(gameover_string)
else:
cast(help_string1)
cast(help_string2)

绘制水平和垂直方向的线条,以及最高分的显示。

棋盘操作

重置
1
2
3
4
5
6
7
def reset(self):
if self.score > self.highscore:
self.highscore = self.score
self.score = 0
self.field = [[0 for i in range(self.width)] for j in range(self.height)]
self.spawn()
self.spawn()
随机添加
1
2
3
4
def spawn(self):
new_element = 4 if randrange(100) > 89 else 2
(i,j) = choice([(i,j) for i in range(self.width) for j in range(self.height) if self.field[i][j] == 0])
self.field[i][j] = new_element

spawn 是卵,繁殖的意思,随机添加 2 或者 4 。

移动

虽然有四个方向的操作,但是通过对矩阵的转置和逆转,我们只要对一个方向进行处理,别的方向上操作,转化过来就行了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def move(self, direction):
def move_row_left(row):
def tighten(row): # squeese non-zero elements together
new_row = [i for i in row if i != 0]
new_row += [0 for i in range(len(row) - len(new_row))]
return new_row

def merge(row):
pair = False
new_row = []
for i in range(len(row)):
if pair:
new_row.append(2 * row[i])
self.score += 2 * row[i]
pair = False
else:
if i + 1 < len(row) and row[i] == row[i + 1]:
pair = True
new_row.append(0)
else:
new_row.append(row[i])
assert len(new_row) == len(row)
return new_row
return tighten(merge(tighten(row)))

moves = {}
moves['Left'] = lambda field: \
[move_row_left(row) for row in field]
moves['Right'] = lambda field: \
invert(moves['Left'](invert(field)))
moves['Up'] = lambda field: \
transpose(moves['Left'](transpose(field)))
moves['Down'] = lambda field: \
transpose(moves['Right'](transpose(field)))

if direction in moves:
if self.move_is_possible(direction):
self.field = moves[direction](self.field)
self.spawn()
return True
else:
return False

棋盘的合并都是先消除中间的空格再合并相邻的数字。tighten 是靠拢,merge 是合并。

判断是否能移动
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def move_is_possible(self, direction):
def row_is_left_movable(row):
def change(i): # true if there'll be change in i-th tile
if row[i] == 0 and row[i + 1] != 0: # Move
return True
if row[i] != 0 and row[i + 1] == row[i]: # Merge
return True
return False
return any(change(i) for i in range(len(row) - 1))

check = {}
check['Left'] = lambda field: \
any(row_is_left_movable(row) for row in field)

check['Right'] = lambda field: \
check['Left'](invert(field))

check['Up'] = lambda field: \
check['Left'](transpose(field))

check['Down'] = lambda field: \
check['Right'](transpose(field))

if direction in check:
return check[direction](self.field)
else:
return False

能移动就两种情况,一是有空格,一是有相邻位有相同的数字。

状态

先分析游戏都有哪些的状态,初始化(Init),游戏中(Game),获胜(Win),失败(GameOver),退出(Exit),如下图:

屏幕快照 2017-06-18 下午8.10.50

然后各个状态之间通过对应的方法联通。

补充主逻辑的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def init():
#重置游戏棋盘
game_field.reset()
return 'Game'

def not_game(state):
#画出 GameOver 或者 Win 的界面
game_field.draw(stdscr)
#读取用户输入得到action,判断是重启游戏还是结束游戏
action = get_user_action(stdscr)
responses = defaultdict(lambda: state) #默认是当前状态,没有行为就会一直在当前界面循环
responses['Restart'], responses['Exit'] = 'Init', 'Exit' #对应不同的行为转换到不同的状态
return responses[action]

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'


state_actions = {
'Init': init,
'Win': lambda: not_game('Win'),
'Gameover': lambda: not_game('Gameover'),
'Game': game
}

curses.use_default_colors()
game_field = GameField(win=1024)


state = 'Init'

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

代码来源