-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththrees.py
199 lines (169 loc) · 5.45 KB
/
threes.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
''' Basic Python implementation of Threes! '''
try:
import numpy as np
except:
print("""Oops!\nYou need to get numpy for this to work.
To do this, do pip install numpy.
If that doesn't work, do it from an admin command prompt.
Sorry for that.""")
import time
import sys
if input("Exit(Y/n):").lower() == 'y':
#sys.exit(0)
quit(True)
__author__ = 'Robert Xiao <nneonneo@gmail.com>'
def to_val(x):
x = np.asarray(x)
return np.where(x < 3, x, 3*2**(x-3))
def to_score(x):
x = np.asarray(x)
return np.where(x < 3, 0, 3**(x-2))
def find_fold(line):
''' find the position where the line folds, assuming it folds towards the left. '''
for i in range(3):
if line[i] == 0:
return i
elif (line[i], line[i+1]) in ((1,2), (2,1)):
return i
elif line[i] == line[i+1] and line[i] >= 3:
return i
return -1
def do_fold(line, pos):
if line[pos] == 0:
line[pos] = line[pos+1]
elif line[pos] < 3:
line[pos] = 3
else:
line[pos] += 1
line[pos+1:-1] = line[pos+2:]
line[-1] = 0
return line
def get_lines(m, dir):
if dir == 0: # up
return [m[:,i] for i in range(4)]
elif dir == 1: # down
return [m[::-1,i] for i in range(4)]
elif dir == 2: # left
return [m[i,:] for i in range(4)]
elif dir == 3: # right
return [m[i,::-1] for i in range(4)]
def make_deck():
import random
deck = [1]*4 + [2]*4 + [3]*4
random.shuffle(deck)
return deck
def do_move(m, move):
lines = get_lines(m, move)
folds = [find_fold(l) for l in lines]
changelines = []
for i in range(4):
if folds[i] >= 0:
do_fold(lines[i], folds[i])
changelines.append(lines[i])
return changelines
def find_max_for_2d_board(deck):
#return "Not working... :-("#For testing reasons
## if deck[0][0] !=None:return True
## else:raise LookupError("NOT TRUE")
MAX = 0
for spam in deck:
if max(spam)>MAX:MAX = max(spam)
return MAX
def play_game():
''' Non-interactive play_game function. Yields (board, next_tile, valid_moves) tuples.
Send your next move in via the generator .send.
Raises StopIteration when the game is over.'''
import random
deck = make_deck()
pos = random.sample(range(16), 9)
m = np.zeros((16,), dtype=int)
m[pos] = deck[:len(pos)]
deck = deck[len(pos):]
m = m.reshape((4,4))
while True:
lineset = [get_lines(m, i) for i in range(4)]
foldset = [[find_fold(l) for l in lineset[i]] for i in range(4)]
valid = [i for i in range(4) if any(f >= 0 for f in foldset[i])]
# TODO: Update random tile generation to account for new pick-three implementation
maxval = m.max()
if maxval >= 7 and random.random() < 1/24.:
if maxval <= 9:
tileset = range(4, maxval-2)
else:
top = random.choice(range(6, maxval-2))
tileset = range(top-2, top+1)
else:
if not deck:
deck = make_deck()
tileset = [deck.pop()]
move = yield m, tileset, valid
if not valid:
break
changelines = do_move(m, move)
random.choice(changelines)[-1] = random.choice(tileset)
def play_game_interactive():
game = play_game()
move = None
while True:
for a in range(33):print()
m, tileset, valid = game.send(move)
print(to_val(m))
if not valid:
print("Game over.")
print("Your score is", to_score(m).sum())
break
print('next tile:', list(to_val(tileset)))
print('Max tile: %d'%find_max_for_2d_board(to_val(m)))
movelist = ''.join('UDLR'[i] for i in valid)
while True:
move = input('Move [%s]? ' % movelist).upper()
if move not in movelist:
print("Invalid move.")
continue
move = 'UDLR'.find(move)
break
def play_game_interactive2():
game = play_game()
move = None
while True:
for a in range(3):print()
m, tileset, valid = game.send(move)
print(to_val(m))
if not valid:
print("Game over.")
print("Your score is", to_score(m).sum())
break
print('next tile:', list(to_val(tileset)))
print('Max tile: %d'%find_max_for_2d_board(to_val(m)))
movelist = ''.join('UDLR'[i] for i in valid)
while True:
move = input('Move [%s]? ' % movelist).upper()
if move not in movelist:
print("Invalid move.")
continue
move = 'UDLR'.find(move)
break
def play_game_interactive3():
game = play_game()
move = None
while True:
m, tileset, valid = game.send(move)
print(to_val(m))
if not valid:
print("Game over.")
print("Your score is", to_score(m).sum())
break
print('next tile:', list(to_val(tileset)))
movelist = ''.join('UDLR'[i] for i in valid)
while True:
move = input('Move [%s]? ' % movelist).upper()
## if move == 'exit'.upper():sys.exit()
if move not in movelist:
print("Invalid move.")
continue
move = 'UDLR'.find(move)
break
if __name__ == '__main__':
play_game_interactive2()
##else:
## play_game_interactive()