-
Notifications
You must be signed in to change notification settings - Fork 0
/
game_screens.py
2770 lines (2332 loc) · 105 KB
/
game_screens.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from tkinter import Canvas, Frame, Button, Label, Entry, Toplevel ,Tk, messagebox, StringVar, Scale, OptionMenu, END
from random import choice
from game_idles import *
from variable import Variable, demo_variable
from helper import deep_copy, darken_hex_color
class Game_screen:
"""
Class to manage the game screen, including navigation setup,
game canvas setup, updating game elements, and adding/removing
from the master widget.
Attributes:
var (variable): An object containing game variables.
MASTER (Tk): The parent Tkinter window.
NEVIGATION_CANVAS (Canvas): The canvas for navigation elements.
GAME_CANVAS (Canvas): The canvas for game elements.
SNAKE (Snake): The snake object.
FOOD (Food): The food object.
HEART (Heart): The heart object.
MENU_OPTION (Text): The menu option text.
SCORE_TEXT (Text): The score text.
_game_bord_height (int): Height of the game board.
_nevigation_height (int): Height of the navigation canvas.
Methods:
__init__(Master, var): Initializes the game screen.
adjust_window_size(): Adjusts window size based on game and navigation heights.
nevigation_setup(): Sets up the navigation canvas with heart, score text, and menu option.
game_canvas_setup(): Sets up the game canvas with snake and food.
update_things(**kwargs): Updates game elements based on provided keyword arguments.
add_to_Master(): Packs the navigation and game canvases.
remove_to_Master(): Removes navigation and game canvases from master widget.
"""
def __init__(self,Master:Tk, var:Variable) -> None:
"""
Initialize the game screen.
with main game canvas and nevigation panel
and sneck , food in hevigation heart score board,
and menu option
Args:
Master (Tk): The parent Tkinter window.
var (variable): An object containing game variables.
Note:
1. this method directly interect with variable method
"""
self.var = var
self.root = Master
self.MASTER = Frame(self.root)
self.var1 = None
self.demo = False
self.NEVIGATION_CANVAS = None
self.GAME_CANVAS = None
self.SNAKE = None
self.FOOD = None
self.HEART = None
self.COIN = None
self.HEART_NEW = None
self.MENU_OPTION = None
self.SCORE_TEXT = None
self.inisialize()
def inisialize(self):
self.nevigation_setup()
self.game_canvas_setup()
def nevigation_setup(self) -> None:
"""
This method sets up the navigation canvas with essential elements such as a heart icon
representing the player's remaining lives, a score text displaying the current score,
and a menu option for accessing game options or pausing the game.
"""
var = self.var if not self.demo else self.var1
self.NEVIGATION_CANVAS = Canvas(
master = self.MASTER
)
self.HEART_NEW = Heart_NEV(
canvas = self.NEVIGATION_CANVAS,
color = var.HEART_COLOR,
initial_heart = var.INISISAL_HEART,
limit = var.HEART_LIMIT
)
self.SCORE_TEXT = self.NEVIGATION_CANVAS.create_text(
0 , 0 ,
text = f"Score: 0",
)
self.MENU_OPTION = self.NEVIGATION_CANVAS.create_text(
0 , 0 ,
text = "Menu",
)
self.NEVIGATION_CANVAS.pack()
def game_canvas_setup(self) -> None:
"""
This method sets up the game canvas with the snake and food objects.
It creates a canvas widget with the specified background color, width,
and height. Then, it initializes the snake and food objects on the canvas
using the provided game variables.
"""
var = self.var if not self.demo else self.var1
self.GAME_CANVAS = Canvas(
master = self.MASTER,
bg = var.CANVAS_COLOR
)
self.SNAKE = Snake(
canvas = self.GAME_CANVAS,
coordinates = var.SNAKE_CORDINATES,
box_size = var.game_box_size,
lenght = var.SNAKE_LENGHT,
color = var.SNAKE_COLOR
)
self.FOOD = Food(
canvas = self.GAME_CANVAS,
box_size = var.game_box_size,
color = var.FOOD_COLOR,
)
self.HEART = Heart(
canvas = self.GAME_CANVAS,
box_size = var.game_box_size,
color = var.HEART_COLOR
)
self.COIN = Coin(
canvas = self.GAME_CANVAS,
box_size = var.game_box_size,
color = var.COIN_COLOR
)
self.HEART.delete_all()
self.COIN.delete_all()
self.GAME_CANVAS.pack()
def adjust_window_size(self) -> None:
"""
Adjust the window size based on game height and navigation heights.
Note:
The navigation height is calculated as one-eighth of the game height,
but if the calculated height is less than or equal to the size of game
boxes, it defaults to the size of game boxes.
Attributes created:
_nevigation_height (int): The height of the navigation canvas.
_game_bord_height (int): The height of the game board canvas.
"""
var = self.var if not self.demo else self.var1
#game_variables
self.game_height = var.game_height
self.game_width = var.game_width
self._game_bord_height = None
self._nevigation_height = None
nevigation_h = self.game_height // 8
nevigation_height = nevigation_h // var.game_box_size
if not bool(nevigation_height):
self._nevigation_height = nevigation_h
else:
self._nevigation_height = var.game_box_size
self._game_bord_height = self.game_height - self._nevigation_height
def UPDATE(self) -> None:
"""
this method update all elemets posstion and color acording to new one
"""
self.adjust_window_size()
var = self.var if not self.demo else self.var1
#updating nevigation and its itemes================
braking_into_4 = self._nevigation_height // 4
if self.NEVIGATION_CANVAS: self.NEVIGATION_CANVAS.config(
bg = var.NEV_COLOR,
width = self.game_width,
height = self._nevigation_height
)
if self.HEART_NEW:
self.HEART_NEW.update_color(var.HEART_COLOR)
self.HEART_NEW.update_size()
self.HEART_NEW.initial_heart = var.INISISAL_HEART
self.HEART_NEW.limit = var.HEART_LIMIT
if self.SCORE_TEXT and self.MENU_OPTION:
#tuple1 contain text id and its x cords
tuple1 = ((self.SCORE_TEXT,self.game_width // 2), (self.MENU_OPTION,braking_into_4 * 4))
for text_id , xcords in tuple1:
# updating color and size
self.NEVIGATION_CANVAS.itemconfig(
text_id,
font = ("Arial",braking_into_4 * 2,"bold"),
fill = var.TEXT_COLOR
)
# updating postion.
self.NEVIGATION_CANVAS.coords(
text_id,
xcords,#x
braking_into_4 * 2#y
)
#updating canvas and its itemes===================
if self.GAME_CANVAS: self.GAME_CANVAS.config(
bg = var.CANVAS_COLOR,
width = self.game_width,
height = self._game_bord_height
)
if self.SNAKE:
self.SNAKE.update_color(var.SNAKE_COLOR)
self.SNAKE.lenght = var.SNAKE_LENGHT
if self.FOOD:
self.FOOD.update_color(var.FOOD_COLOR)
self.FOOD._calculate_dimension()
if self.HEART:
self.HEART.update_color(var.HEART_COLOR)
self.HEART._calculate_dimension()
if self.COIN:
self.COIN.update_color(var.COIN_COLOR)
self.COIN._calculate_dimension()
def update_text(self, color:str) -> None:
tuple1 = (self.SCORE_TEXT, self.MENU_OPTION)
if self.SCORE_TEXT and self.MENU_OPTION:
for text_id in tuple1:
self.NEVIGATION_CANVAS.itemconfig(
text_id,
fill = color
)
def update_things(self,**kwargs) -> None:
"""
Update game elements based on provided keyword arguments.
Args:
**kwargs: Keyword arguments to update game elements. Available args:
- score: Score to be updated.
"""
if kwargs.get('score',None) is not None:
self.NEVIGATION_CANVAS.itemconfig(
self.SCORE_TEXT,text=f"Score: {kwargs['score']}"
)
print("updated ",kwargs['score'])
else:
print("error : 0012, cant update text of score !")
def demo_screen_var_update(self, **kwargs) -> demo_variable:
"""
Update screen variables with provided keyword arguments and optionally initialize the screen.
Args:
initialize (bool, optional): Whether to call the SET_UP method after updating variables. Defaults to False.
**kwargs: Arbitrary keyword arguments for updating screen variables. Expected keys:\
game_height , game_width , game_box_size , HEART_LIMIT , INISISAL_HEART
HEART_COLOR, NEV_COLOR , TEXT_COLOR , CANVAS_COLOR , COIN_COLOR
FOOD_COLOR , SNAKE_COLOR , SNAKE_CORDINATES , SNAKE_LENGHT
Returns:
tuple: _description_
"""
var = {
"game_height" : self.var.game_height,
"game_width" : self.var.game_width,
"game_box_size": self.var.game_box_size,
"HEART_LIMIT":self.var.HEART_LIMIT,
"INISISAL_HEART":self.var.INISISAL_HEART,
"HEART_COLOR":self.var.HEART_COLOR,
"NEV_COLOR": self.var.NEV_COLOR,
"TEXT_COLOR":self.var.TEXT_COLOR,
"CANVAS_COLOR":self.var.CANVAS_COLOR,
"FOOD_COLOR":self.var.FOOD_COLOR,
"COIN_COLOR":self.var.COIN_COLOR,
"SNAKE_COLOR":self.var.SNAKE_COLOR,
"SNAKE_LENGHT":self.var.SNAKE_LENGHT,
"SNAKE_CORDINATES":self.var.SNAKE_CORDINATES,
}
var.update(kwargs)
self.demo = True
if self.var1 is None:
self.var1 = demo_variable(var)
else:
self.var1.update_with_dict(var)
self.UPDATE()
return var
def add_to_Master(self) -> None:
"""
Pack the navigation and game canvases and add it to master
"""
self.MASTER.pack()
def remove_to_Master(self)-> None:
"""
remove the navigation and game canvases. from master
"""
self.MASTER.pack_forget()
class inisial_screens:
"""
A class representing an initial screen setup for a game.
This class provides methods for setting up the initial screen of a game, including adding snakes, food items, starting animations, and managing animations.
Attributes:
master (Tk | Frame): The master widget where the initial screen will be placed.
background_color (str): The background color of the game screen.
game_width (int): The width of the game screen.
game_height (int): The height of the game screen.
box_size (int): The size of each box or unit in the game grid.
speed (int): The speed of animations in milliseconds.
child_window (tkinter.Canvas): The canvas widget representing the game screen.
food (Food): The food item on the game screen.
heart (Heart): The heart item on the game screen.
coin (Coin): The coin item on the game screen.
snakes (list): A list containing snake objects on the game screen.
Windows_list (list): A list of additional widgets (windows) added to the game screen.
Header (list): A list containing header widgets placed at the top of the game screen.
footer (list): A list containing footer widgets placed at the bottom of the game screen.
methods (list): A list to store methods for deferred execution.
color_list (list): A list of predefined colors for game elements.
Methods:
__init__: Initializes the initial screen with provided parameters.
add_snakes: Adds a snake to the game screen.
add_food: Adds a food item to the game screen.
add_heart: Adds a heart item to the game screen.
add_coin: Adds a coin item to the game screen.
add_windows: Adds window widgets to the game screen.
add_header: Adds header widgets to the game screen.
add_footer: Adds footer widgets to the game screen.
update_window_size: Updates the positions of all windows on the game screen.
update_header: Updates the positions of header elements on the game screen.
update_footer: Updates the positions of footer elements on the game screen.
update_nessassaery: Appends methods to self.methods and optionally executes them.
HomeScreen_HeaderFooter_modle1_inisalization: Initializes header and footer with labels and a coin widget.
start_animation: Starts the animation loop for moving snakes and updating the game state.
stop_animation: Stops the animation loop.
update_everything: Updates various attributes, elements, and widgets based on provided variables.
add_to_master: Adds the game screen to the master widget.
remove_from_master: Removes the game screen from the master widget.
Note:
Note: If you add any more elements to the canvas that are not part of the game_screens
method and their size and color can be updated, create a method to update them and append
it to the self.methods list or through the self.update_message method.
"""
def __init__(self, master:Tk|Frame, background_color:str, game_width:int, game_height:int, box_size:int, pack:bool = True ) -> None:
"""
Initialize the initial screen of the game.
Args:
master (Tk | Frame): The master widget where the initial screen will be placed.
background_color (str): The background color of the game screen.
game_width (int): The width of the game screen.
game_height (int): The height of the game screen.
box_size (int): The size of each box or unit in the game grid.
pack (bool): Whether to automatically pack the canvas widget (default is True).
"""
self.master = master
self.background_color = background_color
self.game_width = game_width
self.game_height = game_height
self.box_size = box_size
#inisalizing child window
self.child_window = Canvas(
master = self.master,
bg = self.background_color,
height = self.game_height,
width = self.game_width
)
#elements of the game_screen :0
self.food = None
self.heart = None
self.coin = None
self.snakes = []
self.Windows_list = []
self.Header = []
self.footer = []
self.methods = []
self.color_list = [
"#FFA500", "#800080", "#00FFFF", "#FFD700", "#00FF00",
"#0000FF", "#FFFF00", "#FF0000", "#FFC0CB"
]
#arttibutes used for game_screen elements
self.random_food_color = False
self.random_heart_color = False
self.random_coin_color = False
#important regardin animation
self.speed = None
self.animation_after_ids = None
#header footer and middele button posstion
self._middel_windows = 0
self.header_info = (0,0) #padding x and y
self.footer_info = (0,0) ##padding x and y
#windows ids created id on canvas
self._Windows_ids = []
self._header_ids = [None,None,None]
self._footer_ids = [None,None,None]
if pack:
self.child_window.pack()
def add_food(self, color:str, randome_color=False) -> None:
"""
Add a food item to the game screen.
Args:
color (str): The color of the food item.
random_color (bool): Whether to randomize the color of the food item (default is False).
"""
self.random_food_color = randome_color
self.food=Food(
canvas = self.child_window,
box_size = self.box_size,
color = color,
initialize = True
)
def add_heart(self, color:str, randome_color=False) -> None:
"""
add heart item to the game screen.
Args:
color (str): The color of the heart item.
random_color (bool): Whether to randomize the color of the heart item (default is False).
"""
self.random_heart_color = randome_color
self.heart = Heart(
canvas = self.child_window,
box_size = self.box_size,
color = color,
initialize = True
)
def add_coin(self, color:str, randome_color=False) -> None:
"""
add coin item to the game screen.
Args:
color (str): The color of the coin item
random_color (bool): Whether to randomize the color of the coin item (default is False).
"""
self.random_coin_color = randome_color
self.coin = Coin(
canvas = self.child_window,
box_size = self.box_size,
color = color,
initialize = True
)
def add_snakes(self, color:str, coordinates:list, lenght:int, direction:str) -> None:
"""
Add a snake to the game screen.
Args:
color (str): The color of the snake.
coordinates (list): The initial coordinates of the snake. It should be a list of two integers [x, y],
and both coordinates should be divisible by box_size.
length (int): The length of the snake.
direction (str): The initial direction of the snake ('up', 'down', 'left', 'right').
Note:
The coordinates should be divisible by box_size to ensure proper alignment on the game grid.
"""
# getting the cords in the range not out of game width and height and not less then 0 then * it to get cords
coordinates[0] = min((self.game_height // self.box_size),max(0,coordinates[0]))*self.box_size
coordinates[1] = min((self.game_width // self.box_size),max(0,coordinates[1]))*self.box_size
snake = goofy_Snakes(
master = self.child_window,
box_size = self.box_size,
color = color,
lenght = lenght,
coordinates = coordinates,
inisial_direction = direction
)
self.snakes.append(snake)
def add_windows(self, *args, middle:int = 1 , destroy:bool = True) -> None:
"""
Add window widgets to the game screen.
This method places given widgets (e.g., buttons) on the game screen at a specific
position based on the `middle` parameter. It also handles the removal of previously
added widgets if called multiple times.
Args:
*args: Widgets to be added to the game screen.
middle (int, optional): Determines the vertical offset of the widgets. Defaults to 1.
The value represents how much the widgets should move upwards, with 1
representing one box size.
destroy (bool, optional): Indicates whether to destroy the original widgets when
this method is called again. Defaults to True. If True, the original widget will
be destroyed; otherwise, only the canvas item will be deleted.
Note:
This method should ideally be used only once per object to avoid adding new
widgets and deleting old ones repeatedly.
"""
#destroying all widget if its called again
for _ in range(len(self._Windows_ids)):
window = self._Windows_ids.pop()
self.child_window.delete(window)
if destroy:
window = self.Windows_list.pop()
window.destroy()
self.Windows_list = list(args)
self._middel_windows = middle
# getting the box size in negative or the inisal cords:0
num = (self.box_size - (self.box_size * 2)) * middle
for button in args:
id = self.child_window.create_window(
self.game_width//2, # x value
self.game_height//2+num, # y value
window=button
)
self._Windows_ids.append(id)
num += self.box_size
def add_header(self, header:tuple[int,int,int], pady:int = 10, padx:int = 10, destroy:bool = True) -> None:
"""
Add header widgets to the header section of the game screen.
This method positions up to three widgets in the header section: right side, center, and left side.
The `header` tuple should contain the widget IDs for these positions. If no widget is desired in
a particular position, `None` can be used.
Args:
header (tuple[int, int, int]): A tuple containing the widget IDs for the right side, center, and
left side of the header, respectively. Example: (right_side_id, center_id, left_side_id).
Use `None` for positions where no widget is needed.
pady (int, optional): Padding on the y-axis. Defaults to 10.
padx (int, optional): Padding on the x-axis. Defaults to 10.
destroy (bool, optional): Indicates whether to destroy the original widgets when this method
is called again. Defaults to True. If True, the original widgets will be destroyed.
Note:
This method should ideally be used only once per object to avoid repeatedly adding new
headers and deleting old ones.
"""
# Deleting existing header widgets if the method is called again
for num in range(0,len(self._header_ids)):
if not self._header_ids[num]:
continue
self.child_window.delete(self._header_ids[num])
if destroy:
self.Header[num].destroy()
# Reset header ids and store new header tuple
self.Header = header
self._header_ids = [None, None, None]
self.header_info = (padx,pady)
# Adding widget
if header[0]:# right-side header widget
x = 0 + padx
y = 0 + pady
self._header_ids[0] = self.child_window.create_window(
x, y, window=header[0], anchor="nw"
)
if header[1]: #center header widget
x = (self.game_width // 2 )
y = (header[1].winfo_reqheight() // 2) + pady
self._header_ids[1] = self.child_window.create_window(
x, y, window=header[1], anchor="center"
)
if header[2]: #left-side header widget
x = self.game_width - padx
y = 0 + pady
self._header_ids[2] = self.child_window.create_window(
x, y, window=header[2], anchor="ne"
)
def add_footer(self, footer:tuple, pady:int = 10, padx:int = 10, destroy:bool = True) -> None:
"""
Add footer widgets to the footer section of the game screen.
This method positions up to three widgets in the footer section: right side, center, and left side.
The `footer` tuple should contain the widget IDs for these positions. If no widget is desired in
a particular position, `None` can be used.
Args:
footer (tuple): A tuple containing the widget IDs for the right side, center, and
left side of the footer, respectively. Example: (right_side_id, center_id, left_side_id).
Use `None` for positions where no widget is needed.
pady (int, optional): Padding on the y-axis. Defaults to 10.
padx (int, optional): Padding on the x-axis. Defaults to 10.
destroy (bool, optional): Indicates whether to destroy the original widgets when this method
is called again. Defaults to True. If True, the original widgets will be destroyed.
Note:
This method should ideally be used only once per object to avoid repeatedly adding new
footers and deleting old ones.
"""
# Deleting existing footer widgets if the method is called again
for num in range(0, len(self._footer_ids)):
if not self._footer_ids[num]:
continue
self.child_window.delete(self._footer_ids[num])
if destroy:
self.footer[num].destroy()
# Reset footer ids and store new footer tuple
self.footer = footer
self._footer_ids = [None, None, None]
self.footer_info = (padx,pady)
if footer[0]:
x = 0 + padx
y = self.game_height - pady
self._footer_ids[0] = self.child_window.create_window(
x, y, window=footer[0], anchor="sw"
)
if footer[1]:
x = (self.game_width // 2 )
y = self.game_height - (footer[1].winfo_reqheight() // 2) - pady
self._footer_ids[1] = self.child_window.create_window(
x, y, window=footer[1], anchor="center"
)
if footer[2]:
x = self.game_width - padx
y = self.game_height - pady
self._footer_ids[2] = self.child_window.create_window(
x, y, window=footer[2], anchor="se"
)
def update_window_size(self) -> None:
"""
Update the positions of all windows in the game screen.
This method adjusts the coordinates of each window stored in self._Windows_ids
to be centered horizontally and vertically stacked in the middle of the game screen.
"""
if self._Windows_ids == []:
return None
num = (self.box_size - (self.box_size * 2)) * self._middel_windows
for window in self._Windows_ids:
x = self.game_width // 2
y = self.game_height // 2 + num
self.child_window.coords(window, x , y)
num += self.box_size
def update_header(self) -> None:
"""
Update the positions of header elements on the game screen.
This method adjusts the coordinates of each header element based on its stored ID and position info:
- If self._header_ids[0] exists, it positions it at (0 + self.header_info[0], 0 + self.header_info[1]).
- If self._header_ids[1] exists, it positions it horizontally centered and adjusted vertically based on its height.
- If self._header_ids[2] exists, it positions it at (self.game_width - self.header_info[0], 0 + self.header_info[1]).
"""
if self._header_ids[0]:
x = 0 + self.header_info[0]
y = 0 + self.header_info[1]
self.child_window.coords(self._header_ids[0],x,y)
if self._header_ids[1]:
x = (self.game_width // 2 )
y = (self.Header[1].winfo_reqheight() // 2) + self.header_info[1]
self.child_window.coords(self._header_ids[1],x,y)
if self._header_ids[2]:
x = self.game_width - self.header_info[0]
y = 0 + self.header_info[1]
self.child_window.coords(self._header_ids[2],x,y)
def update_footer(self) -> None:
"""
Update the positions of footer elements on the game screen.
This method adjusts the coordinates of each footer element based on its stored ID and position info:
- If self._footer_ids[0] exists, it positions it at (0 + self.footer_info[0], self.game_height - self.footer_info[1]).
- If self._footer_ids[1] exists, it positions it horizontally centered and adjusted vertically based on its height.
- If self._footer_ids[2] exists, it positions it at (self.game_width - self.footer_info[0], self.game_height - self.footer_info[1]).
"""
if self._footer_ids[0]:
x = 0 + self.footer_info[0]
y = self.game_height - self.footer_info[1]
self.child_window.coords(self._footer_ids[0],x,y)
if self._footer_ids[1]:
x = (self.game_width // 2 )
y = self.game_height - (self.footer[1].winfo_reqheight() // 2) - self.footer_info[1]
self.child_window.coords(self._footer_ids[1],x,y)
if self._header_ids[2]:
x = self.game_width - self.footer_info[0]
y = self.game_height - self.footer_info[1]
self.child_window.coords(self._footer_ids[2],x,y)
def update_nessassaery(self, *args_method, update:bool = False):
"""
Append methods to self.methods and optionally execute them.
Args:
*args_method: Variable length argument list of methods to append to self.methods.
update (bool): If True, execute all methods in self.methods after appending new methods.
"""
for method in args_method:
self.methods.append(method)
if update:
for method in self.methods: method()
def HomeScreen_HeaderFooter_modle1_inisalization(self, var , padx:int = 10, pady:int = 10) -> None:
"""
Initialize the header and footer for the home screen with specified labels and a coin widget.
This method sets up the header with high score and player coin information, and the footer with the version info.
It also initializes a coin widget in the specified position.
Args:
var (object): An object containing necessary attributes for initialization:
- HIGHT_SCORE (int): The high score value to be displayed.
- CANVAS_COLOR (str): Background color for the labels.
- TEXT_COLOR (str): Text color for the labels.
- FONT_STYLE (str): Font style for the labels.
- PLAYERP_COINE (int): The player's coin count to be displayed.
- version (str): The version of the game to be displayed.
- Form_font (str): Font style for the version label.
padx (int, optional): Padding on the x-axis for header and footer. Defaults to 10.
pady (int, optional): Padding on the y-axis for header and footer. Defaults to 10.
Note:
This method utilizes the `add_header_or_footer` method to add widgets to the header and footer sections.
"""
box_size = 20
lable1 = Label(
master = self.child_window,
text = f"High score: {var.HIGHT_SCORE}",
bg = var.CANVAS_COLOR,
fg = var.TEXT_COLOR,
font = (var.FONT_STYLE,int(box_size//1.66)),
relief = "flat"
)
label2 = Label(
master = self.child_window,
text = f": {var.PLAYERP_COINE}",
bg = var.CANVAS_COLOR,
fg = var.TEXT_COLOR,
font = (var.FONT_STYLE,int(box_size//1.66)),
relief = "flat"
)
label3 = Label(
master = self.child_window,
text = f"Version: {var.version}v",
bg = var.CANVAS_COLOR,
fg = var.TEXT_COLOR,
font = (var.Form_font,7),
relief = "flat"
)
self.add_header(header = (lable1,None,label2), padx= padx, pady= pady)
self.add_footer(footer = (None, None, label3), padx= padx, pady= pady)
#cords for coin:
x = self.game_width - label2.winfo_reqwidth() - padx - box_size
y = pady
#inisalizing coin
home_coin = Coin(
canvas = self.child_window,
box_size = box_size,
color = "#ffff00",
initialize = False
)
home_coin._create_coin_shape(coordinates = (x , y))
def update(header1,header2,footer1,var, home_coin,gamewidth,box_size,padx,pady):
header1.config(text = f"High score: {var.HIGHT_SCORE}")
header2.config(text = f": {var.PLAYERP_COINE}")
footer1.config(text = f"Version: {var.version}v")
x = gamewidth - header2.winfo_reqwidth() - padx - box_size - 5
y = 0 + pady
home_coin.update_color(var.COIN_COLOR)
home_coin._move_resize_coin_shape((x,y))
self.update_nessassaery(lambda : update(lable1,label2,label3,var,home_coin,self.game_width,box_size,padx,pady))
def start_animation(self , speed:int) -> None:
"""
Start the animation loop for moving snakes and updating the game state.
This method moves each snake in the game, checks for collisions with
food, heart, or coin, updates their colors if needed, and generates new
items as appropriate. It then schedules the next frame of the animation.
Args:
speed (int): The delay in milliseconds between each animation frame.
Note:
we need to inisalize atlest 1 snake to start the animation if not its return None :)
"""
if len(self.snakes) == 0:
return None
for snake in self.snakes:
snake.move_the_snakes()
snake_cords = snake.snake.snake_coordinates
x , y = snake.coordinates
if bool(self.food) and (x, y )== self.food.coords:
if self.random_food_color:
color = choice(self.color_list)
self.food.update_color(color)
self.food.new_food(snake_cords)
if bool(self.heart) and (x , y) == self.heart.coords:
if self.random_heart_color:
color = choice(self.color_list)
self.heart.update_color(color)
self.heart.new_heart(snake_cords)
if bool(self.coin) and (x , y) == self.coin.coords:
if self.random_coin_color:
color = choice(self.color_list)
self.coin.update_color(color)
self.coin.new_coin(snake_cords)
self.animation_after_ids = self.child_window.after(speed,self.start_animation,speed)
def stop_animation(self) -> None:
"""Stop the animation loop."""
if self.animation_after_ids:
self.child_window.after_cancel(self.animation_after_ids)
def update_everything(self,var:Variable) -> None:
"""
Update various attributes, elements, and widgets based on the provided `var` object.
Args:
var: An object containing variables to update the game screen attributes and elements.
"""
if self.food:
self.food.update_color(var.FOOD_COLOR)
self.food.update_size(var.home_boxsize)
if self.heart:
self.heart.update_color(var.HEART_COLOR)
self.heart.update_size(var.home_boxsize)
if self.coin:
self.coin.update_color(var.COIN_COLOR)
self.coin.update_size(var.home_boxsize)
#updating snake
for snake in self.snakes:
snake.update_size(var.home_boxsize)
#updating canvas and mislanerious
self.background_color = var.CANVAS_COLOR
self.game_height = var.game_height
self.game_width = var.game_width
self.box_size = var.home_boxsize
self.speed = var.home_speed
self.child_window.config(
bg = var.CANVAS_COLOR,
width = var.game_width,
height = var.game_height
)
#updating all window elements:0
for windows in self.Windows_list:
windows.config(bg=var.CANVAS_COLOR,fg=var.TEXT_COLOR)
self.update_window_size()
for window in self.Header:
if window: window.config(bg=var.CANVAS_COLOR,fg=var.TEXT_COLOR)
self.update_header()
for window in self.footer:
if window: window.config(bg=var.CANVAS_COLOR,fg=var.TEXT_COLOR)
self.update_footer()
self.update_nessassaery(update=True)
def add_to_master(self) -> None:
'''add to the master'''
self.child_window.pack()
def remove_from_master(self) -> None:
'''remove window from master'''
self.stop_animation()
self.child_window.pack_forget()
class account_screen:
#fix update_and_size_and_color method for better
#fixing with good calculation...
def __init__(self,var:Variable, master:Frame, root:Tk, change_window:callable ) -> Canvas:
self.master = master
self.height = 0
self.width = 0
self.var = var
self.window = WindowGenerator(root, var)
self.change_method = change_window
self._create_window1()
self._create_window2()
def __change_window_method(self) -> None:
"""
this function helps to confirm user password and also if password
ryt then take them to account setting canvas:0
"""
get_pass = self.window.taking_password_for_verification_window()
if get_pass == self.var._player_acc_info["password"]:
messagebox.showinfo("password matched","password matched now u can modify you account")
self.change_method(self.canvas2)
else:
messagebox.showinfo("wrong password","wrong password u cant modify your account")
def __change_password(self) -> None:
value1, value2 = self.window.change_password_window()
if value1 is None:
return None
if not (value1 == value2):
messagebox.showwarning("Password Mismatch", "The new password and confirmation do not match.")
return None
return_code = self.var.update_password(value1)
if return_code:
messagebox.showinfo("Password Changed Successfully", "Your password has been updated successfully.")
else:
messagebox.showerror("Password Change Failed", "There was an error updating your password. Please try again.")
def __new_account(self) -> None:
"""
Handles the creation of a new player account.
This method gathers user input for account creation, verifies the input,
and creates a new account if all checks are passed. It displays appropriate
messages to the user based on the success or failure of the account creation process.
"""
account_name, name, pass1, pass2 = self.window.create_new_account_window()
account_list = self.var.get_account_list()
if not (account_name and name and pass1 and pass2):