-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgamescreen.py
More file actions
2741 lines (2532 loc) · 105 KB
/
gamescreen.py
File metadata and controls
2741 lines (2532 loc) · 105 KB
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 random
import time
import os
from kivy.app import App
from kivy.clock import Clock
from kivy.properties import OptionProperty, ObjectProperty, StringProperty, ListProperty, BooleanProperty, NumericProperty, DictProperty
from kivy.animation import Animation
from kivy.uix.relativelayout import RelativeLayout
from kivy.graphics import Rectangle
from kivy.graphics import Color
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from generalelements import TetraScreen, ReactionButton, ChatLabel, Countdown, generate_2d_array, time_index, generate_seed
from kivy.lang.builder import Builder
Builder.load_string("""
<GameScreen>:
ScreenLayout:
pos: root.pos
size: root.size
size_hint: None, None
orientation: 'vertical'
Header:
NormalButton:
text: ' Back '
on_release: root.back()
WideButton:
text: 'Unpause Game' if root.paused and not root.unpausing else 'Pause Game'
disabled: True if (not root.game_running) else False
on_release: root.pause()
WideButton:
text: 'End Game' if root.game_running else 'New Game'
disabled: True if root.replay or (not root.game_running and root.game_mode == 'C') else False
on_release: root.toggle_game()
InfoLabel:
SettingsButton:
on_release: app.show_settings('game')
BoxLayout:
padding: app.screen_border, 0, app.screen_border, app.screen_border
PlayLayout:
id: playLayout
owner: root
field_height: root.field_height
field_width: root.field_width
GridLayout:
cols: max(1, round((self.width / self.height) * 2.5))
id: reactionArea
spacing: app.button_scale / 4
size_hint: None, None
ReactionButton:
emotion: 'happy'
ReactionButton:
emotion: 'unamused'
ReactionButton:
emotion: 'mad'
ReactionButton:
emotion: 'surprised'
ReactionButton:
emotion: 'evil'
ReactionButton:
emotion: 'sad'
BoxLayout:
canvas.before:
Color:
rgba: app.theme.darkened[0], app.theme.darkened[1], app.theme.darkened[2], (0 if self.orientation == 'vertical' else app.theme.darkened[3])
Rectangle:
size: self.size
pos: self.pos
Color:
rgba: app.theme.indented[0], app.theme.indented[1], app.theme.indented[2], (0 if self.orientation == 'horizontal' else app.theme.indented[3])
BorderImage:
display_border: [app.display_border, app.display_border, app.display_border, app.display_border]
border: 16, 16, 16, 16
size: self.size
pos: self.pos
source: 'data/inverted.png'
id: scoreArea
size_hint: None, None
padding: 0, 0
orientation: 'horizontal'
NormalLabel:
text: 'Score: '+str(root.score)
NormalLabel:
text: 'Remaining:'+str(root.remaining_lines) if root.game_mode == 'B' else 'Lines: '+str(root.completed_lines)
NormalLabel:
text: 'Level: '+str(root.level)+('+'+str(root.level_offset_real) if root.level_offset_real else '')
NormalLabel:
text: 'Time: '+app.format_frames(root.total_ticks)
BoxLayout:
id: extraArea
size_hint: None, None
padding: app.button_scale / 2
Image:
source: 'data/icon.png'
BoxLayout:
id: nameArea
size_hint: None, None
padding: app.button_scale / 2
Image:
source: 'data/appname.png'
StencilBox:
id: playAreaBox
size_hint: None, None
padding: app.display_border / 2, app.display_border / 2
canvas.before:
Color:
rgba: app.theme.indented
BorderImage:
display_border: [app.display_border, app.display_border, app.display_border, app.display_border]
border: 16, 16, 16, 16
size: self.size
pos: self.pos
source: 'data/inverted.png'
RelativeLayout:
PlayArea:
paused: root.paused and not root.unpausing
opacity: 0 if self.paused else 1
id: playArea
size_hint_y: None
pos: overlayArea.pos
height: overlayArea.height
Widget:
canvas.before:
Color:
rgba: 1, 0, 0, .3
Rectangle:
size: self.size
pos: self.pos
size_hint_y: len(root.lines_to_add) / root.field_height
Widget:
canvas:
Color:
rgba: 1, 0, 0, .5
Rectangle:
pos: self.pos[0] + self.width, self.pos[1]
size: 6, self.height * (root.opponent_block_height / root.field_height)
BoxLayout:
orientation: 'vertical'
RelativeLayout:
id: overlayArea
WideButton:
disabled: not root.paused
on_release: root.pause()
opacity: 1 - playArea.pause_opacity
Image:
opacity: 1 - playArea.pause_opacity
source: 'data/paused.png'
FastForwardLabel:
activate: root.playback_speed
TouchControl:
invisible: True
BoxLayout:
size_hint_y: None
disabled: not (root.show_chat and app.connected)
opacity: 0 if self.disabled else 1
height: 0 if self.disabled else (app.button_scale * 5)
orientation: 'vertical'
FloatLayout:
NormalRecycleView:
canvas.before:
Color:
rgba: app.theme.indented
BorderImage:
display_border: [app.display_border, app.display_border, app.display_border, app.display_border]
border: 16, 16, 16, 16
size: self.size
pos: self.pos
source: 'data/inverted.png'
scroll_y: 0
do_scroll_x: False
size_hint: None, None
pos: self.parent.pos
size: self.parent.size
id: chatArea
data: app.multiplayer_text
viewclass: 'ChatLabel'
RecycleBoxLayout:
padding: app.button_scale / 4, app.button_scale / 10
default_size_hint: 1, None
orientation: 'vertical'
size_hint_y: None
height: self.minimum_height
Image:
size_hint: None, None
size: app.button_scale / 2, app.button_scale / 6.666
color: app.theme.button_text if app.multiplayer_typing else (1, 1, 1, 0)
anim_delay: 0.0333
pos: self.parent.pos[0] + self.parent.size[0] - self.size[0], self.parent.pos[1]
source: 'data/elipsis.zip'
BoxLayout:
size_hint_y: None
height: app.button_scale
NormalInputChat:
multiline: False
hint_text: 'Type A Message To Your Opponent'
text: app.multiplayer_text_current
on_text: app.multiplayer_text_current = self.text
NormalButton:
text: 'Send'
on_release: app.multiplayer_send_message()
FloatLayout:
canvas.before:
Color:
rgba: app.theme.indented
BorderImage:
display_border: [app.display_border, app.display_border, app.display_border, app.display_border]
border: 16, 16, 16, 16
size: self.size
pos: self.pos
source: 'data/inverted.png'
id: nextArea
size_hint: None, None
PieceDisplay:
pos: self.parent.pos
size: self.parent.size
cols: 1
padding: self.width / (self.cols + 1)
id: nextPiece
LeftNormalLabel:
padding: 15, 15
valign: 'top'
pos: self.parent.pos
size: self.parent.size
text: 'Next:'
TouchArea:
function: 'down'
show_image: False
pos: self.parent.pos
FloatLayout:
canvas.before:
Color:
rgba: app.theme.indented
BorderImage:
display_border: [app.display_border, app.display_border, app.display_border, app.display_border]
border: 16, 16, 16, 16
size: self.size
pos: self.pos
source: 'data/inverted.png'
id: storedArea
size_hint: None, None
PieceDisplay:
cols: 1
padding: self.width / (self.cols + 1)
pos: self.parent.pos
size: self.parent.size
id: storedPiece
LeftNormalLabel:
pos: self.parent.pos
size: self.parent.size
padding: 15, 15
valign: 'top'
text: 'Stored:'
TouchButton:
opacity: 0
pos: self.parent.pos
on_press: root.store()
TouchDrop:
id: hardDownButton
size_hint: None, None
disabled: False if app.touch_area else True
opacity: 0 if self.disabled else 1
on_press: root.hard_down(safe=True)
TouchButton:
id: rotateLeftButton
disabled: not app.touch_rotate
opacity: 0 if self.disabled else 1
size_hint: None, None
image: 'data/rotatel.png'
on_press: root.rotate_left()
TouchArea:
id: moveLeftButton
disabled: not app.touch_slide
opacity: 0 if self.disabled else 1
size_hint: None, None
function: 'left'
image: 'data/left.png'
TouchArea:
id: moveDownButton
size_hint: None, None
function: 'down'
image: 'data/down.png'
TouchArea:
id: moveRightButton
disabled: not app.touch_slide
opacity: 0 if self.disabled else 1
size_hint: None, None
function: 'right'
image: 'data/right.png'
TouchButton:
id: rotateRightButton
disabled: not app.touch_rotate
opacity: 0 if self.disabled else 1
size_hint: None, None
image: 'data/rotater.png'
on_press: root.rotate_right()
<Piece>:
canvas.before:
PushMatrix
Rotate:
angle: self.rotation
axis: 0,0,1
origin: self.center[0] - self.pos[0], self.center[1] - self.pos[1]
canvas.after:
PopMatrix
pos_hint: {'top': 1 - (self.grid_pos_y / self.field_height), 'x': (self.grid_pos_x) / self.field_width}
<Block>:
canvas.before:
PushMatrix
Rotate:
angle: self.rotation
axis: 0,0,1
origin: self.center
Scale:
x: self.scale
y: self.scale
origin: self.center
canvas:
Color:
rgba: root.color
Rectangle:
source: app.block_file(self.block_type)
pos: self.pos
size: self.size
Color:
rgba: root.color[0], root.color[1], root.color[2], root.color[3] * .333
Rectangle:
size: self.size
pos: self.pos
canvas.after:
PopMatrix
<BGColumn>:
canvas:
Color:
rgba: app.theme.background_column
Rectangle:
source: app.column_image
pos: self.pos
size: self.size
<BG>:
canvas:
Color:
rgba: self.owner.bg_color
Rectangle:
pos: self.pos
size: self.size
<Row>:
pos_hint:{'y': 1 - ((self.grid_pos + 1) * self.size_hint_y)}
<PlayArea>:
<GameOver>:
orientation: 'vertical'
<GameOverInfo>:
text_height: self.height / 18
opacity: 0
orientation: 'vertical'
Widget:
Image:
source: 'data/congratulations.png' if root.win else 'data/game_over.png'
allow_stretch: True
size_hint_y: None
height: root.text_height * 2
NormalLabel:
size_hint_y: None
height: root.text_height
text: 'Score: '+root.score
NormalLabel:
size_hint_y: None
height: root.text_height
text: 'Game Time: '+root.length
NormalLabel:
size_hint_y: None
height: root.text_height
text: root.lines+' Lines Completed'
NormalLabel:
size_hint_y: None
height: root.text_height
text: root.pieces+' Pieces Played'
Widget:
""")
from globals import fps, pieces, default_bg, levels, clear_modes
def draw_block(canvas, pos, size, color, block=''):
"""Draws a block on the given canvas element
Arguments:
canvas: canvas object to draw the block on
pos: x, y tuple for block position
size: width, height tuple for block size
color: r, g, b, a tuple describing the color of the block. Set to transparent black if block is ''
block: string, type of block. If '', will be drawn invisible, if 'shadow' will be drawn as a shadow (simplified). Otherwise, must be a piece type name.
Returns:
Added canvas elements (Color, Rectangle in shadow mode or Color, Rectangle, Color, Rectangle in normal mode.
Last element is a data list containing passed in data: x, y, width, height, color
"""
app = App.get_running_app()
x_pos, y_pos = pos
size_x, size_y = size
if block == 'shadow':
col = Color(*color)
box = Rectangle(pos=(x_pos, y_pos), size=(size_x, size_y))
canvas.add(col)
canvas.add(box)
data = [x_pos, y_pos, size_x, size_y, color[-1]]
return [col, box, data]
else:
if block == '':
color_value = (0, 0, 0, 0)
color2_value = color_value
else:
color_value = color[:3] + [1]
color2_value = color[:3] + [app.piece_color2_alpha]
color = Color(*color_value)
box = Rectangle(pos=(x_pos, y_pos), size=(size_x, size_y), source=app.block_file(block))
color2 = Color(*color2_value)
box2 = Rectangle(pos=(x_pos, y_pos), size=(size_x, size_y))
canvas.add(color)
canvas.add(box)
canvas.add(color2)
canvas.add(box2)
data = [x_pos, y_pos, size_x, size_y, 1, app.piece_color2_alpha]
return [color, box, color2, box2, data]
class GameScreen(TetraScreen):
show_chat = BooleanProperty(False)
block_height = NumericProperty(0) #Variable that indicates the current max height of the blocks in the play field
opponent_block_height = NumericProperty(0) #When in multiplayer mode, this indicates the block height of opponent's field
piece_randomizer = None
piece_seed = 0
game_mode = StringProperty('A') #A = Marathon, B = Sprint, C = Multiplayer
bg_color = ListProperty([0, 0, 0, 1])
fall_speed = 0.2
completed_lines = NumericProperty(0)
level = NumericProperty(0)
game_running = BooleanProperty(False)
screen_manager = ObjectProperty()
field_width = NumericProperty(10)
field_height = NumericProperty(18)
current_piece = ObjectProperty(allownone=True)
storing_piece = ObjectProperty(allownone=True)
next_piece = None
stored_piece = None
key_press = StringProperty()
board_overflow = []
board_elements = []
board = ObjectProperty()
play_area = ObjectProperty()
board_color = (.5, 0, 0, 1)
score = NumericProperty(0)
update_function = ObjectProperty(allownone=True)
completed_rows = ListProperty()
clearing_rows = BooleanProperty(False)
adding_rows = BooleanProperty(False)
lines_to_add = ListProperty()
added_rows = ListProperty()
adding_animation = ObjectProperty(allownone=True)
board_widgets = ListProperty()
level_ticks = 1
ticks = 0
clear_mode = ''
clearing_animation = None
can_store = BooleanProperty(True)
paused = BooleanProperty(False)
unpausing = BooleanProperty(False)
unpausing_widget = ObjectProperty(allownone=True)
chances = []
level_offset = NumericProperty(0)
level_offset_real = NumericProperty(0)
garbage_lines = ListProperty()
remaining_lines = NumericProperty(0)
falling_piece = BooleanProperty(False)
clear_line_animations = []
periodic_add_line_counter = NumericProperty(0)
periodic_add_line_ticks = NumericProperty(0)
periodic_add_lines = NumericProperty(0) #Add lines occasionally
start_speed = NumericProperty(0) #Starting level
start_filled = NumericProperty(0) #Number of lines to fill with garbage
start_length = NumericProperty(1) #Number of lines to clear to complete game
replay = BooleanProperty(False)
replay_path = StringProperty()
replay_length = NumericProperty()
move_delay_fast = 10
move_delay_slow = 24
max_move = 4
max_move_down = 3
max_rotate = 12
move_speedup_fast = 5
move_speedup_slow = 2
total_ticks = NumericProperty(0)
piece_ticks = 0
history = []
history_playback = []
total_pieces = 0
m_rotate_l = 0
m_rotate_l_delay = 25
m_rotate_r = 0
m_rotate_r_delay = 25
m_down = 0
m_down_delay = 14
m_left = 0
m_left_delay = 14
m_right = 0
m_right_delay = 14
m_drop = 0
m_store = 0
m_pause = 0
playback_speed = NumericProperty(1)
def back(self):
app = App.get_running_app()
if self.replay:
app.replay('right')
elif self.game_mode == 'A':
app.marathon('right')
elif self.game_mode == 'B':
app.sprint('right')
else:
app.multiplayer_send('leave game', [])
app.multiplayer('right')
def move_x_percent(self, percent):
if self.current_piece:
space_l, piece_width = self.get_piece_spacing(self.current_piece.piece_grid)
width = self.field_width - piece_width
target_grid = int(round(width * percent)) - space_l
if self.current_piece.grid_h > target_grid:
if self.m_left == 0:
self.move_left()
self.m_left += 1
self.m_right = 0
elif self.current_piece.grid_h < target_grid:
if self.m_right == 0:
self.move_right()
self.m_right += 1
self.m_left = 0
else:
self.m_left = 0
self.m_right = 0
def move_x_percent_off(self):
self.m_left = 0
self.m_right = 0
def move_down_touch(self):
self.m_down += 1
def move_down_touch_off(self):
self.m_down = 0
def move_left_touch(self):
self.m_left += 1
def move_left_touch_off(self):
self.m_left = 0
def move_right_touch(self):
self.m_right += 1
def move_right_touch_off(self):
self.m_right = 0
def add_lines(self):
if self.lines_to_add:
self.added_rows = self.lines_to_add
self.lines_to_add = []
def add_line(self):
#add a single line to the bottom of the field
self.adding_rows = True
add_length = 0.025
line_to_add = self.added_rows.pop(0)
space, block = line_to_add
board_data = self.board_elements
new_line = self.spacer_line(space, block)
self.board_elements = board_data[1:] + [new_line]
for index, widget in enumerate(self.board_widgets):
animation = Animation(grid_pos=widget.grid_pos-1, duration=add_length, t='out_back')
self.clear_line_animations.append([widget, animation])
animation.start(widget)
self.adding_animation = Clock.schedule_once(self.add_line_finished, add_length)
def add_line_finished(self, *_):
self.stop_line_animations()
self.update_board()
self.adding_rows = False
def get_piece_spacing(self, grid):
#iterate through a list and determine if each column contains any True
column_totals = []
width = len(grid[0])
height = len(grid)
for index_x in range(width):
trues = 0
for index_y in range(height):
if grid[index_y][index_x] is True:
trues += 1
if trues > 0:
column_totals.append(True)
else:
column_totals.append(False)
space_l = 0
for column in column_totals:
if column is True:
break
space_l += 1
space_r = 0
for column in reversed(column_totals):
if column is True:
break
space_r += 1
piece_width = width - space_l - space_r
return space_l, piece_width
def add_history(self, action):
"""
Keep a record of actions for the game, all actions are stored as: [game_tick, action]
"""
#if action in ['F', 'D']:
self.history.append([self.piece_ticks, action])
def save_history(self, time_data):
app = App.get_running_app()
if self.game_mode == 'C':
return
current_time = time.strftime("%Y-%m-%d %H-%M-%S", time_data)
current_time_internal = time.strftime("%Y,%m,%d,%H,%M", time_data)
file_basename = 'Game '+self.game_mode+' From '+current_time
filename = file_basename+'.txt'
histories_folder = os.path.join(app.savefolder, 'histories')
filepath = os.path.join(histories_folder, filename)
if os.path.exists(filepath):
os.remove(filepath)
file = open(filepath, 'w')
file.write(current_time_internal+'\n')
file.write(str(self.total_ticks)+'\n')
file.write(str(self.completed_lines)+'\n')
file.write(str(self.total_pieces)+'\n')
file.write(str(self.score)+'\n')
file.write(self.game_mode+'\n')
file.write(str(self.level_offset)+'\n')
file.write(str(self.start_length)+'\n')
file.write(self.get_garbage_data_string()+'\n')
for line in self.history:
file.write(str(line[0])+','+line[1]+'\n')
file.close()
def load_history(self, filepath):
try:
self.history_playback = []
file = open(filepath, 'r')
for index, line in enumerate(file):
if index == 0:
current_time = line.strip()
elif index == 1:
self.replay_length = int(line.strip())
elif index == 2:
completed_lines = int(line.strip())
elif index == 3:
total_pieces = int(line.strip())
elif index == 4:
score = int(line.strip())
elif index == 5:
self.game_mode = line.strip()
elif index == 6:
self.start_speed = int(line.strip())
elif index == 7:
self.start_length = int(line.strip())
elif index == 8:
garbage_data = line.strip().split(',')
garbage_lines = []
for garbage_line in garbage_data:
if ' ' in garbage_line:
line_data = [int(n) for n in garbage_line.split(' ')]
garbage_lines.append(line_data)
self.garbage_lines = garbage_lines
else:
history_tick, history_action = line.strip().split(',')
self.history_playback.append([int(history_tick), history_action])
except:
self.history_playback = []
if self.history_playback:
return True
else:
return False
def history_action(self, action):
"""
Play back a history action
Possible actions:
I, J, L, O, S, Z, T - Added corrosponding piece
7 - Rotate piece left
9 - Rotate piece right
4 - Move piece left
6 - Move piece right
5 - Move piece down
2 - Hard drop piece
0 - Store/recall piece
F - Piece fell on board
D - System moves piece down
A## - Add line with spacer at number
W - Game won
"""
moved = False
if action == 'D':
if self.current_piece:
self.current_piece.move_down()
moved = True
elif action == 'F':
if self.current_piece:
x = self.current_piece.grid_h
y = self.current_piece.grid_v
grid = self.current_piece.piece_grid
color = self.current_piece.color
name = self.current_piece.name
self.fall_piece(x, y, grid, color, name)
moved = True
elif action == '7':
if self.current_piece:
moved = self.current_piece.rotate_piece('l')
elif action == '9':
if self.current_piece:
moved = self.current_piece.rotate_piece('r')
elif action == '4':
if self.current_piece:
moved = self.current_piece.move_left()
elif action == '6':
if self.current_piece:
moved = self.current_piece.move_right()
elif action == '5':
if self.current_piece:
moved = self.current_piece.move_down(quick=True)
elif action == '2':
if self.current_piece:
self.current_piece.hard_down()
moved = True
elif action == '0':
moved = self.store()
elif action == 'W':
self.game_win()
moved = True
elif action in ['I', 'J', 'L', 'O', 'S', 'Z', 'T']:
self.new_piece(new_ident=action)
moved = True
elif action.startswith('A'):
space = int(action[1:])
block = random.randint(0, len(pieces)-1)
self.lines_to_add.append([space, block])
moved = True
else:
moved = True
if not moved:
self.failed_play_recorded()
def failed_play_recorded(self):
app = App.get_running_app()
self.end_game()
app.message("Unable to\nplay replay")
app.replay()
def enable_show_chat(self):
app = App.get_running_app()
if app.connected and self.game_mode == 'C':
self.show_chat = True
def pause(self, force=False, silent=False):
app = App.get_running_app()
if not self.game_running:
return
if self.unpausing:
app.pause_music()
if not silent:
app.multiplayer_send('pause start', [])
self.unpause_countdown_cancel()
self.enable_show_chat()
return
if self.paused and not force:
self.show_chat = False
Clock.schedule_once(self.refresh_piece_size, 1)
#app.resume_music()
if self.replay:
self.paused = False
self.update_function = Clock.schedule_interval(self.game_loop_playback, 1.0/fps)
else:
if not silent:
app.multiplayer_send('pause end', [])
self.unpause_countdown_start()
else:
self.enable_show_chat()
app.pause_music()
if not silent:
app.multiplayer_send('pause start', [])
if not self.paused:
app.play_sound('pause')
self.cancel_clear_line()
while self.completed_rows:
self.clear_line(instant=True)
self.paused = True
if self.update_function:
self.update_function.cancel()
def unpause_countdown_start(self):
play_area = self.ids['playArea']
self.unpausing_widget = Countdown()
self.unpausing_widget.bind(on_count_finished=self.unpause_countdown_finish)
play_area.add_widget(self.unpausing_widget)
self.unpausing = True
self.unpausing_widget.start()
def unpause_countdown_cancel(self):
if self.unpausing_widget is not None:
self.unpausing_widget.cancel()
play_area = self.ids['playArea']
play_area.remove_widget(self.unpausing_widget)
self.unpausing = False
self.unpausing_widget = None
def refresh_piece_size(self, *_):
if self.current_piece:
self.current_piece.on_size()
if self.current_piece.piece_shadow:
self.current_piece.piece_shadow.on_size()
def unpause_countdown_finish(self, *_):
self.unpause_countdown_cancel()
self.paused = False
self.play_music()
self.update_function = Clock.schedule_interval(self.game_loop, 1.0/fps)
def get_garbage_data_string(self):
garbage_data = []
for data in self.garbage_lines:
garbage_data.append(' '.join([str(item) for item in data]))
garbage_string = ','.join(garbage_data)
return garbage_string
def save_pause(self):
app = App.get_running_app()
if self.game_mode == 'C':
app.pause_data = ''
return
if not self.history:
return
if self.replay:
return
#save the current game state
total_ticks = self.total_ticks
total_pieces = self.total_pieces
if self.current_piece:
current_piece_type = self.current_piece.name
current_piece_x = self.current_piece.grid_h
current_piece_y = self.current_piece.grid_v
current_piece_rotate = self.current_piece.rotate_index
else:
current_piece_type = ''
current_piece_x = 0
current_piece_y = 0
current_piece_rotate = 0
if self.stored_piece:
stored_piece_type = self.stored_piece['name']
else:
stored_piece_type = ''
next_piece = self.next_piece['name']
history = self.history
chances = self.chances
score = self.score
completed_lines = self.completed_lines
piece_ticks = self.piece_ticks
board_elements = self.board_elements
board_format = []
for row in board_elements:
for column in row:
if column:
#point = str(column[0])+' '+str(column[1])+' '+str(column[2])+' '+column[3]
point = column[3]
else:
point = '0'
board_format.append(point)
add_lines_data = []
for line in self.lines_to_add:
add_lines_data.append(str(line[0]))
add_lines = ','.join(add_lines_data)
board_string = ','.join(board_format)
garbage_string = self.get_garbage_data_string()
pause_data = [total_ticks, total_pieces, current_piece_type, current_piece_x, current_piece_y, current_piece_rotate, stored_piece_type, next_piece, score, completed_lines, piece_ticks, board_string]
pause_data = pause_data + [self.game_mode, self.level_offset, self.start_length, self.periodic_add_lines, self.periodic_add_line_counter, add_lines, garbage_string]
pause_data = pause_data + chances
history_data = []
for line in history:
history_data.append(str(line[0])+','+line[1])
pause_data = pause_data + history_data
app.pause_data = ';'.join(str(x) for x in pause_data)
def resume_pause(self):
app = App.get_running_app()
pause_string = app.pause_data
if pause_string:
#parse pause string
try:
add_lines = []
history_data = pause_string.split(';')
total_ticks = int(history_data[0])
total_pieces = int(history_data[1])
current_piece_type = history_data[2]
current_piece_x = int(history_data[3])
current_piece_y = int(history_data[4])
current_piece_rotate = int(history_data[5])
stored_piece_type = history_data[6]
next_piece = history_data[7]
score = int(history_data[8])
completed_lines = int(history_data[9])
piece_ticks = int(history_data[10])
board_string = history_data[11]
board_format = board_string.split(',')
game_mode = history_data[12]
level_offset = int(history_data[13])
start_length = int(history_data[14])
periodic_add_lines = int(history_data[15])
periodic_add_line_counter = int(history_data[16])
add_line_data = history_data[17].split(',')
for add_line in add_line_data:
if add_line:
block = random.randint(0, len(pieces)-1)
add_lines.append([int(add_line), block])
garbage_data = history_data[18].split(',')
garbage_lines = []
for line in garbage_data:
if ' ' in line:
line_data = [int(n) for n in line.split(' ')]
garbage_lines.append(line_data)
chances = [int(history_data[19]), int(history_data[20]), int(history_data[21]), int(history_data[22]), int(history_data[23]), int(history_data[24]), int(history_data[25])]
history_list = history_data[26:]
history = []
for line in history_list:
history_ticks, history_action = line.split(',')
history_element = [int(history_ticks), history_action]
history.append(history_element)
except:
return False
#prepare game to resume
self.end_game()
self.setup_randomizer()
self.setup_board()
self.game_mode = game_mode
self.periodic_add_lines = periodic_add_lines
self.periodic_add_line_counter = periodic_add_line_counter
self.level_offset = level_offset
self.start_length = start_length
self.garbage_lines = garbage_lines
self.total_ticks = total_ticks
self.total_pieces = total_pieces
self.piece_ticks = piece_ticks
self.chances = chances
self.history = history
self.score = score
self.lines_to_add = add_lines
self.completed_lines = completed_lines
self.level = completed_lines // 10
index_data = 0
for row in self.board_elements:
for index, column in enumerate(row):
if board_format[index_data] == '0':
row[index] = None
else:
color_name = board_format[index_data]
try:
color = getattr(app.theme, color_name)
except:
color_name = 'T'
color = app.theme.T
color = color[:3] + [color_name]