-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathpython-2048.py
executable file
·182 lines (174 loc) · 6 KB
/
python-2048.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/usr/bin/env python
# encoding: utf-8
"""
The minigame 2048 in python
"""
import random
def init():
"""
initialize a 2048 matrix. return a matrix list
"""
matrix = [ 0 for i in range(16) ]
random_lst = random.sample( range(16), 2 ) # generate 2 different number
matrix[random_lst[0]] = matrix[random_lst[1]] = 2
return matrix
def move(matrix,direction):
"""
moving the matrix. return a matrix list
"""
mergedList = [] #initial the merged index
if direction == 'w':
for i in range(16):
j = i
while j - 4 >= 0:
if matrix[j-4] == 0:
matrix[j-4] = matrix[j]
matrix[j] = 0
elif matrix[j-4] == matrix[j] and j not in mergedList:
matrix[j-4] *=2
matrix[j] = 0
mergedList.append(j-4)
mergedList.append(j) #prevent the number to be merged twice
print mergedList
print matrix
j -= 4
elif direction == 's':
for i in range(15,-1,-1):
j = i
while j + 4 < 16:
if matrix[j+4] == 0:
matrix[j+4] = matrix[j]
matrix[j] = 0
elif matrix[j+4] == matrix[j] and j not in mergedList:
matrix[j+4] *=2
matrix[j] = 0
mergedList.append(j)
mergedList.append(j+4)
j += 4
elif direction == 'a':
for i in range(16):
j = i
while j % 4 != 0:
if matrix[j-1] == 0:
matrix[j-1] = matrix[j]
matrix[j] = 0
elif matrix[j-1] == matrix[j] and j not in mergedList:
matrix[j-1] *=2
matrix[j] = 0
mergedList.append(j-1)
mergedList.append(j)
j -= 1
else:
for i in range(15,-1,-1):
j = i
while j % 4 != 3:
if matrix[j+1] == 0:
matrix[j+1] = matrix[j]
matrix[j] = 0
elif matrix[j+1] == matrix[j] and j not in mergedList:
matrix[j+1] *=2
matrix[j] = 0
mergedList.append(j)
mergedList.append(j+1)
j += 1
return matrix
def insert(matrix):
"""insert one 2 or 4 into the matrix. return the matrix list
"""
getZeroIndex = []
for i in range(16):
if matrix[i] == 0:
getZeroIndex.append(i)
randomZeroIndex = random.choice(getZeroIndex)
matrix[randomZeroIndex] = 2
return matrix
def output(matrix):
"""
print the matrix. return the matrix list
"""
max_num_width = len(str(max(matrix)))
conver2char = lambda num :'{0:>{1}}'.format(num, max_num_width) \
if num>0 else ' '*max_num_width
demarcation = ( '+' + '-'*(max_num_width+2) ) * 4 + '+' #generate demarcation line like '+---+---+---+'
print(demarcation)
print(('\n'+demarcation+'\n').join(['| '+' | '.join([ conver2char(num)
for num in matrix[i*4:(i+1)*4]])+' |' for i in range(4)]))
print(demarcation)
def isOver(matrix):
"""is game over? return bool
"""
if 0 in matrix:
return False
else:
for i in range(16):
if i % 4 != 3:
if matrix[i] == matrix[i+1]:
return False
if i < 12:
if matrix[i] == matrix [i+4]:
return False
return True
def getchar(prompt="Wait input: "):
import termios, sys
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~termios.ICANON # lflags
try:
termios.tcsetattr(fd, termios.TCSADRAIN, new)
sys.stderr.write(prompt)
sys.stderr.flush()
c = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
return c
def play():
matrix = init()
vim_mode = False
vim_map = {'h':'a', 'j':'s', 'k':'w', 'l':'d'}
matrix_stack = [] # just used by back function
matrix_stack.append(list(matrix))
step = len(matrix_stack) - 1
while True:
output(matrix)
if isOver(matrix) == False:
if max(matrix) == 2048:
input = raw_input('The max number is 2048, win the goal! q for quit, others for continue. ')
if input == 'q':
exit()
while True:
prompt = "[NORMAL] w(up)/s(down)/a(left)/d(right)"
if vim_mode:
prompt = "[VIM MODE] h:left, j:down, k:up, l:right"
input = getchar(prompt = 'Step {0:2d} {1} q(quit) b(back) v(vim_mode): '.format(step,prompt))
if vim_mode:
input = vim_map.get(input, input)
print('get:', input)
if input in ['w', 's', 'a', 'd']:
matrix = move(matrix,input)
if matrix == matrix_stack[-1]:
print('Not chaged. Try another direction.')
else:
insert(matrix)
matrix_stack.append(list(matrix))
break
elif input == 'b':
if len(matrix_stack) == 1:
print('Cannot back anymore...')
continue
matrix_stack.pop()
matrix = list(matrix_stack[-1])
break
elif input == 'q':
print('Byebye!')
exit()
elif input == 'v':
vim_mode = not vim_mode
else:
print('Input error! Try again.')
else:
print('Cannot move anyway. Game Over...')
exit()
step = len(matrix_stack) - 1
if __name__ == '__main__':
play()