-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrtk.py
More file actions
2610 lines (2387 loc) · 104 KB
/
Copy pathrtk.py
File metadata and controls
2610 lines (2387 loc) · 104 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 os
import pygame
import string
import logging
import logging.config
import traceback
import configparser
import random
import csv
from datetime import datetime
from math import ceil, floor, pi, cos, sin, radians, degrees
from PIL import Image
from pygame.locals import *
''' Global constants '''
scr_w = 320
scr_h = 240
fps = 60
msg_title_x = 'center'
msg_title_y = 24
msg_text_x = 24
msg_text_y = 56
''' Main Sprite Container '''
all_sprites = pygame.sprite.LayeredDirty()
''' Utility Functions '''
def get_display_inf():
return pygame.display.Info()
def print_screen():
screen_copy = screen.copy().convert()
capture_file = os.path.join(capture_dir, 'capture_' + str(datetime.now().strftime('%Y_%m_%d_%H_%M_%S')) + '.bmp')
pygame.image.save(screen_copy, capture_file)
def parse_val(value):
try:
if 'Rtk' in value:
val = value.replace(' ','')
else:
val = eval(value) # int and list
except:
# bool
if value.lower() in ("yes", "true", "t", "1"):
val = True
elif value.lower() in ("no", "false", "f", "0"):
val = False
elif value.lower() == 'none':
val = None
else:
val = value # string
return val
def get_color_key(image):
return image.get_at((0, 0))
def load_image(image, colorkey=None):
try:
img_path = os.path.join(path_rgbpi_images, image)
img_path_2 = os.path.join(img_dir, image)
if os.path.isfile(img_path):
image = pygame.image.load(img_path)
else:
image = pygame.image.load(img_path_2)
rect = image.get_rect()
except Exception as error:
logging.debug('Cannot load image: %s, error: %s', image, error)
else:
image = image.convert()
if colorkey is not None:
if colorkey == 'auto':
colorkey = get_color_key(image)
image.set_colorkey(colorkey, pygame.RLEACCEL)
return image, rect
def load_image_at(image, rectangle, colorkey=None):
# Load a specific image from a specific rectangle
# Rectangle = x, y, x+offset, y+offset
rect = pygame.Rect(rectangle)
subimage = pygame.Surface(rect.size).convert()
subimage.blit(image, (0, 0), rect)
if colorkey is not None:
if colorkey == 'auto':
colorkey = get_color_key(subimage)
subimage.set_colorkey(colorkey, pygame.RLEACCEL)
return subimage
def load_images_at(image, rects, colorkey=None):
# Load a whole bunch of images and return them as a list.
return [load_image_at(image, rect, colorkey) for rect in rects]
def load_rect(w, h, color, colorkey=None):
image = pygame.Surface((w, h))
image.fill(color)
image = image.convert()
if colorkey is not None:
if colorkey == 'auto':
colorkey = get_color_key(image)
image.set_colorkey(colorkey, pygame.RLEACCEL)
return image, image.get_rect()
def load_translations():
translations = []
with open(trans_file, 'r', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
for row in reader:
translation = {'Lang':row["Lang"],'Name':row["Name"],'Value':row["Value"]}
translations.append(translation)
return translations
def get_translation(name):
for translation in translations:
if translation["Name"] == name and translation["Lang"] == cfg_language:
return translation["Value"]
return name
def load_font_map(font_file):
# Load font map from data sheet
font_map = {}
with open(font_file, 'r', encoding='utf-8') as file:
for line in file:
line = line.replace('\n','')
char_map = line.split(',')
# Fix comma char and comma separator
if len(char_map) == 6:
del char_map[0]
char_map[0] = ','
if len(char_map[0]) > 1: # lower key words
char_map[0] = char_map[0].lower()
font_map[char_map[0]] = char_map[1:]
# Get char size
rectangle = font_map['0']
char_width = int(rectangle[2])
char_height = int(rectangle[3])
return font_map, char_width, char_height
def get_random_id():
alphabet = string.ascii_lowercase + string.digits
return ''.join(random.choices(alphabet, k=8))
def load_trasition(is_refresh=False):
global transition, transition_tate
global err_draw_trans
err_draw_trans = False
opid=get_random_id()
if is_refresh:
try:
cont_bg = ContainerMgr.containers['Background']
for widget in cont_bg.widgets:
if widget.name in ('Transition','Transition_Tate'):
cont_bg.remove(widget=widget,opid=opid)
except:
pass
try:
transition = RtkAniGif(name='Transition', image='transition.gif', position=(tran_x,tran_y), speed=tran_speed, loop=False)
transition_tate = RtkAniGif(name='Transition_Tate', image='transition_tate.gif', position=(tran_x,tran_y), speed=tran_speed, loop=False)
except Exception as error:
logging.error('Error loading transition image. Falling back on RtkRect. %s\n%s', error, traceback.format_exc())
transition = RtkRect(name='Transition', position=(0,0), w=0, h=0)
transition_tate = RtkRect(name='Transition_Tate', position=(0,0), w=0, h=0)
transition._layer = 5
transition_tate._layer = 5
ContainerMgr.append(parent=container_bg, child=transition)
ContainerMgr.append(parent=container_bg, child=transition_tate)
def load_mouse(is_refresh=False):
global mouse
global err_draw_mouse
err_draw_mouse = False
opid=get_random_id()
if is_refresh:
try:
cont_bg = ContainerMgr.containers['Background']
for widget in cont_bg.widgets:
if widget.name in ('Mouse'):
cont_bg.remove(widget=widget,opid=opid)
except:
pass
try:
mouse = RtkImage(name='lgun_aim', image='lgun_aim.bmp', is_active=False, position=(0,0), colorkey=color_key)
except:
logging.error('Error loading mouse image. Falling back on RtkRect')
mouse = RtkRect(name='Transition', position=(0,0), w=8, h=8)
mouse._layer = 5
ContainerMgr.append(parent=container_bg, child=mouse)
def draw_transition(time_step):
global err_draw_trans
try:
transition_tate.animate(time_step)
transition.animate(time_step)
except Exception as error:
if not err_draw_trans:
logging.error('Error drawing transition. %s', error)
err_draw_trans = True
def load_messages(is_refresh=False):
global error_msg, user_msg, popup_msg, notif_msg
if is_refresh:
try:
opid=get_random_id()
error_msg.destroy(opid=opid)
user_msg.destroy(opid=opid)
popup_msg.destroy(opid=opid)
notif_msg.destroy(opid=opid)
except:
pass
error_msg = RtkTxtMsg(name='Error',type='full',title='error_title',text='Error text',txt_color=msg_error_txt_color,bg_color=msg_error_bg_color, duration=5)
user_msg = RtkTxtMsg(name='Info',type='full',title='info_title',text='Info text',txt_color=msg_info_txt_color,bg_color=msg_info_bg_color)
popup_msg = RtkTxtMsg(name='Popup',type='popup',text=' Popup text ',txt_color=msg_popup_txt_color,bg_color=msg_popup_bg_color, bg_border_color=msg_popup_bg_border_color)
notif_msg = RtkTxtMsg(name='Notif',type='popup',text=' Popup text ',txt_color=msg_notif_txt_color,bg_color=msg_notif_bg_color, bg_border_color=msg_notif_bg_border_color, duration=2)
def draw_messages(time_step):
error_msg.draw_msg(time_step)
user_msg.draw_msg(time_step)
popup_msg.draw_msg(time_step)
notif_msg.draw_msg(time_step)
def load_background(is_refresh=False):
global background, background_tate
global container_bg
global err_draw_bg
err_draw_bg = False
opid=get_random_id()
if is_refresh:
try:
cont_bg = ContainerMgr.containers['Background']
for widget in cont_bg.widgets:
if widget.name in ('Background','Background_Tate'):
cont_bg.remove(widget=widget,opid=opid)
except:
pass
try:
if bg_type == 'static':
background = RtkSprite(name='Background', image='background.bmp', position=(0,0), opid=opid)
background_tate = RtkSprite(name='Background_Tate', image='background_tate.bmp', position=(0,0), opid=opid)
elif bg_type == 'ani_gif':
background = RtkAniGif(name='Background', image='background.gif', position=(0,0), speed=bg_speed, opid=opid)
background_tate = RtkAniGif(name='Background_Tate', image='background_tate.gif', position=(0,0), speed=bg_speed, opid=opid)
elif bg_type == 'scroll_left':
background = RtkScrollBg(name='Background', image='background.bmp', type='h', position=(0, 0), opid=opid)
background.set_scroll(state=-1)
background_tate = RtkScrollBg(name='Background_Tate', image='background_tate.bmp', type='h', is_tate=True, position=(0, 0), opid=opid)
background_tate.set_scroll(state=-1)
elif bg_type == 'scroll_right':
background = RtkScrollBg(name='Background', image='background.bmp', type='h', position=(0, 0), opid=opid)
background.set_scroll(state=1)
background_tate = RtkScrollBg(name='Background_Tate', image='background_tate.bmp', type='h', is_tate=True, position=(0, 0), opid=opid)
background_tate.set_scroll(state=1)
elif bg_type == 'scroll_up':
background = RtkScrollBg(name='Background', image='background.bmp', type='v', position=(0, 0), opid=opid)
background.set_scroll(state=-1)
background_tate = RtkScrollBg(name='Background_Tate', image='background_tate.bmp', type='v', is_tate=True, position=(0, 0), opid=opid)
background_tate.set_scroll(state=-1)
elif bg_type == 'scroll_down':
background = RtkScrollBg(name='Background', image='background.bmp', type='v', position=(0, 0), opid=opid)
background.set_scroll(state=1)
background_tate = RtkScrollBg(name='Background_Tate', image='background_tate.bmp', type='v', is_tate=True, position=(0, 0), opid=opid)
background_tate.set_scroll(state=1)
elif bg_type == 'parallax_left':
background = RtkParallaxBg(name='Background', image='background.bmp', type='h', position=(0,0), opid=opid)
background.set_scroll(state=-1)
background_tate = RtkParallaxBg(name='Background_Tate', image='background_tate.bmp', type='h', position=(0, 0), opid=opid)
background_tate.set_scroll(state=-1)
elif bg_type == 'parallax_right':
background = RtkParallaxBg(name='Background', image='background.bmp', type='h', position=(0,0), opid=opid)
background.set_scroll(state=1)
background_tate = RtkParallaxBg(name='Background_Tate', image='background_tate.bmp', type='h', position=(0, 0), opid=opid)
background_tate.set_scroll(state=1)
elif bg_type == 'parallax_up':
background = RtkParallaxBg(name='Background', image='background.bmp', type='v', position=(0,0), opid=opid)
background.set_scroll(state=-1)
background_tate = RtkParallaxBg(name='Background_Tate', image='background_tate.bmp', type='v', position=(0, 0), opid=opid)
background_tate.set_scroll(state=-1)
elif bg_type == 'parallax_down':
background = RtkParallaxBg(name='Background', image='background.bmp', type='v', position=(0,0), opid=opid)
background.set_scroll(state=1)
background_tate = RtkParallaxBg(name='Background_Tate', image='background_tate.bmp', type='v', position=(0, 0), opid=opid)
background_tate.set_scroll(state=1)
else:
logging.error('Error loading background. %s type is not valid. Falling back on RtkRect', bg_type)
background = RtkRect(name='Background', position=(0,0), w=scr_w, h=scr_h, color=d_blue, opid=opid)
background_tate = RtkRect(name='Background_Tate', position=(0,0), w=scr_h, h=scr_w, color=d_blue, opid=opid)
except Exception as error:
logging.error('Error loading background. %s', error)
background = RtkRect(name='Background', position=(0,0), w=scr_w, h=scr_h, color=d_blue, opid=opid)
background_tate = RtkRect(name='Background_Tate', position=(0,0), w=scr_h, h=scr_w, color=d_blue, opid=opid)
background._layer = 0
background_tate._layer = 0
# Create default background container
if not is_refresh:
container_bg = ContainerMgr.create(name='Background', opid=opid)
ContainerMgr.append(parent=container_bg, child=background, opid=opid)
ContainerMgr.append(parent=container_bg, child=background_tate, opid=opid)
def set_screen_mode(is_tate):
if is_tate:
background.deactivate()
background_tate.activate()
transition.deactivate()
transition_tate.activate()
if fg_display:
foreground.deactivate()
foreground_tate.activate()
set_custom_sprites_rotation(is_tate)
error_msg.set_rotation(is_tate)
user_msg.set_rotation(is_tate)
popup_msg.set_rotation(is_tate)
notif_msg.set_rotation(is_tate)
else:
background.activate()
background_tate.deactivate()
transition.activate()
transition_tate.deactivate()
if fg_display:
foreground.activate()
foreground_tate.deactivate()
set_custom_sprites_rotation(is_tate)
error_msg.set_rotation(is_tate)
user_msg.set_rotation(is_tate)
popup_msg.set_rotation(is_tate)
notif_msg.set_rotation(is_tate)
def draw_background(time_step):
global err_draw_bg
try:
if bg_type == 'ani_gif':
background_tate.animate(time_step)
background.animate(time_step)
elif 'scroll' in bg_type or 'parallax' in bg_type:
background_tate.scroll(bg_speed, time_step)
background.scroll(bg_speed, time_step)
except Exception as error:
if not err_draw_bg:
logging.error('Error drawing background. %s', error)
err_draw_bg = True
def load_foreground(is_refresh=False):
global foreground, foreground_tate
global container_fg
global err_draw_fg
err_draw_fg = False
opid=get_random_id()
if is_refresh:
try:
cont_fg = ContainerMgr.containers['Foreground']
for widget in cont_fg.widgets:
if widget.name in ('Foreground','Foreground_Tate'):
cont_fg.remove(widget=widget,opid=opid)
except:
container_fg = ContainerMgr.create(name='Foreground', opid=opid)
try:
if fg_display:
foreground = RtkSprite(name='Foreground', image='foreground.bmp', position=(0,0), colorkey=color_key, opid=opid)
foreground_tate = RtkSprite(name='Foreground_Tate', image='foreground_tate.bmp', position=(0,0), colorkey=color_key, opid=opid)
if fg_sent_back:
foreground._layer = 1
foreground_tate._layer = 1
else:
foreground._layer = 3
foreground_tate._layer = 3
# Create default foreground container
if not is_refresh:
container_fg = ContainerMgr.create(name='Foreground', opid=opid)
ContainerMgr.append(parent=container_fg, child=foreground, opid=opid)
ContainerMgr.append(parent=container_fg, child=foreground_tate, opid=opid)
else:
logging.debug('Foreground inactive')
except Exception as error:
logging.error('Error loading foreground. %s', error)
def load_custom_sprites(is_refresh=False):
global cust_sprites
if is_refresh:
try:
opid=get_random_id()
cont_bg = ContainerMgr.containers['Background']
for sprite in cust_sprites:
for widget in cont_bg.widgets:
if widget.name == sprite.name:
cont_bg.remove(widget=widget,opid=opid)
sprite.destroy(opid=opid)
cust_sprites = []
except:
pass
if has_custom_sprites:
global err_draw_cust_sprites
err_draw_cust_sprites = False
cust_sprites = []
try:
names = cust_sprt_name.replace(' ','').split(',')
types = cust_sprt_type.replace(' ','').split(',')
positions = cust_sprt_position
angles = cust_sprt_angle
num_frames = cust_sprt_num_frames
ani_rev_cycles = cust_sprt_ani_rev_cycle.replace(' ','').split(',')
wobbles = cust_sprt_wobble.replace(' ','').split(',')
for i, name in enumerate(names):
position = positions[i]
angle = angles[i]
num_frms = num_frames[i]
ani_rev_cycle = parse_val(ani_rev_cycles[i])
wobble = wobbles[i]
if types[i] == 'RtkSprite':
sprite = RtkSprite(name=name, image=name+'.bmp', position=position, colorkey=color_key)
sprite._layer = 0
cust_sprites.append(sprite)
elif types[i] == 'RtkAniSprite':
sprite = RtkAniSprite(name=name, image=name+'.bmp', angle=angle, num_frames=num_frms, position=position, colorkey=color_key, rev_cycle=ani_rev_cycle)
sprite._layer = 0
cust_sprites.append(sprite)
if wobble:
cust_sprites[i].set_wobble(state=1)
# Add custom sprites to background container
ContainerMgr.append(parent=container_bg, child=cust_sprites)
except Exception as error:
logging.error('Error loading custom sprites. %s', error)
def set_custom_sprites_rotation(is_tate):
if has_custom_sprites:
if is_tate:
positions = cust_sprt_position_tate
else:
positions = cust_sprt_position
for i, sprite in enumerate(cust_sprites):
position = positions[i]
sprite.set_position(position)
sprite.start_pos = position
def draw_custom_sprites(time_step, is_tate=False):
if has_custom_sprites:
global err_draw_cust_sprites
try:
wobbles = cust_sprt_wobble.replace(' ','').split(',')
wobble_speeds = cust_sprt_wobble_speed
wobble_limits = cust_sprt_wobble_limit
any_speeds = cust_sprt_any_speed
bounces = cust_sprt_bounce.replace(' ','').split(',')
bounce_speeds = cust_sprt_bounce_speed
for i, sprite in enumerate(cust_sprites):
wobble = wobbles[i]
wobble_speed = wobble_speeds[i]
wobble_limit = wobble_limits[i]
any_speed = any_speeds[i]
bounce = bounces[i]
bounce_speed = bounce_speeds[i]
if sprite.wobble_state !=0:
sprite.wobble(mode=wobble, speed=wobble_speed, limit=wobble_limit, time_step=time_step)
if type(sprite).__name__ == 'RtkAniSprite':
sprite.animate(speed=any_speed, time_step=time_step)
if bounce == 'true':
sprite.bounce(speed=bounce_speed, time_step=time_step, is_tate=is_tate)
except Exception as error:
if not err_draw_cust_sprites:
logging.error('Error drawing custom sprites. %s', error)
err_draw_cust_sprites = True
def render():
try:
global screen, screen_tate
if cfg_ui_rotation == 'rotate_ccw':
all_sprites.draw(screen_tate)
scr_tate = pygame.transform.rotate(screen_tate, 90)
screen.blit(scr_tate, (0, 0))
elif cfg_ui_rotation == 'rotate_cw':
all_sprites.draw(screen_tate)
scr_tate = pygame.transform.rotate(screen_tate, 270)
screen.blit(scr_tate, (0, 0))
elif cfg_ui_rotation == 'rotate_full':
all_sprites.draw(screen)
scr = pygame.transform.rotate(screen, 180)
screen.blit(scr, (0, 0))
else:
all_sprites.draw(screen)
pygame.display.update() # Removed rects to allow proper rotation
clock.tick(fps) # Removing the framerate makes vsync adjust to the same monitor freq
except Exception as error:
logging.error('Error drawing custom sprites. %s', error)
''' Configuration Files '''
def load_app_cfg():
global main_dir, dat_dir, capture_dir
global cfg_file, trans_file
# Directories
main_dir = os.path.split(os.path.abspath(__file__))[0]
dat_dir = os.path.join(main_dir, 'data')
capture_dir = os.path.join(main_dir, 'captures')
# Files
cfg_file = os.path.join(main_dir, 'config.ini')
trans_file = os.path.join(dat_dir, 'translations.dat')
# Inilialize logging
logging.config.fileConfig(cfg_file)
logging.debug('*** Starting Program ***')
# Load configuration file
load_cfg_file()
def load_cfg_file():
# Open config file
config = configparser.RawConfigParser()
config.read(cfg_file)
# Read configuration
for section in config.sections():
for (option, value) in config.items(section):
if section == 'cfg':
if option == 'theme':
globals()[section + '_' + option] = str(value)
else:
globals()[section + '_' + option] = parse_val(value)
else:
globals()[section + '_' + option] = value
logging.debug('Program configuration loaded')
def save_cfg_file():
# Open config file
configr = configparser.RawConfigParser()
configr.read(cfg_file)
# Create new configuration
configw = configparser.RawConfigParser()
# Set configuration values
for section in configr.sections():
configw.add_section(section)
for (option, value) in configr.items(section):
try:
configw.set(section, option, globals()[section + '_' + option])
except:
configw.set(section, option, value)
# Write configuration to file
with open(cfg_file, 'w', encoding='utf-8') as configfile:
configw.write(configfile)
logging.debug('Program configuration saved')
def load_theme_cfg():
global themes_dir, theme_dir, img_dir, snd_dir, music_dir, font_dir, cfg_theme, cfg_playlist
global fnt_title_file, fnt_title_dat_file, fnt_list_file, fnt_list_dat_file, fnt_info_file, fnt_info_dat_file, \
fnt_helper_file, fnt_helper_dat_file, theme_cfg_file
global has_custom_sprites, title_font_map, title_char_width, title_char_height, list_font_map, list_char_width, list_char_height, \
info_font_map, info_char_width, info_char_height, helper_font_map, helper_char_width, helper_char_height
# Directories
themes_dir = os.path.join(main_dir, 'themes')
theme_dir = os.path.join(themes_dir, cfg_theme)
if not (os.path.exists(theme_dir) and os.path.isdir(theme_dir)):
cfg_theme = cfg_default_theme
theme_dir = os.path.join(themes_dir, cfg_theme)
cfg_playlist = cfg_theme
img_dir = os.path.join(theme_dir, 'images')
snd_dir = os.path.join(theme_dir, 'sounds')
music_dir = os.path.join(theme_dir, 'music')
font_dir = os.path.join(theme_dir, 'fonts')
# Files
fnt_title_file = os.path.join(font_dir, 'title.bmp')
fnt_title_dat_file = os.path.join(font_dir, 'title.dat')
fnt_list_file = os.path.join(font_dir, 'list.bmp')
fnt_list_dat_file = os.path.join(font_dir, 'list.dat')
fnt_info_file = os.path.join(font_dir, 'info.bmp')
fnt_info_dat_file = os.path.join(font_dir, 'info.dat')
fnt_helper_file = os.path.join(font_dir, 'helper.bmp')
fnt_helper_dat_file = os.path.join(font_dir, 'helper.dat')
theme_cfg_file = os.path.join(theme_dir, 'theme.ini')
# Load font data
title_font_map, title_char_width, title_char_height = load_font_map(fnt_title_dat_file)
list_font_map, list_char_width, list_char_height = load_font_map(fnt_list_dat_file)
info_font_map, info_char_width, info_char_height = load_font_map(fnt_info_dat_file)
helper_font_map, helper_char_width, helper_char_height = load_font_map(fnt_helper_dat_file)
# Open config file
config = configparser.RawConfigParser()
config.read(theme_cfg_file)
# Read configuration
has_custom_sprites = False
for section in config.sections():
for (option, value) in config.items(section):
if section == 'cust_sprt':
has_custom_sprites = True
if section == 'pal':
globals()[option] = parse_val(value)
else:
globals()[section + '_' + option] = parse_val(value)
if has_custom_sprites:
logging.debug('Custom sprites found')
logging.debug('Theme configuration loaded')
''' Load config '''
load_app_cfg()
load_theme_cfg()
''' RTK Classes '''
class RtkEvent:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class RtkStepTimer:
def __init__(self):
self.timer()
def timer(self):
# The clock time when the timer started
self.start_ticks = 0
# The ticks stored when the timer was paused
self.paused_ticks = 0
# The timer status
self.paused = False
self.started = False
def start(self):
# Start the timer
self.started = True
# Unpause the timer
self.paused = False
# Get the current clock time
self.start_ticks = pygame.time.get_ticks()
self.paused_ticks = 0
def stop(self):
# Stop the timer
self.started = False
# Unpause the timer
self.paused = False
# Clear tick variables
self.start_ticks = 0
self.paused_ticks = 0
def pause(self):
# If the timer is running and isn't already paused
if self.started and not self.paused:
# Pause the timer
self.paused = True
# Calculate the paused ticks
self.paused_ticks = pygame.time.get_ticks() - self.start_ticks
self.start_ticks = 0
def unpause(self):
# If the timer is running and paused
if self.started and self.paused:
# Unpause the timer
self.paused = False
# Reset the starting ticks
self.start_ticks = pygame.time.get_ticks() - self.paused_ticks
# Reset the paused ticks
self.paused_ticks = 0
def get_ticks(self):
# The actual timer time
time = 0
# If the timer is running
if self.started:
# If the timer is paused
if self.paused:
# Return the number of ticks when the timer was paused
time = self.paused_ticks
else:
# Return the current time minus the start time
time = pygame.time.get_ticks() - self.start_ticks
return time
def is_started(self):
return self.started
def is_paused(self):
return self.paused and self.started
class RtkImage(pygame.sprite.DirtySprite):
def __init__(self, name, image, is_active=True, position=(0,0), colorkey=None, opid=get_random_id()):
pygame.sprite.DirtySprite.__init__(self)
self.name = name
logging.debug('OpID %s, Created %s %s', opid, type(self).__name__, self.name)
if is_active:
self.activate()
else:
self.deactivate()
self.parent = None
self.is_sprite = True
self.position = position # This is the current position
self.__set_surface_size()
self.__load_image(image, colorkey)
self.set_position(self.position)
self.start_pos = self.position # This is the used for reseting the position
self._layer = 2
self.draw()
def set_parent(self, par_obj):
self.parent = par_obj
def __set_surface_size(self):
screen = get_display_inf()
self.screen_w = screen.current_w
self.screen_h = screen.current_h
def __load_image(self, image, colorkey):
self.fallback_image, self.fallback_rect = load_rect(w=scr_w, h=scr_h, color=color_key, colorkey=colorkey)
try:
self.image, self.rect = load_image(image=image, colorkey=colorkey)
except:
self.image = self.fallback_image
self.rect = self.fallback_rect
def change_image(self, image, colorkey=None):
try:
self.image, self.rect = load_image(image=image, colorkey=colorkey)
img_exists = True
except:
self.image = self.fallback_image
self.rect = self.fallback_rect
img_exists = False
self.set_position(position=self.start_pos)
return img_exists
def rotate(self, angle):
self.image = pygame.transform.rotate(self.image, angle)
self.rect = self.image.get_rect()
def set_position(self, position, use_center=False, is_tate=False):
x, y = position
if x == 'center':
if is_tate:
x = self.screen_h / 2
else:
x = self.screen_w / 2
self.rect.centerx = x
x = self.rect.left
else:
if use_center:
self.rect.centerx = x
else:
self.rect.left = x
if y == 'center':
if is_tate:
y = self.screen_w / 2
else:
y = self.screen_h / 2
self.rect.centery = y
y = self.rect.top
else:
if use_center:
self.rect.centery = y
else:
self.rect.top = y
self.position = (x, y)
self.draw()
def draw(self):
self.dirty = 1
def show(self):
self.visible = 1
self.dirty = 1
def hide(self):
self.visible = 0
self.dirty = 1
def destroy(self, opid):
logging.debug('OpID %s, Removing %s widget', opid, self.name)
self.kill()
def activate(self):
self.is_active = True
self.show()
def deactivate(self):
self.is_active = False
self.hide()
class RtkSprite(pygame.sprite.DirtySprite):
def __init__(self, name, image=None, parent=None, is_active=True, is_tate=False, flip=False, angle=0, position=(0,0), align='left', colorkey=None, opid=get_random_id()):
pygame.sprite.DirtySprite.__init__(self)
self.name = name
logging.debug('OpID %s, Created %s %s', opid, type(self).__name__, self.name)
self.parent = parent
if is_active:
self.activate()
else:
self.deactivate()
self.is_sprite = True
self.position = position # This is the current position
self.align = align
self.wobble_state = 0
self.wobble_y_counter = None
self.wobble_x_counter = None
self.wobble_elapsed_time = 0
self.magnify_state = 0
self.magnify_counter = 0
self.magnify_elapsed_time = 0
self.ani_elapsed_time = 0
self.alpha = 255
self.alpha_state = 0
self.__set_surface_size()
self.set_angle(angle)
if image:
self.__load_image(image, colorkey)
self.set_position(position=position,is_tate=is_tate)
if flip:
self.__flip()
self.start_pos = self.position # This is the used for reseting the position
self._layer = 2
self.draw()
def __del__(self):
#logging.debug('Destroyed %s with id %s', type(self).__name__, self.name)
pass
def set_parent(self, par_obj):
self.parent = par_obj
def __load_image(self, image, colorkey):
self.image, self.rect = load_image(image=image, colorkey=colorkey)
self.original_img = self.image.copy()
def __set_surface_size(self):
screen = get_display_inf()
self.screen_w = screen.current_w
self.screen_h = screen.current_h
def change_image(self, image, colorkey=None):
self.image, self.rect = load_image(image=image, colorkey=colorkey)
def __flip(self):
self.image = pygame.transform.flip(self.image, True, False)
def change_color(self, color, repcolor):
# Apply to main image
pixel_array = pygame.PixelArray(self.image)
pixel_array.replace(color, repcolor)
pixel_array.close()
# Apply to original image
pixel_array = pygame.PixelArray(self.original_img)
pixel_array.replace(color, repcolor)
pixel_array.close()
self.dirty = 1
def rotate(self, angle):
self.image = pygame.transform.rotate(self.image, angle)
self.rect = self.image.get_rect()
def set_wobble(self, state):
self.wobble_state = state # -1 left/up 0 stop 1 rigth/down
def set_mangnify(self, state):
self.magnify_state = state # -1 inactive 0 normal 1 magnify
if state == 0: # Restore image zoom
self.magnify_counter = 0
self.image = self.original_img.copy()
self.rect = self.image.get_rect()
self.set_position(position=self.start_pos)
def handle(self, event):
handler = f'handle_{event}'
if hasattr(self, handler):
method = getattr(self, handler)
method(event)
elif self.parent is not None:
self.parent.handle(event)
elif hasattr(self, 'handle_default'):
self.handle_default(event)
def handle_default(self, event):
logging.debug('%s, handle_default %s', self.name, event)
def set_position(self, position, is_tate=False):
x, y = position
# X
if x == 'center':
if is_tate:
x = self.screen_h / 2
else:
x = self.screen_w / 2
self.rect.centerx = x
x = self.rect.left
else:
if self.align == 'right':
self.rect.right = x
x = self.rect.left
self.rect.left = x
# Y
if y == 'center':
if is_tate:
y = self.screen_w / 2
else:
y = self.screen_h / 2
self.rect.centery = y
y = self.rect.top
else:
self.rect.top = y
self.position = (x, y)
self.draw()
def move(self, displacement):
# Change current position
x = self.position[0] + displacement[0]
y = self.position[1] + displacement[1]
self.set_position((x, y))
# Change start position
x = self.start_pos[0] + displacement[0]
y = self.start_pos[1] + displacement[1]
self.start_pos = (x, y)
def set_angle(self, angle):
# Normalize angle
angle = radians(angle)
circle_turn = radians(360)
normalized_angle = angle % circle_turn # Remainder of any angle by a circle turn removes all extra turns
self.angle = normalized_angle
def __get_quadrant(self):
angle = round(degrees(self.angle))
quadrant = 1
if angle >= 0 and angle < 90:
quadrant = 1
elif angle >= 90 and angle < 180:
quadrant = 2
elif angle >= 180 and angle < 270:
quadrant = 3
elif angle >= 270 and angle <= 360:
quadrant = 4
return quadrant
def advance(self, speed, time_step):
x, y = self.position
distance = speed * (time_step/1000)
x += cos(self.angle) * distance
y -= sin(self.angle) * distance
self.set_position((x, y))
def fade(self, speed, time_step):
if self.alpha_state == 0:
self.alpha += speed * (time_step/1000)
elif self.alpha_state == 1:
self.alpha -= speed * (time_step/1000)
if self.alpha_state == 0 and self.alpha >= 255:
self.alpha_state = 1
elif self.alpha_state == 1 and self.alpha <= 0:
self.alpha_state = 0
self.image.set_alpha(self.alpha)
def set_alpha(self, alpha):
self.alpha = alpha
self.image.set_alpha(self.alpha)
def bounce(self, speed, time_step, is_tate=False):
quadrant = self.__get_quadrant()
new_angle = None
x = None
y = None
# Set simple collider point based on angle quadrant
if quadrant == 1:
x, y = self.rect.topright
elif quadrant == 2:
x, y = self.rect.topleft
elif quadrant == 3:
x, y = self.rect.bottomleft
elif quadrant == 4:
x, y = self.rect.bottomright
# Calculate new trayectory
if x != None and y != None:
if is_tate:
screen_w = self.screen_h
screen_h = self.screen_w
else:
screen_w = self.screen_w
screen_h = self.screen_h
# The angle of reflection is equal to the angle of incidence
if x > screen_w or x < 0:
new_angle = (180 - degrees(self.angle))
elif y > screen_h or y < 0:
new_angle = (360 - degrees(self.angle))
if new_angle == 0:
new_angle = 360
if new_angle:
self.set_angle(angle=new_angle)
#logging.debug('>>> quadrant %s, new_angle %s, pos %s, rect_pos %s',quadrant, new_angle, self.position, (x,y))
self.advance(speed, time_step)
def wobble(self, mode, speed, limit, time_step):
if mode == 'horizontal':
self.__wobble_h(speed, limit, time_step)
elif mode == 'vertical':
self.__wobble_v(speed, limit, time_step)
def __wobble_v(self, speed, limit, time_step):
distance = speed * (time_step/1000)
if not self.wobble_y_counter:
self.wobble_y_counter = abs(limit)
x = self.position[0]
y = self.position[1] + distance * self.wobble_state
if self.wobble_y_counter <= 0:
self.wobble_y_counter = abs(limit*2)
self.wobble_state *= -1
# The below code corrects positions caused by python micro cuts
if self.position[1] < self.start_pos[1] - limit:
y = self.start_pos[1] - limit
elif self.position[1] > self.start_pos[1] + limit:
y = self.start_pos[1] + limit
self.wobble_y_counter -= distance