-
Notifications
You must be signed in to change notification settings - Fork 0
/
tetris.py
executable file
·424 lines (362 loc) · 9.96 KB
/
tetris.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
#!/usr/bin/env python3
# program to play tetris on frozen-bottle setup using cursor-key input on terminal.
import socket
import time
import sys
import random
import argparse
import LedClientBase
import hex
import noncanon_input
import gamecontroller
DEFAULT_PORT = 8901
class brickdef(object):
__slots__ = ('shape','colorindex')
def __init__(self,shape,colorindex):
self.shape = tuple(shape)
self.colorindex = int(colorindex)
BRICK_BAR = brickdef( ((-1,0),(0,0),(1,0)) , 1 )
BRICK_CURV = brickdef( ((-1,0),(0,0),(1,1)) , 2 )
BRICK_DIAMOND= brickdef( ((-1,0),(0,0),(1,1),(0,1)) , 3 )
BRICK_CROOK = brickdef( ((-1,0),(0,0),(1,0),(0,1)) , 4 )
all_brickdefs = (BRICK_BAR,BRICK_CURV,BRICK_DIAMOND,BRICK_CROOK)
colrgb = (
b"\x00\x00\x00",b"\xE0\x00\x00",b"\x00\xE0\x00",b"\x00\x00\xE0",
b"\xC0\xC0\x00",b"\xC0\xA0\x50",b"\x00\x00\x00",b"\x00\x00\x00",
b"\x00\x00\x00",b"\x00\x00\x00",b"\x00\x00\x00",b"\x00\x00\x00",
b"\x00\x00\x00",b"\x00\x00\x00",b"\xE0\xE0\xE0",b"\x60\x60\x60"
)
class brick(object):
__slots__ = ('field','bdef','w','h','dir','slide_right')
# transforms for the six rotations
xforms = (hex.HexBuff.XFORM_UNITY,hex.HexBuff.XFORM_ROT60,hex.HexBuff.XFORM_ROT120,hex.HexBuff.XFORM_ROT180,hex.HexBuff.XFORM_ROT240,hex.HexBuff.XFORM_ROT300)
def __init__(self,field,brickdf):
if not isinstance(brickdf,brickdef) or not isinstance(field,hex.HexBuff):
raise TypeError("need a hex.HexBuff and a brickdef")
self.field = field
self.bdef = brickdf
self.w , self.h = self.find_center_of_top_row()
self.dir = 0
self.slide_right = True
valid=False
for h in range(self.h,-1,-1):
if self.doesfit(self.w,h,self.xforms[self.dir]):
self.h = h
valid=True
break
if not valid:
raise Exception("cannot place brick. all blocked.")
def doesfit(self,w,h,xform):
if w<0 or h<0 or w>=self.field.w or h>=self.field.h:
return False
mt = hex.HexBuff.transform_list_of_tuples(self.bdef.shape,xform)
for dw,dh in mt:
if self.field.get_wh(dw+w,dh+h)!=0:
return False
return True
def slide_down(self,pref_dw=0):
toRgt = self.slide_right
if pref_dw<0:
toRgt=False
if pref_dw>0:
toRgt=True
# attempt to slide down, both dirs.
dwl=(0,-1)
if not toRgt:
dwl=(-1,0)
for dw in dwl:
if self.doesfit(self.w+dw,self.h-1,self.xforms[self.dir]):
self.h -= 1
self.w += dw
self.slide_right = (dw==0)
return True
return False
def move_sideways(self,dw=1):
if dw>=0:
dw=1
else:
dw=-1
self.slide_right = (dw>=0)
if self.doesfit(self.w+dw,self.h,self.xforms[self.dir]):
self.w += dw
return True
return False
def try_rotate(self, ddir=-1):
# try to rotate. This might need to shift position to match.
xform = self.xforms[(self.dir+6+ddir)%6]
trypos = list()
trypos.append((0,0))
trypos.extend(hex.dir_wh)
for dw,dh in trypos:
if self.doesfit(self.w+dw,self.h,xform):
self.w += dw
self.h += dh
self.dir = (self.dir+6+ddir)%6
return True
return False
def render(self,add_colors=True):
mt = hex.HexBuff.transform_list_of_tuples(self.bdef.shape,self.xforms[self.dir])
col = self.bdef.colorindex
if not add_colors:
col = 0
for dw,dh in mt:
dw += self.w
dh += self.h
if self.field.get_wh(dw,dh) is not None:
self.field.set_wh(dw,dh,col)
def find_center_of_top_row(self):
for h in range(self.field.h-1,-1,-1):
mn,mx = 4096,-4096
for w in range(self.field.w):
if self.field.get_wh(w,h) is not None:
mn = min(mn,w)
mx = max(mx,w)
if mn<=mx:
return (mn+mx)>>1,h
raise Exception("no valid spaces in field???")
class game(object):
__slots__ = ('field','brk','state','delayp','delay','fulllines','score','next_bdef')
# states: 0=normal, 1=flash lines, 2=gameover
def __init__(self,field):
if not isinstance(field,hex.HexBuff):
raise TypeError("need a hex.HexBuff")
self.field = field
self.brk = None
self.state = 0
self.delayp = 6000
self.delay = 0
self.fulllines = None
self.score = 0
self.next_bdef = self.pickbrick()
for x in range(1,14,1):
self.field.set_wh(x,1,1)
for x in range(2,13,1):
self.field.set_wh(x,2,2)
def reset(self):
self.delayp = 6000
self.score = 0
def pickbrick(self):
return all_brickdefs[random.randint(0,len(all_brickdefs)-1)]
def step(self,userinput=[]):
if not isinstance(userinput,list):
raise TypeError("userinput should be list.")
if self.state==0:
self.step0(userinput)
elif self.state==1:
self.step1(userinput)
elif self.state==2:
self.step2(userinput)
elif self.state==3:
self.step3(userinput)
else:
raise Exception("invalid state "+repr(self.state))
def step0(self,inputs):
# normal run.
if self.brk is None:
try:
self.brk = brick(self.field,self.next_bdef)
self.brk.render(True)
self.next_bdef = self.pickbrick()
#print("added new brick")
except Exception:
# cannot spawn new brick. game lost.
self.state=2
return
for inp in inputs:
# proc user-input
if inp=="\x1b[D":
self.brk.render(False)
self.brk.move_sideways(-1)
self.brk.render(True)
if inp=="\x1b[C":
self.brk.render(False)
self.brk.move_sideways(1)
self.brk.render(True)
if inp=="\x1b[A":
self.brk.render(False)
self.brk.try_rotate(-1)
self.brk.render(True)
if inp=="\x1b[1":
self.brk.render(False)
self.brk.try_rotate(1)
self.brk.render(True)
if inp=="\x1b[B":
self.delay=0
if inp in (" ","\n","\r"):
self.delay=0
clearboard(self.field, self)
self.state=0
return
# process auto-movedown
self.delay-=1000
if self.delay<=0:
self.delay += self.delayp
self.brk.render(False)
res = self.brk.slide_down(0)
self.brk.render(True)
if not res:
# not ok. is landed.
# erase brick. will have new one next tick.
self.brk = None
# check if any lines are full
self.fulllines = find_full_lines(self.field)
if len(self.fulllines)>0:
self.delay=3000
self.state = 1
fl = len(self.fulllines)
self.score += fl+fl
self.delayp *= 0.98
highlight_lines(self.field,self.fulllines)
return
def step1(self,inputs):
# flash finished lines
self.delay-=1000
if self.delay>0:
return
move_down_rest(self.field,self.fulllines)
self.delay = self.delayp
self.state = 0
def step2(self,inputs):
# game over
for inp in inputs:
if inp in (" ","\n","\r"):
self.delay=0
clearboard(self.field, self)
self.state=0
break
def step3(self,inputs):
# doh?
pass
def main(args):
parser = argparse.ArgumentParser()
parser.add_argument("address",type=str,help="UDP address")
parser.add_argument("-p","--port",type=int,help="UDP port number")
aa = parser.parse_args()
print(repr(aa))
port = DEFAULT_PORT
address = "127.0.0.1"
if aa.port is not None:
port = aa.port
if port<=0 or port==0xFFFF:
sys.stderr.write("bad port number %u\n"%port)
return 1
if aa.address is not None:
address = aa.address
# start input
try:
tio = gamecontroller.GameController()
tio.start()
except:
tio = noncanon_input.cio()
# connect to socket
if not LedClientBase.connect(address,port):
return 1
t = 0.0
# build array matrix.
field = LedClientBase.get_matching_HexBuff(0,1)
brk = brick(field,BRICK_CURV)
tickdown_time = 2
next_tickdown = tickdown_time
gam = game(field)
for i in range(0x7FFF0000):
# do game.
c = []
while True:
cc = tio.getch()
if cc is not None:
c.append(cc)
else:
break
# make sure the list contains at least None
if not c:
c.append(None)
gam.step(c)
# convert to color-LED-string
lin = list()
for j in range(LedClientBase.NUMLEDS):
(xx,yy) = LedClientBase.seq_2_pos(j)
colidx = field.get_xy(xx,yy)
if colidx is None:
colidx = 15
lin.append(colrgb[colidx])
# build scoreline
_s = gam.score
_s = b"".join(colrgb[15*((_s>>b)&1)] for b in range(12))
_s = colrgb[gam.next_bdef.colorindex] + _s
_s = mix_col_liness(_s,b"".join(lin[-13:]),2,1)
del lin[-13:]
lin.append(_s)
#send
LedClientBase.send(b"".join(lin))
#loop-delay
time.sleep(0.1)
t += 0.100
LedClientBase.closedown()
return 0
def find_full_lines(field):
res = list()
for h in range(field.h):
bm=0
for w in range(field.w):
c = field.get_wh(w,h)
if c is not None:
if c==0:
bm |= 1
else:
bm |= 2
if bm==2: # only full spaces (no empty, and at least one full)
res.append(h)
return res
def highlight_lines(field,lines):
for h in lines:
for w in range(field.w):
if field.get_wh(w,h) is not None:
field.set_wh(w,h,14)
def move_down_rest(field,fulllines):
# make mapping-list to map new lines from old.
maph = list(range(field.h))
rem = fulllines[:]
rem.sort()
rem.reverse()
for h in rem:
del maph[h]
while len(maph)<field.h:
maph.append(-1)
# Oh Dreck. Wie runterschieben?? Zeilen sind nicht gleichlang...
for h in range(field.h):
from_h = maph[h]
if from_h<0: # clear line
for w in range(field.w):
if field.get_wh(w,h) is not None:
field.set_wh(w,h,0)
elif from_h!=h:
# copy from [from_h]
for w in range(field.w):
if field.get_wh(w,h) is not None:
val = field.get_wh(w,from_h)
if val is None:
val=field.get_wh(w+1,from_h)
if val is None:
val = 0
field.set_wh(w,h,val)
def mix_col_liness(lin1,lin2,fac1,fac2):
if len(lin1)!=len(lin2) or (len(lin1)%3)!=0:
raise ValueError("need two strings of same length, multiple of 3")
if (not isinstance(fac1,int)) or (not isinstance(fac2,int)) or fac1<1 or fac2<1:
raise ValueError("bad factors. need integers, >=1. have "+repr((fac1,fac2)))
sm = fac1+fac2
res = list()
for i in range(len(lin1)//3):
p1=lin1[3*i:3*i+3]
p2=lin2[3*i:3*i+3]
val1, val2, val3 = (p1[0]*fac1+p2[0]*fac2)//sm, (p1[1]*fac1+p2[1]*fac2)//sm, (p1[2]*fac1+p2[2]*fac2)//sm
res.append(LedClientBase.rgbF_2_bytes((val1/100, val2/100, val3/100)))
return b"".join(res)
def clearboard(field,game):
game.reset()
for h in range(field.h):
for w in range(field.w):
if field.get_wh(w,h) is not None:
field.set_wh(w,h,0)
if __name__=="__main__":
sys.exit(main(sys.argv[1:]))