-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtetris.py
1500 lines (1216 loc) · 48.3 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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os, pygame, sys, math, random
from pygame.locals import *
from events import *
from utilities import Utilities, Callable
if not pygame.font: print 'Warning, fonts disabled'
if not pygame.mixer: print 'Warning, sound disabled'
TITLE_CAPTION = "Super Tetra Master"
SCREEN_RESOLUTION = (640,480)
FRAMES_PER_SECOND = 60
HOLD_ORIGIN = (240, 32)
NEXT_ORIGINS = ((292, 20), (362, 40), (400, 40))
WELL_ORIGIN = (240,48) #pixels
TILE_SIZE = (16,16) #pixels
SMALL_TILE_SIZE = (8, 8)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
ORANGE = (255, 153, 51)
GREY = (100, 100, 100)
DIRECTION_UP = 0
DIRECTION_DOWN = 1
DIRECTION_LEFT = 2
DIRECTION_RIGHT = 3
DIRECTION_CW = 4
DIRECTION_CCW = 5
class EventManager:
"""class that coordinates communication between the model and the view and controller"""
def __init__(self):
from weakref import WeakKeyDictionary
self.listeners = WeakKeyDictionary()
self.eventQueue = []
def RegisterListener(self, listener):
self.listeners[listener] = 1
def UnregisterListener(self, listener):
if listener in self.listeners:
del self.listeners[listener]
def Post(self, event):
"""post a new event, broadcast to all listeners"""
self.eventQueue.append(event)
if isinstance(event, TickEvent):
self.ConsumeEventQueue()
def ConsumeEventQueue(self):
i = 0;
while i < len(self.eventQueue):
event = self.eventQueue[i]
for listener in self.listeners:
listener.Notify(event)
i += 1
# all events handled, clear queue
self.eventQueue = []
class KeyboardController:
def __init__(self, eventManager):
self.eventManager = eventManager
self.eventManager.RegisterListener(self)
#pygame.event.set_allowed([KEYDOWN])
pygame.key.set_repeat(250, 20)
def Notify(self, event):
if isinstance(event, TickEvent):
#Handle Input
for event in pygame.event.get():
if event.type == QUIT:
self.eventManager.Post(QuitEvent())
elif event.type == KEYDOWN and event.key == K_ESCAPE:
self.eventManager.Post(QuitEvent())
elif event.type == KEYDOWN and event.key == K_1:
self.eventManager.Post(TetradRotateRequest(DIRECTION_CCW))
elif event.type == KEYDOWN and event.key == K_2:
self.eventManager.Post(TetradRotateRequest(DIRECTION_CW))
elif event.type == KEYDOWN and event.key == K_BACKQUOTE:
self.eventManager.Post(TetradSwapRequest())
elif event.type == KEYDOWN and event.key == K_DOWN:
self.eventManager.Post(TetradMoveRequest(DIRECTION_DOWN))
elif event.type == KEYDOWN and event.key == K_UP:
self.eventManager.Post(SonicDropRequest())
elif event.type == KEYDOWN and event.key == K_LEFT:
self.eventManager.Post(TetradMoveRequest(DIRECTION_LEFT))
elif event.type == KEYDOWN and event.key == K_RIGHT:
self.eventManager.Post(TetradMoveRequest(DIRECTION_RIGHT))
elif event.type == KEYDOWN and event.key == K_RETURN:
print 'start game'
self.eventManager.Post(GameStartRequest())
class CPUSpinnerController:
def __init__(self, eventManager):
self.eventManager = eventManager
self.eventManager.RegisterListener(self)
self.keepGoing = True
self.clock = pygame.time.Clock()
self.running = True
def Run(self):
while self.keepGoing:
self.clock.tick(FRAMES_PER_SECOND)
if self.running:
self.eventManager.Post(TickEvent())
def Notify(self, event):
if isinstance(event, QuitEvent):
self.keepGoing = False
class BlockSprite(pygame.sprite.Sprite):
"""..."""
def __init__(self, block, colour, group=None):
pygame.sprite.Sprite.__init__(self, group)
surf = pygame.Surface((15,15))
surf.fill(colour)
self.image = surf
self.rect = surf.get_rect()
self.block = block
self.moveTo = None
self.shrink = False
self.grow = False
def MoveTo(self, moveTo):
self.moveTo = moveTo
def Shrink(self):
self.shrink = True
def Grow(self):
self.grow = True
def update(self):
if self.moveTo:
self.rect.center = self.moveTo
self.moveTo = None
if self.shrink == True:
surf = pygame.transform.scale(self.image, (7,7))
self.image = surf
self.shrink = False
if self.grow == True:
surf = pygame.transform.scale(self.image, (15,15))
self.image = surf
self.grow = False
class PygameView:
def __init__(self, eventManager):
self.eventManager = eventManager
self.eventManager.RegisterListener(self)
self.window = pygame.display.set_mode(SCREEN_RESOLUTION)
pygame.display.set_caption(TITLE_CAPTION)
#self.background = pygame.Surface(self.window.get_size())
#self.background.fill(BLACK)
self.background, self.backgroundRect = Utilities.LoadImage("frame.png")
#font = pygame.font.Font(None, 30) #default font, 30px high
#textImg = font.render("Press Enter", 1, WHITE)
#self.background.blit( textImg, (0,0) )
self.window.blit(self.background, self.backgroundRect)
pygame.display.flip()
self.backSprites = pygame.sprite.RenderUpdates()
self.frontSprites = pygame.sprite.RenderUpdates()
def AddTetrads(self, tetrads):
origin = (-1, -1)
colour = None
blockSprite = None
#add the next tetrads along the preview
for tetrad in tetrads:
colour = tetrad.GetColour()
origin = NEXT_ORIGINS[tetrads.index(tetrad)]
for block in tetrad.blocks:
blockSprite = BlockSprite(block, colour, self.frontSprites)
row, column = tetrad.GetPreviewBlockCoordinates(tetrad.blocks.index(block))
if tetrads.index(tetrad) == 0:
moveRect = pygame.Rect((origin[0] + column * TILE_SIZE[0], origin[1] + row * TILE_SIZE[1]), TILE_SIZE)
else:
moveRect = pygame.Rect((HOLD_ORIGIN[0] + column * SMALL_TILE_SIZE[0], HOLD_ORIGIN[1] + row * SMALL_TILE_SIZE[1]), SMALL_TILE_SIZE)
blockSprite.Shrink()
blockSprite.MoveTo(moveRect.center)
def AddTetrad(self, currentTetrad, nextTetrads):
tetrad = None
origin = (-1, -1)
colour = None
blockSprite = None
#move currentTetrad to initial coordinates
for block in currentTetrad.blocks:
self.MoveBlock(block)
#move the next tetrads along the preview regions
for tetrad in nextTetrads:
origin = NEXT_ORIGINS[nextTetrads.index(tetrad)]
if nextTetrads.index(tetrad) == 0:
for block in tetrad.blocks:
blockSprite = self.GetBlockSprite(block)
row, column = tetrad.GetPreviewBlockCoordinates(tetrad.blocks.index(block))
moveRect = pygame.Rect((origin[0] + column * TILE_SIZE[0], origin[1] + row * TILE_SIZE[1]), TILE_SIZE)
blockSprite.MoveTo(moveRect.center)
blockSprite.Grow()
elif nextTetrads.index(tetrad) < len(nextTetrads) - 1:
for block in tetrad.blocks:
blockSprite = self.GetBlockSprite(block)
row, column = tetrad.GetPreviewBlockCoordinates(tetrad.blocks.index(block))
moveRect = pygame.Rect((origin[0] + column * SMALL_TILE_SIZE[0], origin[1] + row * SMALL_TILE_SIZE[1]), SMALL_TILE_SIZE)
blockSprite.MoveTo(moveRect.center)
else:
for block in tetrad.blocks:
colour = tetrad.GetColour()
blockSprite = BlockSprite(block, colour, self.frontSprites)
row, column = tetrad.GetPreviewBlockCoordinates(tetrad.blocks.index(block))
moveRect = pygame.Rect((origin[0] + column * SMALL_TILE_SIZE[0], origin[1] + row * SMALL_TILE_SIZE[1]), SMALL_TILE_SIZE)
blockSprite.MoveTo(moveRect.center)
blockSprite.Shrink()
def MoveTetrad(self, tetrad):
for block in tetrad.blocks:
self.MoveBlock(block)
def MoveBlock(self, block):
blockSprite = self.GetBlockSprite(block)
square = block.GetSquare()
if square != None:
row, column = square.GetCoordinates()
moveRect = pygame.Rect((WELL_ORIGIN[0] + column * TILE_SIZE[0], WELL_ORIGIN[1] + row * TILE_SIZE[1]), TILE_SIZE)
blockSprite.MoveTo(moveRect.center)
def GrowTetrad(self, tetrad):
for block in tetrad.blocks:
blockSprite = self.GetBlockSprite(block)
blockSprite.Grow()
def HoldTetrad(self, tetrad):
for block in tetrad.blocks:
blockSprite = self.GetBlockSprite(block)
row, column = tetrad.GetPreviewBlockCoordinates(tetrad.blocks.index(block))
moveRect = pygame.Rect((HOLD_ORIGIN[0] + column * SMALL_TILE_SIZE[0], HOLD_ORIGIN[1] + row * SMALL_TILE_SIZE[1]), SMALL_TILE_SIZE)
blockSprite.MoveTo(moveRect.center)
blockSprite.Shrink()
def AddGhost(self, tetrad):
colour = tetrad.GetColour()
for block in tetrad.blocks:
blockSprite = BlockSprite(block, colour, self.backSprites)
#row, column = block.GetCoordinates()
#moveRect = pygame.Rect((WELL_ORIGIN[0] + column * TILE_SIZE[0], WELL_ORIGIN[1] + row * TILE_SIZE[1]), TILE_SIZE)
#blockSprite.MoveTo(moveRect.center)
def UpdateGhost(self, tetrad):
for block in tetrad.blocks:
blockSprite = self.GetBlockSprite(block)
row, column = block.GetCoordinates()
moveRect = pygame.Rect((WELL_ORIGIN[0] + column * TILE_SIZE[0], WELL_ORIGIN[1] + row * TILE_SIZE[1]), TILE_SIZE)
blockSprite.MoveTo(moveRect.center)
def GetBlockSprite(self, block):
for s in self.frontSprites:
if hasattr(s, "block") and s.block == block:
return s
for s in self.backSprites:
if hasattr(s, "block") and s.block == block:
return s
def Notify(self, event):
if isinstance(event, TickEvent):
#Draw everything
self.backSprites.clear(self.window, self.background)
self.frontSprites.clear(self.window, self.background)
self.backSprites.update()
self.frontSprites.update()
dirtyRects1 = self.backSprites.draw(self.window)
dirtyRects2 = self.frontSprites.draw(self.window)
dirtyRects = dirtyRects1 + dirtyRects2
pygame.display.update( dirtyRects )
elif isinstance(event, TetradsCreatedEvent):
self.AddTetrads(event.tetrads)
elif isinstance(event, TetradAddedEvent):
self.AddTetrad(event.currentTetrad, event.nextTetrads)
elif isinstance(event, TetradMovedEvent):
self.MoveTetrad(event.tetrad)
elif isinstance(event, SonicDropEvent):
self.MoveTetrad(event.tetrad)
elif isinstance(event, TetradRotatedEvent):
self.MoveTetrad(event.tetrad)
elif isinstance(event, TetradDroppedEvent):
self.MoveTetrad(event.tetrad)
elif isinstance(event, GhostAddedEvent):
self.AddGhost(event.tetrad)
elif isinstance(event, GhostUpdatedEvent):
self.UpdateGhost(event.tetrad)
elif isinstance(event, TetradHeldEvent):
self.HoldTetrad(event.tetrad)
elif isinstance(event, TetradSwappedEvent):
self.GrowTetrad(event.currentTetrad)
self.MoveTetrad(event.currentTetrad)
self.HoldTetrad(event.holdTetrad)
elif isinstance(event, StackUpdateEvent):
for block in event.clearedBlocks:
blockSprite = self.GetBlockSprite(block)
self.frontSprites.remove(blockSprite)
for block in event.movedBlocks:
self.MoveBlock(block)
class Game:
"""..."""
STATE_PREPARING = 0
STATE_RUNNING = 1
STATE_PAUSED = 2
def __init__(self, eventManager):
self.eventManager = eventManager
self.eventManager.RegisterListener(self)
self.state = Game.STATE_PREPARING
#create the players (one player for now)
self.players = [Player(eventManager)]
def Start(self):
for player in self.players:
player.Start()
self.state = Game.STATE_RUNNING
print "game started"
self.eventManager.Post(GameStartedEvent(self))
def Notify(self, event):
if isinstance(event, GameStartRequest):
if self.state == Game.STATE_PREPARING:
self.Start()
class Player:
NO_NEXT_TETRADS = 3
"""Model of the player that has a current and next tetrad"""
def __init__(self, eventManager):
self.eventManager = eventManager
self.eventManager.RegisterListener(self)
#player needs a well to put the tetrads on
self.well = Well(eventManager)
#player's tetrads
self.nextTetrads = range(Player.NO_NEXT_TETRADS)
self.holdTetrad = None
def Start(self):
#create starting tetrads
for i in range(Player.NO_NEXT_TETRADS):
self.nextTetrads[i] = Tetrad.GetRandomTetrad(self.eventManager)
self.eventManager.Post(TetradsCreatedEvent(self.nextTetrads))
#build well
self.well.Build()
def AddTetrad(self):
currentTetrad = self.nextTetrads.pop(0)
self.well.AddTetrad(currentTetrad)
self.nextTetrads.append(Tetrad.GetRandomTetrad(self.eventManager))
self.eventManager.Post(TetradAddedEvent(currentTetrad, self.nextTetrads))
def SwapTetrad(self):
if self.holdTetrad == None:
self.holdTetrad = self.well.GetCurrentTetrad()
self.holdTetrad.ClearBlocksSquares()
self.holdTetrad.ResetRotationState()
self.holdTetrad.SetState(Tetrad.STATE_INACTIVE)
self.AddTetrad()
self.eventManager.Post(TetradHeldEvent(self.holdTetrad))
else:
currentTetrad = self.holdTetrad
self.holdTetrad = self.well.GetCurrentTetrad()
self.holdTetrad.ClearBlocksSquares()
self.holdTetrad.ResetRotationState()
self.holdTetrad.SetState(Tetrad.STATE_INACTIVE)
self.well.AddTetrad(currentTetrad)
self.eventManager.Post(TetradSwappedEvent(currentTetrad, self.holdTetrad))
def Notify(self, event):
if isinstance(event, GameStartedEvent):
self.AddTetrad()
elif isinstance(event, TetradLockedEvent):
self.AddTetrad()
elif isinstance(event, TetradSwapRequest):
if self.well.GetCurrentTetrad().GetState() != Tetrad.STATE_LOCKED:
self.SwapTetrad()
class Well:
"""Model for the well in which tetrads fall into place."""
WELL_ROWS = 22 # two rows at top are padding for rotations
WELL_COLUMNS = 10
STATE_PREPARING = 0
STATE_BUILT = 1
LEVELS_FOR_LINES = (1, 2, 4, 6)
def __init__(self, eventManager):
self.eventManager = eventManager
self.eventManager.RegisterListener(self)
self.state = Well.STATE_PREPARING
self.squares = range(Well.WELL_ROWS * Well.WELL_COLUMNS)
self.stackedBlocks = dict()
self.currentTetrad = None
self.ghostTetrad = None
self.dropTimer = 20
self.lockTimer = 10
self.lines = 0
self.gravity = 0
def Build(self):
#create all the squares, give them row/column coordinates
for row in range(Well.WELL_ROWS):
for column in range(Well.WELL_COLUMNS):
self.squares[row*Well.WELL_COLUMNS + column] = Square(self.eventManager, row, column)
#create a dictionary that keeps rows of dropped blocks for easy line detection
for row in range(Well.WELL_ROWS):
self.stackedBlocks[row] = list()
self.ghostTetrad = GhostTetrad(self.eventManager)
self.eventManager.Post(GhostAddedEvent(self.ghostTetrad))
self.state = Well.STATE_BUILT
self.eventManager.Post(WellBuiltEvent(self))
def GetCurrentTetrad(self):
return self.currentTetrad
def AddTetrad(self, currentTetrad):
self.currentTetrad = currentTetrad
square = None
row, column = (-1, -1)
#give current tetrad blocks their initial squares
for i in range(4):
row, column = self.currentTetrad.GetInitialBlockCoordinates(i)
square = self.GetSquare((row, column))
self.currentTetrad.SetBlockSquare(i, square)
currentTetrad.SetState(Tetrad.STATE_ACTIVE)
self.UpdateGhostTetrad()
def UpdateGhostTetrad(self):
rowsDown = 1
squares = range(4)
canDrop = True
# initially ghost is in the same location has current
for i in range(4):
self.ghostTetrad.SetBlockSquare(i, self.currentTetrad.GetBlockSquare(i))
while canDrop:
for block in self.currentTetrad.blocks:
row, column = block.GetCoordinates()
row += rowsDown
if row >= Well.WELL_ROWS:
canDrop = False
break
elif self.GetSquare((row, column)).IsFilled():
canDrop = False
break
else:
squares[self.currentTetrad.blocks.index(block)] = self.GetSquare((row, column))
if canDrop == True:
for i in range(4):
self.ghostTetrad.SetBlockSquare(i, squares[i])
rowsDown += 1
self.eventManager.Post(GhostUpdatedEvent(self.ghostTetrad))
def SonicDropCurrentTetrad(self):
for i in range(4):
self.currentTetrad.SetBlockSquare(i, self.ghostTetrad.GetBlockSquare(i))
self.eventManager.Post(SonicDropEvent(self.currentTetrad))
def DropCurrentTetrad(self):
nextSquares = range(4)
row, column = (-1, -1)
canDrop = True
#check to see if each block in the tetrad can move down
for i in range(4):
row, column = self.currentTetrad.GetBlockCoordinates(i)
row += 1
if row >= Well.WELL_ROWS:
canDrop = False
break
elif self.GetSquare((row, column)).IsFilled():
canDrop = False
break
else:
nextSquares[i] = self.GetSquare((row, column))
# only move the tetrad if all the target squares are valid
if canDrop == True:
for i in range(4):
self.currentTetrad.SetBlockSquare(i, nextSquares[i])
self.eventManager.Post(TetradDroppedEvent(self.currentTetrad))
else:
self.currentTetrad.SetState(Tetrad.STATE_DROPPED)
print "can't drop tetrad"
return canDrop
def MoveCurrentTetrad(self, direction):
nextSquares = range(4)
canMove = True
row, column = (-1, -1)
# make sure the squares the tetrad is moving to are valid and not filled
for i in range(4):
row, column = self.currentTetrad.GetBlockCoordinates(i)
if direction == DIRECTION_LEFT:
column -= 1
elif direction == DIRECTION_RIGHT:
column += 1
elif direction == DIRECTION_DOWN:
row += 1
if row >= Well.WELL_ROWS or column < 0 or column >= Well.WELL_COLUMNS:
canMove = False
break
elif self.GetSquare((row, column)).IsFilled():
canMove = False
break
else:
nextSquares[i] = self.GetSquare((row, column))
# only move the tetrad if all the target squares are valid
if canMove == True:
for i in range(4):
self.currentTetrad.SetBlockSquare(i, nextSquares[i])
self.currentTetrad.SetState(Tetrad.STATE_ACTIVE)
self.eventManager.Post(TetradMovedEvent(self.currentTetrad))
if direction != DIRECTION_DOWN:
self.UpdateGhostTetrad()
else:
print "can't move tetrad"
return canMove
def RotateCurrentTetrad(self, direction):
nextSquares = range(4)
canRotate = True
row, column = (-1, -1)
# make sure the squares the tetrad is rotating to are valid and not filled
for i in range(4):
row, column = self.currentTetrad.GetRotatedBlockCoordinates(i, direction)
if row >= Well.WELL_ROWS or column < 0 or column >= Well.WELL_COLUMNS:
canRotate = False
break
elif self.GetSquare((row, column)).IsFilled():
canRotate = False
break
else:
nextSquares[i] = self.GetSquare((row, column))
# only rotate the tetrad if all the target squares are valid
if canRotate == True:
for i in range(4):
self.currentTetrad.SetBlockSquare(i, nextSquares[i])
self.currentTetrad.ChangeRotationState(direction)
self.currentTetrad.SetState(Tetrad.STATE_ACTIVE)
self.eventManager.Post(TetradRotatedEvent(self.currentTetrad))
self.UpdateGhostTetrad()
else:
print "can't rotate tetrad"
return canRotate
def LockCurrentTetrad(self):
block = None
square = None
row, column = (-1, -1)
clearedRows = set()
clearedBlocks = list()
movedBlocks = list()
noRowsToShift = 0
# add current tetrad to stack, check for cleared rows
for block in self.currentTetrad.blocks:
row, column = block.GetCoordinates()
square = block.GetSquare()
square.SetFilled()
self.stackedBlocks[row].append(block)
if len(self.stackedBlocks[row]) == Well.WELL_COLUMNS:
clearedRows.add(row)
# if any rows were marked for clearance remove them and shift down the other rows
if len(clearedRows) > 0:
for i in range(max(clearedRows), 0, -1):
# remove rows marked for clearance
if clearedRows & set([i]):
clearedBlocks.extend(self.stackedBlocks[i])
for block in self.stackedBlocks[i]:
block.GetSquare().SetFilled(False)
self.stackedBlocks[i] = list()
noRowsToShift += 1
# if rows below have been remove shift down the row
elif noRowsToShift > 0:
for block in self.stackedBlocks[i]:
square = block.GetSquare()
row, column = square.GetCoordinates()
square.SetFilled(False)
square = self.GetSquare((row + noRowsToShift, column))
square.SetFilled()
block.SetSquare(square)
movedBlocks.extend(self.stackedBlocks[i])
self.stackedBlocks[i + noRowsToShift] = self.stackedBlocks[i]
self.stackedBlocks[i] = list()
self.eventManager.Post(StackUpdateEvent(clearedBlocks, movedBlocks))
print "tetrad locked"
self.eventManager.Post(TetradLockedEvent(self.currentTetrad))
return True
def GetSquare(self, (row, column)):
return self.squares[row*Well.WELL_COLUMNS + column]
def Notify(self, event):
if self.currentTetrad != None:
if isinstance(event, TetradMoveRequest):
if self.currentTetrad.GetState() == Tetrad.STATE_ACTIVE or self.currentTetrad.GetState() == Tetrad.STATE_DROPPED:
if self.MoveCurrentTetrad(event.direction) == True:
self.lockTimer = 10 #successful move resets lock timer
# pressing down again locks piece
if self.currentTetrad.GetState() == Tetrad.STATE_DROPPED and event.direction == DIRECTION_DOWN:
self.lockTimer = 1
if isinstance(event, SonicDropRequest):
if self.currentTetrad.GetState() == Tetrad.STATE_ACTIVE:
self.SonicDropCurrentTetrad()
elif isinstance(event, TetradRotateRequest):
if self.currentTetrad.GetState() == Tetrad.STATE_ACTIVE or self.currentTetrad.GetState() == Tetrad.STATE_DROPPED:
if self.RotateCurrentTetrad(event.direction) == True:
self.lockTimer = 10 #successful rotate resets lock timer
elif isinstance(event, TickEvent):
if self.currentTetrad.GetState() == Tetrad.STATE_ACTIVE:
self.dropTimer -= 1
if self.dropTimer == 0:
self.DropCurrentTetrad()
self.dropTimer = 20
elif self.currentTetrad.GetState() == Tetrad.STATE_DROPPED:
self.lockTimer -= 1
if self.lockTimer == 0:
self.LockCurrentTetrad()
self.lockTimer = 10
class Square:
"""Model for a square of the well that could be filled with a block"""
def __init__(self, eventManager, row, column):
self.eventManager = eventManager
#self.eventManager.RegisterListener(self)
self.row = row
self.column = column
self.filled = False
def GetCoordinates(self):
return (self.row, self.column)
def IsFilled(self):
return self.filled
def SetFilled(self, filled=True):
self.filled = filled
class Block:
"""Model for the individual blocks that make up tetrads and the pile at the bottom."""
def __init__(self, eventManager):
self.eventManager = eventManager
#self.eventManager.RegisterListener
#the current square the block occupies
self.square = None
def GetCoordinates(self):
if self.square == None:
print "block has no coordinates"
return (-1, -1)
return self.square.GetCoordinates()
def SetSquare(self, square):
self.square = square
def GetSquare(self):
return self.square
class Tetrad:
"""Model for the tetrads that fall from the top into the pile at the bottom."""
STATE_INACTIVE = 0
STATE_ACTIVE = 1
STATE_DROPPED = 2
STATE_LOCKED = 3
def __init__(self, eventManager):
self.eventManager = eventManager
#self.eventManager.RegisterListener(self)
# create tetrads blocks
self.blocks = range(4)
for i in range(0, 4):
self.blocks[i] = Block(eventManager)
self.state = self.STATE_INACTIVE
self.rotationState = 0
self.colour = GREY
self.initialBlockCoordinates = [(-1, -1), (-1, -1), (-1, -1), (-1, -1)]
def GetBlock(self, blockIndex):
return self.blocks[blockIndex]
def GetInitialBlockCoordinates(self, blockIndex):
return self.initialBlockCoordinates[blockIndex]
def GetPreviewBlockCoordinates(self, blockIndex):
row, column = self.initialBlockCoordinates[blockIndex]
return (row - 2, column - 3)
def GetColour(self):
return self.colour
def SetState(self, state):
self.state = state
def GetState(self):
return self.state
def ResetRotationState(self):
self.rotationState = 0
def ChangeRotationState(self, direction):
if direction == DIRECTION_CW:
self.rotationState = (self.rotationState + 1) % 4
else:
self.rotationState = (self.rotationState - 1) % 4
def GetRotationState(self):
return self.rotationState
def SetBlockSquare(self, blockIndex, square):
self.blocks[blockIndex].SetSquare(square)
def GetBlockSquare(self, blockIndex):
square = self.blocks[blockIndex].GetSquare()
return square
def ClearBlocksSquares(self):
for block in self.blocks:
block.SetSquare(None)
def GetBlockCoordinates(self, blockIndex):
return self.blocks[blockIndex].GetCoordinates()
def GetRotatedBlockCoordinates(self, blockIndex, direction):
return self.GetBlockCoordinates(blockIndex)
def GetRandomTetrad(eventManager):
randNum = random.randint(1,7)
tetrad = None
if randNum == 1:
tetrad = OTetrad(eventManager)
elif randNum == 2:
tetrad = ITetrad(eventManager)
elif randNum == 3:
tetrad = TTetrad(eventManager)
elif randNum == 4:
tetrad = ZTetrad(eventManager)
elif randNum == 5:
tetrad = STetrad(eventManager)
elif randNum == 6:
tetrad = LTetrad(eventManager)
elif randNum == 7:
tetrad = JTetrad(eventManager)
return tetrad
GetRandomTetrad = Callable(GetRandomTetrad)
class GhostTetrad(Tetrad):
"""the ghost or shadow of the current piece"""
def __init__(self, eventManager):
Tetrad.__init__(self, eventManager)
self.colour = GREY
self.visible = True
def SetVisible(self, visible=True):
self.visible = visible
def IsVisible(self):
return self.visible
class OTetrad(Tetrad):
"""the 'O' shaped tetrad
block indices: |0|1|
|3|2|
rotates about centre
"""
def __init__(self, eventManager):
Tetrad.__init__(self, eventManager)
self.colour = YELLOW
self.initialBlockCoordinates = [(2, 4), (2, 5), (3, 5), (3, 4)]
def GetRotatedBlockCoordinates(self, blockIndex, direction):
row, column = self.GetBlockCoordinates(blockIndex)
if direction == DIRECTION_CW:
if self.rotationState == 0:
if blockIndex == 0:
column += 1
elif blockIndex == 1:
row += 1
elif blockIndex == 2:
column -= 1
elif blockIndex == 3:
row -= 1
elif self.rotationState == 1:
if blockIndex == 0:
row += 1
elif blockIndex == 1:
column -= 1
elif blockIndex == 2:
row -= 1
elif blockIndex == 3:
column += 1
elif self.rotationState == 2:
if blockIndex == 0:
column -= 1
elif blockIndex == 1:
row -= 1
elif blockIndex == 2:
column += 1
elif blockIndex == 3:
row += 1
elif self.rotationState == 3:
if blockIndex == 0:
row -= 1
elif blockIndex == 1:
column += 1
elif blockIndex == 2:
row += 1
elif blockIndex == 3:
column -= 1
elif direction == DIRECTION_CCW:
if self.rotationState == 0:
if blockIndex == 0:
row += 1
elif blockIndex == 1:
column -= 1
elif blockIndex == 2:
row -= 1
elif blockIndex == 3:
column += 1
elif self.rotationState == 3:
if blockIndex == 0:
column += 1
elif blockIndex == 1:
row += 1
elif blockIndex == 2:
column -= 1
elif blockIndex == 3:
row -= 1
elif self.rotationState == 2:
if blockIndex == 0:
row -= 1
elif blockIndex == 1:
column += 1