-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1613 lines (1448 loc) · 63.9 KB
/
main.py
File metadata and controls
1613 lines (1448 loc) · 63.9 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
"""
todo:
multiplayer may freeze on unpause
should look into 'un-forwarding' a port when a 'ConflictInMappingEntry' error happens
sometimes detected external ip address might be wrong for some reason?
add option for bluetooth networking if possible - https://gist.github.com/tito/7432757
"""
import time
startup_time = time.time()
from globals import *
from kivy.config import Config
Config.set('input', 'mouse', 'mouse,disable_multitouch')
Config.set('graphics', 'maxfps', str(fps * 2))
FileBrowser = None
from configparser import ConfigParser
import random
from datetime import datetime
import os
app_directory = os.path.dirname(os.path.realpath(__file__))
if platform == 'win':
import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(1)
if platform == 'android':
from plyer import vibrator
else:
vibrator = None
#Initialize audio system
if os.path.exists(os.path.join(app_directory, 'default_audio')):
force_audio = False
else:
force_audio = True
if force_audio:
if platform == 'android':
from audio_android import SoundAndroid as SoundFX
from audio_android import SoundAndroid as SoundMusic
else:
try:
from kivy.core.audio.audio_sdl2 import SoundSDL2 as SoundFX
from kivy.core.audio.audio_sdl2 import MusicSDL2 as SoundMusic
except:
from kivy.core.audio_output.audio_sdl3 import SoundSDL3 as SoundFX
from kivy.core.audio_output.audio_sdl3 import MusicSDL3 as SoundMusic
SoundFX(source='') # this needs to be run before importing "Window", or a freeze can haappen for some reason
else:
try:
from kivy.core.audio import SoundLoader
except:
from kivy.core.audio_output import SoundLoader
SoundLoader.load('')
#Kivy imports
from kivy.logger import Logger
from kivy.core.window import Window
from kivy.base import EventLoop
from kivy.clock import Clock
from kivy.app import App
from kivy.animation import Animation
from kivy.uix.screenmanager import ScreenManager, SlideTransition
from kivy.properties import OptionProperty, ObjectProperty, StringProperty, ListProperty, BooleanProperty, NumericProperty, DictProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.recycleview import RecycleView
from kivy.resources import resource_find
from generalelements import *
from smoothsetting import SmoothSetting
#Multiplayer screen imports, delay until needed
Connector = None
socket = None
class Theme(Widget):
"""Theme class that stores all the colors used in the interface."""
#not used currently
button_warn_down = ListProperty([0.78, 0.33, 0.33, 1.0])
button_warn_up = ListProperty([1.0, 0.6, 0.6, 1.0])
#Not Setable
scroller = ListProperty([0.7, 0.7, 0.7, 0.388])
scroller_selected = ListProperty([0.7, 0.7, 0.7, 0.9])
info_text = ListProperty([0.0, 0.0, 0.0, 1.0])
info_background = ListProperty([1.0, 1.0, 0.0, 0.75])
darkened = ListProperty([0, 0, .1, .2])
#Set By Theme
button_down = ListProperty([1, 1, 1, 1])
button_up = ListProperty([1, 1, 1, 1])
button_text = ListProperty([1, 1, 1, 1])
button_toggle_true = ListProperty([1, 1, 1, 1])
button_toggle_false = ListProperty([1, 1, 1, 1])
button_disabled = ListProperty([1, 1, 1, 1])
button_disabled_text = ListProperty([1, 1, 1, 1])
slider_background = ListProperty([1, 1, 1, 1])
slider_grabber = ListProperty([1, 1, 1, 1])
input_background = ListProperty([1, 1, 1, 1])
header_background = ListProperty([1, 1, 1, 1])
header_text = ListProperty([1, 1, 1, 1])
text = ListProperty([1, 1, 1, 1])
disabled_text = ListProperty([1, 1, 1, 1])
selected = ListProperty([1, 1, 1, 1])
indented = ListProperty([1, 1, 1, 1])
background = ListProperty([1, 1, 1, 1])
background_overlay = ListProperty([1, 1, 1, 1])
background_column = ListProperty([1, 1, 1, 1])
shadow_color = ListProperty([0, 0, 0, .15])
I = ListProperty([1, 1, 1, 1])
J = ListProperty([1, 1, 1, 1])
L = ListProperty([1, 1, 1, 1])
O = ListProperty([1, 1, 1, 1])
S = ListProperty([1, 1, 1, 1])
Z = ListProperty([1, 1, 1, 1])
T = ListProperty([1, 1, 1, 1])
class MainScreenManager(ScreenManager):
"""Base screen manager class, holds the various game screens"""
pass
class MainScreen(TetraScreen):
"""Screen that displays the main menu"""
scores_a = ListProperty()
scores_b = ListProperty()
def on_enter(self):
app.clear_selected_overlay()
self.scores_a = []
self.scores_b = []
for score in app.scores_a:
score_formatted = str(score[0])+'points '+str(score[1])+'lines '+score[2]
self.scores_a.append({'text': score_formatted})
for score in app.scores_b:
score_formatted = str(score[0])+'points '+str(score[1])+'lines '+score[2]
self.scores_b.append({'text': score_formatted})
class TouchArea(BoxLayout):
image = StringProperty('')
function = StringProperty('down')
def on_touch_down(self, touch):
if self.disabled:
return
game_screen = app.game_screen
if game_screen is None:
return
if game_screen.paused or game_screen.replay or not game_screen.game_running:
return
if self.collide_point(*touch.pos):
touch.grab(self)
if self.function == 'down':
game_screen.move_down()
game_screen.move_down_touch()
elif self.function == 'left':
game_screen.move_left()
game_screen.move_left_touch()
elif self.function == 'right':
game_screen.move_right()
game_screen.move_right_touch()
def on_touch_up(self, touch):
if touch.grab_current is self:
touch.ungrab(self)
game_screen = app.game_screen
if game_screen is None:
return
if self.function == 'down':
game_screen.move_down_touch_off()
elif self.function == 'left':
game_screen.move_left_touch_off()
elif self.function == 'right':
game_screen.move_right_touch_off()
class TouchControl(BoxLayout):
delay_move = ObjectProperty(allownone=True)
invisible = BooleanProperty(False)
swipe_distance = 50
swipe_down_distance = 100
def on_touch_down(self, touch):
game_screen = app.game_screen
if game_screen is None:
return
if game_screen.paused or game_screen.replay or not game_screen.game_running:
return
if app.touch_area or self.invisible:
if self.collide_point(*touch.pos):
touch.grab(self)
self.delay_move = Clock.schedule_once(lambda x: self.update_move(touch), app.rotate_time)
def on_touch_move(self, touch):
if touch.grab_current is self:
touch_length = time.time() - touch.time_start
if touch_length > app.rotate_time:
self.update_move(touch)
def update_move(self, touch):
game_screen = app.game_screen
if game_screen is None:
return
x_pos = touch.pos[0] - self.pos[0]
touch_percent_x = x_pos / self.width
if touch_percent_x < 0:
touch_percent_x = 0
elif touch_percent_x > 1:
touch_percent_x = 1
game_screen.move_x_percent(touch_percent_x)
def on_touch_up(self, touch):
if self.delay_move:
self.delay_move.cancel()
self.delay_move = None
if touch.grab_current is self:
touch.ungrab(self)
game_screen = app.game_screen
if game_screen is None:
return
game_screen.move_x_percent_off()
touch_length = touch.time_end - touch.time_start
if touch_length <= app.rotate_time:
x_delta = touch.opos[0] - touch.pos[0]
y_delta = touch.opos[1] - touch.pos[1]
swiped = False
if abs(x_delta) > abs(y_delta):
if x_delta > self.swipe_distance:
#swipe left
swiped = True
if app.play_swipe:
game_screen.rotate_left()
else:
game_screen.move_left()
elif x_delta < 0 - self.swipe_distance:
#swipe right
swiped = True
if app.play_swipe:
game_screen.rotate_right()
else:
game_screen.move_right()
elif app.swipe_vertical:
if y_delta > self.swipe_down_distance:
#swipe down
swiped = True
game_screen.hard_down()
elif y_delta < 0 - self.swipe_down_distance:
#swipe up
swiped = True
#game_screen.store()
if not swiped:
x_pos = touch.pos[0] - self.pos[0]
touch_percent_x = x_pos / self.width
if not app.play_tap:
if touch_percent_x < 0.5:
game_screen.rotate_left()
else:
game_screen.rotate_right()
else:
if touch_percent_x < 0.5:
game_screen.move_left()
else:
game_screen.move_right()
class TouchButton(ButtonBehavior, BoxLayout):
image = StringProperty('')
def on_touch_down(self, touch):
game_screen = app.game_screen
if game_screen is None:
return
if game_screen.paused or game_screen.replay or not game_screen.game_running:
return
return super().on_touch_down(touch)
class Tetrivium(App):
icon = 'data/icon.png'
local_ip = StringProperty('')
external_local_ip = StringProperty('')
remote_ip = StringProperty('')
port = NumericProperty(0)
connected = BooleanProperty(False)
connecting = BooleanProperty(False)
connect_status = StringProperty('Ready To Connect')
connect_action = StringProperty('Connect...')
available_addresses = ListProperty()
has_crashlog = BooleanProperty(False)
crashlog_date = StringProperty()
piece_color2_alpha = NumericProperty(0.333)
popup = ObjectProperty(allownone=True)
helppopup = ObjectProperty(allownone=True)
vibrator = None
font_file = 'data/4mini.ttf'
display_border = NumericProperty(16)
button_scale = NumericProperty(1)
app_directory = StringProperty()
shift_pressed = False
savefolder = StringProperty('histories')
theme = ObjectProperty()
infotext = StringProperty()
infotext_setter = ObjectProperty()
screen_manager = ObjectProperty()
game_screen = ObjectProperty()
replay_screen = ObjectProperty()
settings_screen = ObjectProperty()
control_screen = ObjectProperty()
sprint_screen = ObjectProperty()
marathon_screen = ObjectProperty()
multiplayer_screen = ObjectProperty()
about_screen = ObjectProperty()
text_scale = NumericProperty(1)
animations = BooleanProperty(True)
animation_length = NumericProperty(.2)
piece_animations = BooleanProperty(True)
drop_forgive_multiplier = NumericProperty(1)
clear_length = .5
fall_length = .15
background_image = StringProperty('theme/background.png')
column_image = StringProperty('theme/column.png')
window_leave_timeout = ObjectProperty(allownone=True)
rotate_time = NumericProperty(0.33)
piece_shadow = BooleanProperty(True)
vibration = BooleanProperty(True)
play_swipe = BooleanProperty(False)
play_tap = BooleanProperty(False)
touch_area = BooleanProperty(False)
touch_scale = NumericProperty(1)
touch_rotate = BooleanProperty(True)
touch_slide = BooleanProperty(True)
swipe_vertical = BooleanProperty(True)
deadzone = NumericProperty(0.25)
sound_effects = BooleanProperty(False)
volume = NumericProperty(1)
music_volume = NumericProperty(1)
pause_data = StringProperty('')
theme_folder = StringProperty('')
screen_border = NumericProperty(0)
line_animations = BooleanProperty(True)
music_support = BooleanProperty(True)
music = ObjectProperty(allownone=True)
music_looper = ObjectProperty(allownone=True)
music_start_time = 0
music_pos = 0
music_loop = NumericProperty(0)
music_theme = NumericProperty(0)
musics = ListProperty()
sounds = DictProperty()
scores_a = ListProperty()
scores_b = ListProperty()
m_left = ListProperty()
m_right = ListProperty()
m_down = ListProperty()
m_rotate_l = ListProperty()
m_rotate_r = ListProperty()
m_drop = ListProperty()
m_store = ListProperty()
m_pause = ListProperty()
mp_connection = ObjectProperty(allownone=True)
mp_ready_start = BooleanProperty(False)
mp_thinking = BooleanProperty(False)
multiplayer_text = ListProperty()
multiplayer_text_current = StringProperty()
multiplayer_typing = BooleanProperty(False)
window_maximized = BooleanProperty(False)
window_top = NumericProperty(0)
window_left = NumericProperty(0)
window_width = NumericProperty(400)
window_height = NumericProperty(600)
timer_current = 0
overlay_color = ListProperty([.8, 1, .8, .33])
selected_object = ObjectProperty(allownone=True)
last_joystick_axis = NumericProperty(0)
button_update = BooleanProperty(False)
def help(self, helptext='Help Text'):
if self.helppopup:
return
content = HelpPopupContent(text=helptext)
app.helppopup = NormalPopup(title="", content=content, size_hint=(.9, .9), auto_dismiss=False)
app.helppopup.open()
def reaction_receive(self, reaction):
if reaction in emotions_colors.keys():
reaction_modal = ReactionOverlay(emotion=reaction)
reaction_modal.open()
def load_theme(self):
#This function will handle all theme colors and image loading into local variables.
default_theme_folder = os.path.join(self.app_directory, 'theme')
theme_folder = self.get_theme_folder()
background_test = os.path.join(theme_folder, 'background.png')
if os.path.isfile(background_test):
self.background_image = background_test
else:
self.background_image = os.path.join(default_theme_folder, 'background.png')
column_test = os.path.join(theme_folder, 'column.png')
if os.path.isfile(column_test):
self.column_image = column_test
else:
self.column_image = os.path.join(default_theme_folder, 'column.png')
default_theme = Theme()
color_file = 'theme.ini'
test_file = os.path.join(theme_folder, color_file)
if os.path.isfile(test_file):
theme_file = test_file
else:
theme_file = os.path.join(default_theme_folder, color_file)
try:
config_file = ConfigParser(interpolation=None)
config_file.read(theme_file)
sections = config_file.sections()
try:
color_alpha = float(config_file.get('Colors', 'color_alpha'))
self.piece_color2_alpha = color_alpha
except:
self.piece_color2_alpha = 0.333
if 'Colors' in sections:
for color_name in color_names:
try:
color_data = config_file.get('Colors', color_name)
color_values = color_data.split(',')
color_values_float = []
for color_value in color_values:
color_values_float.append(float(color_value))
if len(color_values_float) == len(getattr(self.theme, color_name)):
setattr(self.theme, color_name, color_values_float)
except Exception as exc:
#cant load color, use default color
setattr(self.theme, color_name, getattr(default_theme, color_name))
except:
#full reset theme
self.piece_color2_alpha = 0.333
for color_name in color_names:
setattr(self.theme, color_name, getattr(default_theme, color_name))
self.button_update = not self.button_update
def format_frames(self, frames):
#Formats a number of frames into a standard minutes:seconds string
seconds_total = int(round(frames / fps))
seconds = seconds_total % 60
minutes = seconds_total // 60
return str(minutes)+':'+str(seconds).zfill(2)
def navigation_key(self, key):
#when given a key code, returns a string value to determine which navigation key was pressed
if key in navigation_next:
return 'next'
elif key in navigation_prev:
return 'prev'
elif key in navigation_activate:
return 'enter'
elif key in navigation_back:
return 'back'
elif key in navigation_left:
return 'left'
elif key in navigation_right:
return 'right'
else:
return None
def dismiss_popup(self, *_):
#Close the app's open popup if it has one
if self.popup:
self.popup.dismiss()
self.popup = None
return True
return False
def activate_selected(self):
#Attempts to activate the current selected_object, depending on what kind of widget it is.
try:
self.selected_object.trigger_action()
except:
pass
try:
self.selected_object.focus = True
except:
pass
def find_active(self, root_widget, forward, found):
if root_widget == self.selected_object and not found:
#The root widget is the current active! If True is returned when recursively searching, the next recursion level up will try to find the next available widget in the tree
return True
if isinstance(root_widget, RecycleView):
#Recycleview, need to do special stuff to acconut for some children not currently existing
is_recycle = True
recycle_layout = root_widget.children[0]
children = sorted(recycle_layout.children, key=lambda x: (x.y, x.x))
else:
#Other types of layouts, just iterate through the child list
is_recycle = False
recycle_layout = None
children = list(root_widget.children)
if forward:
children.reverse()
for index, child in enumerate(children):
is_selectable = hasattr(child, 'selectable_item') and child.selectable_item
if found and not child.disabled and is_selectable:
#last widget in the tree was the old active, now this child becomes the current active
return child
found_active = self.find_active(child, forward, found)
if found_active is True:
#This child or one of its children is selected, need to find the next possible
found = True
if is_recycle and index + 1 >= len(children) and is_selectable:
#This recycleview has no more children to switch to, it could be on the last child, or it may need to be scrolled
scrollable_x = recycle_layout.width - root_widget.width #how many pixels of scrolling is available in the x direction
scrollable_y = recycle_layout.height - root_widget.height
if root_widget.do_scroll_x and scrollable_x > 0: #root can scroll in horizontal
if forward and root_widget.scroll_x > 0: #root can and should scroll forward
root_widget.scroll_x = max(root_widget.scroll_x - (self.selected_object.width / scrollable_x), 0)
return self.selected_object
elif not forward and root_widget.scroll_x < 1: #root can and should scroll backward
root_widget.scroll_x = min(root_widget.scroll_x + (self.selected_object.width / scrollable_x), 1)
return self.selected_object
elif root_widget.do_scroll_y and scrollable_y > 0: #root can scroll in vertical
if forward and root_widget.scroll_y > 0: #root can and should scroll forward
root_widget.scroll_y = max(root_widget.scroll_y - (self.selected_object.height / scrollable_y), 0)
return self.selected_object
elif not forward and root_widget.scroll_y < 1: #root can and should scroll backward
root_widget.scroll_y = min(root_widget.scroll_y + (self.selected_object.height / scrollable_y), 1)
return self.selected_object
elif found_active is None:
#active not found in this child or its children, move on to the next child
continue
else:
#the next active was found, return it to go up one recursion level
return found_active
if found:
#Tried to find the next active but couldnt, continue search in the next tree up
return True
return None #The active was not found in this tree at all
def selected_item(self, lookin, forward):
active = self.find_active(lookin, forward, False)
if active is True:
active = self.find_active(lookin, forward, True)
self.set_current_selected(lookin, active)
def selected_next(self, lookin):
#Convenience function for selecting the next widget in the tree
self.selected_item(lookin, True)
def selected_prev(self, lookin):
#Convenience function for selecting the previous widget in the tree
self.selected_item(lookin, False)
def set_current_selected(self, lookin, to_select):
#This function will set a given widget as selected if it is given, otherwise it will find the first valid selectable widget
if self.selected_object is None and to_select is None:
for widget in lookin.walk(restrict=True):
if hasattr(widget, 'selectable_item'):
if widget.selectable_item:
app.set_selected_overlay(widget)
break
else:
app.set_selected_overlay(to_select)
def set_selected_overlay(self, widget):
#This function will actually set the given widget as the current selected, also ensures it is scrolled to if in a Scroller
self.selected_object = widget
if widget is None:
return
parent = widget.parent
while parent is not None:
if parent.parent == parent:
break
if hasattr(parent, 'scroll_y'):
try:
if parent.children[0].height < parent.height:
parent.scroll_y = 1
else:
parent.scroll_to(widget, animate=False, padding=20)
except:
pass
break
parent = parent.parent
def clear_selected_overlay(self, *_):
#Sets the current selected object to none
self.selected_object = None
def timer(self, *_):
#Testing function, returns the amount of time elapsed since the function was last run
timer_current = time.time()
timer_amount = timer_current - self.timer_current
self.timer_current = timer_current
return timer_amount
def load_window_size(self):
#Loads the window size and position from the settings file, sets it to local variables, and applies the size if necessary
self.window_maximized = self.config.getboolean('Settings', 'window_maximized')
if self.window_maximized:
Window.maximize()
else:
self.window_top = int(self.config.get('Settings', 'window_top'))
self.window_left = int(self.config.get('Settings', 'window_left'))
self.window_height = int(self.config.get('Settings', 'window_height'))
self.window_width = int(self.config.get('Settings', 'window_width'))
if desktop:
Window.minimum_height = 640
Window.minimum_width = 480
if self.window_maximized:
Window.maximize()
else:
Window.size = self.window_width, self.window_height
Window.left = self.window_left
Window.top = self.window_top
def store_window_size(self):
#Saves the current window size and position to local variables and to the settings file
self.config.set("Settings", "window_maximized", 1 if self.window_maximized else 0)
if self.window_maximized:
return
self.window_top = Window.top
self.window_left = Window.left
self.window_width = Window.size[0]
self.window_height = Window.size[1]
self.config.set('Settings', 'window_top', self.window_top)
self.config.set('Settings', 'window_left', self.window_left)
self.config.set('Settings', 'window_width', self.window_width)
self.config.set('Settings', 'window_height', self.window_height)
def set_scale(self, *_):
#Sets button and text scale values based on current window size
self.store_window_size()
scale = Window.height / 15
#scale = int(float(cm(0.85)))
self.display_border = scale / 3
self.button_scale = scale
aspect = Window.width / Window.height
if aspect > 1:
extra = min(aspect - 1, 0.5)
self.text_scale = scale / (3.5 - extra)
else:
self.text_scale = scale / 4
def bump(self, level):
#If the vibrator is activated, vibrates a given strength (level should be 0-5)
if vibrator:
if self.vibration:
vibrate_amounts = [0, .02, .05, .075, .1, .25]
vibrator.vibrate(vibrate_amounts[level])
def connection_friendly(self, multiplayer_mode):
#Returns a 'friendly' formatted string for the current multiplayer mode
if multiplayer_mode == 'port_forward':
return 'Port Forwarding'
elif multiplayer_mode == 'direct':
return 'Direct Connection'
elif multiplayer_mode == 'bluetooth':
return 'Bluetooth Connection'
else: #multiplayer_mode == 'local':
return 'Local'
def multiplayer_send(self, command, data):
#sent messages:
# 'add lines', [number, space]
# 'game over'
# 'pause start'
# 'pause end'
# 'speed set', [speed]
# 'filled set', [filled]
# 'game start', [seed]
# 'line height', [height]
# 'leave game'
# 'chat typing'
# 'chat not typing'
# 'chat', [text]
# 'reaction', [text]
data = list(map(str, data))
command = command+';'+','.join(data)
if self.mp_connection is not None:
self.mp_connection.send(command)
def scroll_bottom(self):
if self.multiplayer_screen:
self.multiplayer_screen.ids['chatArea'].scroll_y = 0
if self.game_screen:
self.game_screen.ids['chatArea'].scroll_y = 0
def multiplayer_send_message(self):
if self.multiplayer_text_current:
self.multiplayer_send('chat', [self.multiplayer_text_current])
self.multiplayer_text.append({'text': 'Me: '+self.multiplayer_text_current})
self.scroll_bottom()
self.multiplayer_text_current = ''
def multiplayer_receive(self, instance, message):
command, data = message.split(';', 1)
multiplayer_screen = self.multiplayer_screen
if multiplayer_screen is None:
return
if command == 'chat typing':
self.multiplayer_typing = True
if command == 'chat not typing':
self.multiplayer_typing = False
if command == 'chat':
self.multiplayer_typing = False
self.multiplayer_text.append({'text': 'Them: '+data})
self.scroll_bottom()
data = data.split(',')
if command == 'speed set':
multiplayer_screen.other_speed = int(data[0])
elif command == 'filled set':
multiplayer_screen.other_filled = int(data[0])
elif command == 'game start':
Clock.schedule_once(lambda x: self.multiplayer_screen.start_game_finish(seed=float(data[0])))
self.multiplayer_send('game ready', [])
elif command == 'game ready':
if multiplayer_screen.starting_game:
Clock.schedule_once(lambda x: multiplayer_screen.start_game_finish())
game_screen = self.game_screen
if game_screen is not None:
if command == 'leave game':
if self.screen_manager.current == 'game':
game_screen.back()
elif command == 'reaction':
self.reaction_receive(data[0])
elif command == 'line height':
game_screen.opponent_block_height = int(data[0])
game_running = game_screen.game_running
if game_running:
if command == 'add lines':
self.play_sound('add_line')
lines, spacer = data
lines = int(lines)
spacer = int(spacer)
block = random.randint(0, len(pieces)-1)
for index in range(0, lines):
game_screen.lines_to_add.append([spacer, block])
elif command == 'pause start':
game_screen.pause(force=True, silent=True)
elif command == 'pause end':
if game_screen.paused:
game_screen.pause(silent=True)
elif command == 'game over':
Clock.schedule_once(lambda x: game_screen.game_win())
def multiplayer_disconnect(self, *_):
self.multiplayer_text = []
if self.multiplayer_screen:
self.multiplayer_screen.starting_game = False
if self.screen_manager.current == 'game':
Clock.schedule_once(lambda x: self.game_screen.back())
def multiplayer_start(self):
if self.multiplayer_screen is None:
return
global socket
import socket
global Connector
from connector import Connector
if self.mp_connection is None and socket is not None:
try:
self.port = int(float(app.config.get('Settings', 'last_multiplayer_port')))
except:
self.port = multiplayer_port
self.mp_connection = Connector(app_name=app_name, port=multiplayer_port)
self.mp_connection.bind(on_ask_connect=self.multiplayer_screen.ask_connect)
self.mp_connection.bind(on_connect=self.multiplayer_screen.connected)
self.mp_connection.bind(on_disconnect=self.multiplayer_disconnect)
self.mp_connection.bind(on_receive=self.multiplayer_receive)
self.mp_connection.bind(on_mode=self.multiplayer_screen.stop_game_start)
self.mp_connection.bind(on_connected=self.save_multiplayer_ip)
self.mp_connection.bind(on_connected=self.save_port)
self.mp_connection.bind(local_ip=self.setter('local_ip'))
self.mp_connection.bind(external_local_ip=self.setter('external_local_ip'))
self.mp_connection.bind(port=self.setter('port'))
self.mp_connection.bind(remote_ip=self.setter('remote_ip'))
self.mp_connection.bind(connected=self.setter('connected'))
self.mp_connection.bind(connecting=self.setter('connecting'))
self.mp_connection.bind(connect_status=self.setter('connect_status'))
self.mp_connection.bind(connect_action=self.setter('connect_action'))
self.mp_connection.bind(available_addresses=self.setter('available_addresses'))
self.mp_connection.bind(thinking=self.setter('mp_thinking'))
def multiplayer_stop(self):
if self.mp_connection is not None:
self.mp_connection.stop()
def save_multiplayer_ip(self, *_):
if self.mp_connection.mode != 'local':
self.config.set('Settings', 'last_multiplayer', self.mp_connection.remote_ip)
def save_port(self, *_):
if self.mp_connection.mode != 'local':
self.config.set('Settings', 'last_multiplayer_port', str(self.mp_connection.port))
def block_file(self, block_type=''):
if block_type == '':
return ''
theme_folder = self.get_theme_folder()
block_file = 'block-'+block_type.lower()+'.png'
test_file = os.path.join(theme_folder, block_file)
if os.path.isfile(test_file):
return test_file
else:
base_file = os.path.join(theme_folder, 'block.png')
if os.path.isfile(base_file):
return base_file
else:
default_theme_folder = os.path.join(self.app_directory, 'theme')
original_file = os.path.join(default_theme_folder, block_file)
return original_file
def reset_settings(self):
if desktop:
touch_area = 0
else:
touch_area = 1
settings = {
'touch_area': touch_area,
'touch_scale': 1,
'vibration': 1,
'touch_rotate': 1,
'touch_slide': 1,
'play_swipe': 0,
'play_tap': 0,
'swipe_vertical': 1,
'rotate_time': 0.25,
'shadow': 1,
'deadzone': 0.25,
'screen_border': 0,
'theme_folder': '',
'sound_effects': 1,
'piece_animations': 1,
'drop_forgive_multiplier': 1,
'line_animations': 1,
'volume': 1,
'music_volume': 0.5,
'slected_music': 0,
'last_multiplayer': '',
'last_multiplayer_mode': 'local',
'last_multiplayer_port': '',
'window_maximized': 0,
'window_top': 50,
'window_left': 10,
'window_width': 400,
'window_height': 600,
}
for setting in settings:
self.config.set("Settings", setting, settings[setting])
self.update_config_settings()
self.load_window_size()
def build_config(self, config):
#Setup config file if it is not found
if desktop:
touch_area = 0
else:
touch_area = 1
config.setdefaults(
'Settings', {
'scores_a': '',
'scores_b': '',
'touch_area': touch_area,
'touch_scale': 1,
'vibration': 1,
'touch_rotate': 1,
'touch_slide': 1,
'play_swipe': 0,
'play_tap': 0,
'swipe_vertical': 1,
'rotate_time': 0.25,
'shadow': 1,
'pause_data': '',
'deadzone': 0.25,
'screen_border': 0,
'theme_folder': '',
'sound_effects': 1,
'piece_animations': 1,
'drop_forgive_multiplier': 1,
'line_animations': 1,
'volume': 1,
'music_volume': 0.5,
'slected_music': 0,
'last_multiplayer': '',
'last_multiplayer_mode': 'local',
'last_multiplayer_port': '',
'window_maximized': 0,
'window_top': 50,
'window_left': 10,
'window_width': 400,
'window_height': 600,
})
config.setdefaults(
'Controls', {
'm_left': ','.join([str(item) for item in default_c_left]),
'm_right': ','.join([str(item) for item in default_c_right]),
'm_rotate_l': ','.join([str(item) for item in default_c_rotate_l]),
'm_rotate_r': ','.join([str(item) for item in default_c_rotate_r]),
'm_down': ','.join([str(item) for item in default_c_down]),
'm_drop': ','.join([str(item) for item in default_c_drop]),
'm_store': ','.join([str(item) for item in default_c_store]),
'm_pause': ','.join([str(item) for item in default_c_pause]),
})
def on_config_change(self, config, section, key, value):
self.update_config_settings()
def update_config_settings(self, *_):
self.theme_folder = self.config.get("Settings", "theme_folder")
self.piece_shadow = self.config.getboolean("Settings", "shadow")
self.vibration = self.config.getboolean("Settings", "vibration")
self.touch_area = self.config.getboolean("Settings", "touch_area")
self.touch_scale = float(self.config.get("Settings", "touch_scale"))
self.touch_rotate = self.config.getboolean("Settings", "touch_rotate")
self.touch_slide = self.config.getboolean("Settings", "touch_slide")
self.play_swipe = self.config.getboolean("Settings", "play_swipe")
self.play_tap = self.config.getboolean("Settings", "play_tap")
self.rotate_time = float(self.config.get("Settings", "rotate_time"))
self.swipe_vertical = self.config.getboolean("Settings", "swipe_vertical")
self.deadzone = float(self.config.get("Settings", "deadzone"))
self.sound_effects = self.config.getboolean("Settings", "sound_effects")
self.volume = float(self.config.get("Settings", "volume"))
self.music_volume = float(self.config.get('Settings', 'music_volume'))
self.music_theme = int(self.config.get('Settings', 'slected_music'))
self.piece_animations = self.config.getboolean("Settings", "piece_animations")
self.drop_forgive_multiplier = float(self.config.get('Settings', 'drop_forgive_multiplier'))
self.line_animations = self.config.getboolean("Settings", "line_animations")
self.screen_border = int(self.config.get("Settings", "screen_border"))
def message(self, text, timeout=20):
"""Sets the app.infotext variable to a specific message, and clears it after a set amount of time."""
self.infotext = text
if self.infotext_setter:
self.infotext_setter.cancel()
self.infotext_setter = Clock.schedule_once(self.clear_message, timeout)
def clear_message(self, *_):
self.infotext = ''
def load_scores(self):
self.scores_a = self.load_score('scores_a')
self.scores_b = self.load_score('scores_b')
def load_score(self, score_name):
scores_data = self.config.get("Settings", score_name).split(';')
scores = []
for score in scores_data:
try:
score_value, score_lines, score_date = score.split(',', 2)
score_value = int(score_value)
score_lines = int(score_lines)
scores.append([score_value, score_lines, score_date])
except:
pass
return scores
def clear_scores(self):
self.scores_a = []
self.scores_b = []
self.save_scores()
def add_score(self, score, lines, date_data, mode):
self.load_scores()
if mode == 'C':
return
elif mode == 'B':
self.scores_b.append([score, lines, date_data])
else:
self.scores_a.append([score, lines, date_data])
self.sort_scores()