-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcows.py
More file actions
1932 lines (1584 loc) · 75.7 KB
/
Copy pathcows.py
File metadata and controls
1932 lines (1584 loc) · 75.7 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 pygame
from typing import Union
# noinspection PyUnresolvedReferences
from yugo_tools import get_image, join, cserp, _move_pos, fetch_text, expand_rect, debug_time
from numpy import clip as clamp, log2
from math import sqrt
# noinspection PyUnresolvedReferences
from pygamepopups import update_popups, handle_popup_events, RightClickMenu, RightClickOption, \
RightClickAbility, get_pause_menu, set_rcm_width
from effects import CurrencyParticle, CircleParticle, play_sound_path, FakeCard
from constants import *
# noinspection PyUnresolvedReferences
from cowspopups import add_popup, draw_cows_popups, handle_cows_popups, add_debug_popup
from random import choices as randchoice, random
class Action:
def __init__(self, card, action: int, param1: Union[int, callable], conditional=None):
self.card: Card = card
self.action = action
self.param1 = param1
self.conditional: Union[ActionConditional, None] = conditional
class InputAction:
def __init__(self, card, what_choose: int, param1: int, conditional=None): # todo this is pretty much abandonied fix it sometime pls
self.card: Card = card
self.choose = what_choose
self.param1 = param1
self.conditional: Union[ActionConditional, None] = conditional
class DelayedAction:
def __init__(self, card, action: int, param1: int, wait_for: int, conditional=None):
self.card: Card = card
self.action = action
self.param1 = param1
self.wait_for = wait_for
self.conditional: Union[ActionConditional, None] = conditional
class ActionConditional:
def __init__(self, card, requirement, comparison_type, amount):
"""Its self, then requirement, then comparison, then amount (e.g. 2 > 3),
so more than means that requirement > amount
"""
self.card = card
self.req = requirement
self.comp = comparison_type
self.amount = amount
def is_true(self):
amount1 = 0
if self.req == REQ_CARD_NUM_RESIDENTS:
amount1 = self.card.get_num_residents()
if self.req == REQ_LAND_AMOUNT:
amount1 = len(list(filter(lambda card: card.type == TYPE_LAND, get_local_player().get_cards_recursively())))
if self.req == REQ_TURNS_PASSED:
amount1 = get_statistics_manager().turns_passed
amount2 = self.amount
if self.comp == COND_OPERATOR_MORE_THAN:
return amount1 > amount2
if self.comp == COND_OPERATOR_EQUALS:
return amount1 == amount2
if self.comp == COND_OPERATOR_LESS_THAN:
return amount1 < amount2
return True
class Hand:
def __init__(self):
self.cards: list[Card] = []
self.anim: dict[int, float] = {}
self.in_anim: dict[int, float] = {}
def draw(self, surface: pygame.Surface, framerate: int) -> None:
padding_width = 200
hand_rect = pygame.Rect(padding_width, surface.get_height()-300, surface.get_width()-padding_width*2, 300)
in_anim_sum = sum([cserp(self.in_anim.get(id(in_card), 0)) for in_card in self.cards])
for count, card in enumerate(self.cards):
self.anim[id(card)] = self.anim.get(id(card), 0)
self.in_anim[id(card)] = self.in_anim.get(id(card), 0)
log_part = 1
if not in_anim_sum == 0:
log_part = clamp(log2(in_anim_sum+1), 1, 18923)
if log_part == 0:
log_part = 1
x = surface.get_width()/2 # start at center
x -= in_anim_sum*125/log_part # offset to the left
spacing = 250/log_part
x += count*spacing # move to the right based on enum count
y = surface.get_height()-180-(cserp(self.anim[id(card)])*145)
card_rect = pygame.Rect(x, y, 250/log_part+(250-250/log_part)*(int(len(self.cards)-1 == count)), 325)
if card_rect.collidepoint(pygame.mouse.get_pos()):
self.anim[id(card)] += 0.06*75/framerate
else:
self.anim[id(card)] -= 0.06*75/framerate
self.anim[id(card)] = clamp(self.anim[id(card)], 0, 1)
self.in_anim[id(card)] += 0.06*75/framerate
self.in_anim[id(card)] = clamp(self.in_anim[id(card)], 0, 1)
optimized_card = get_image(join("images", "cards", card.image), (0.5, 0.5))
if self.anim[id(card)] == 0 and len(self.cards) > 5 and count != len(self.cards)-1: # crop the card for faster drawing
optimized_card = optimized_card.subsurface(pygame.Rect(0, 0, spacing+30, 325))
surface.blit(optimized_card, (x, y))
if debug:
draw_border_of_rect(surface, card_rect)
draw_border_of_rect(surface, hand_rect, (255, 0, 0))
def handle_events(self, event: pygame.event.Event):
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
surface = pygame.display.get_surface()
padding_width = 200
hand_rect = pygame.Rect(padding_width, surface.get_height()-300, surface.get_width()-padding_width*2, 300)
if hand_rect.collidepoint(pygame.mouse.get_pos()):
cards_hitboxes = {}
for count, card in enumerate(self.cards):
surface = pygame.display.get_surface()
self.anim[id(card)] = self.anim.get(id(card), 0)
in_anim_sum = sum([cserp(self.in_anim.get(id(in_card), 0)) for in_card in self.cards])
log_part = 1
if not in_anim_sum == 0:
log_part = log2(in_anim_sum+1)
if log_part == 0:
log_part = 1
x = surface.get_width()/2 # start at center
x -= in_anim_sum*125/log_part # offset to the left
x += count*250/log_part # move to the right based on enum count
cards_hitboxes[tuple(
pygame.Rect(x, surface.get_height()-180-cserp(self.anim[id(card)])*145, 250, 325)[:4])] = card
for card_hitbox in cards_hitboxes.__reversed__():
if pygame.Rect(card_hitbox).collidepoint(pygame.mouse.get_pos()):
return cards_hitboxes[card_hitbox]
return
class Field:
def __init__(self):
self.cards: list[Card] = []
self.land_bloom_out_anim: dict[int, float] = {}
def draw(self, surface: pygame.Surface, framerate: int) -> None:
def sort_by_anim(i: Card):
if id(i) in self.land_bloom_out_anim:
return self.land_bloom_out_anim[id(i)]
else:
return 0
for card in sorted(self.cards, key=sort_by_anim):
if card.type == TYPE_LAND:
self.land_bloom_out_anim[id(card)] = self.land_bloom_out_anim.get(id(card), 0)
if card.get_rect().collidepoint(pygame.mouse.get_pos()):
self.land_bloom_out_anim[id(card)] += 0.05*75/framerate
else:
self.land_bloom_out_anim[id(card)] -= 0.05*75/framerate
self.land_bloom_out_anim[id(card)] = clamp(self.land_bloom_out_anim[id(card)], 0, 1)
anim = cserp(self.land_bloom_out_anim[id(card)])
pygame.draw.circle(surface, pygame.color.Color(169, 228, 239).lerp((255, 147, 61), 0.3+anim*0.4),
_move_pos(card.mod_pos(), (125, 162)), 500)
for card in self.cards:
card.draw(surface)
def handle_events(self, event: pygame.event.Event):
for card in self.cards.__reversed__():
sel_prev = card.selected
mouseevent = card.handle_events(event)
if mouseevent == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
self.put_on_top(card)
return True
elif mouseevent == pygame.MOUSEBUTTONUP:
if event.button == 1:
if sel_prev:
return card
def put_on_top(self, card):
card: Card
self.cards.remove(card)
self.cards.append(card)
def discard_card(self, card):
"""This is for animation support"""
width, height = pygame.display.get_surface().get_size()
if card in self.cards:
self.cards.remove(card)
get_local_player().discarding_fake_cards.append(
FakeCard(card.image, card.mod_pos(), (width-160, height-130), grot=180, srot=180,
anim_time=0.7, real_card=card, endsize=(150, 197)))
def max_animals_allowed(self) -> int:
return sum([land.land_max_capacity for land in self.cards if land.type == TYPE_LAND])
class Camera:
def __init__(self, pos: tuple[int, int]):
self.x = pos[0]
self.y = pos[1]
def __repr__(self):
return f"<Camera({self.x}, {self.y})>"
class Player:
# noinspection PyUnresolvedReferences
def __init__(self, name: str):
# important stuff
self.dollar: int = 5
self.milk: int = 5
self.hay: int = 5
self.username = name
self.field: Field = Field()
self.hand: Hand = Hand()
self.camera = Camera((0, 0))
self.is_my_turn = True
self.step = "collect"
self.in_sandbox = True
# visible stuff
self.visible_money = self.dollar
self.visible_milk = self.milk
self.visible_hay = self.hay
# discard stuff
self.discard_pile: list[Card] = []
self.discarding_fake_cards: list[FakeCard] = []
self.drawing_fake_cards: list[FakeCard] = []
# queues and waiting
self.doing_input_action = False
self.delayed_action_queue: list[DelayedAction] = []
self.action_queue: list[Union[InputAction, Action]] = []
# misc
self.loot_pool = {}
self.has_drawn_starting = False
self.index_of_grab = 0
def update_visible_currencies(self):
global currency_particles
self.visible_money = self.dollar
self.visible_milk = self.milk
self.visible_hay = self.hay
currency_particles = []
def all_of_type(self, card_class):
return [card for card in self.get_cards_recursively() if isinstance(card, card_class)]
def amount_of(self, card_class):
return len(self.all_of_type(card_class))
@property
def currencies(self):
return {DOLLAR: self.dollar, HAY: self.hay, MILK: self.milk}
@property
def can_use_cards(self):
return self.step == "use"
def draw(self, surface: pygame.Surface, font: pygame.font.Font, big_font: pygame.font.Font):
# ratios and div numbers
box_width = 40
box_height = 90
text_height_from_top = 60
spacing_x = 18
box_height_from_top = 7
# this is used a lot
player_info_rect = pygame.Rect((10, pygame.display.get_surface().get_height()-160+box_height_from_top, 150, 150))
# show step
surface.blit(fetch_text(f"step: {self.step}", big_font), (10, 40))
# money border
money_rectangle = pygame.Rect(player_info_rect.left, player_info_rect.top, box_width, box_height)
pygame.draw.rect(surface, (77, 77, 77), expand_rect(money_rectangle, 4).move(0, 4))
pygame.draw.rect(surface, (0, 0, 0), expand_rect(money_rectangle, 4))
money_surf = pygame.Surface(money_rectangle.size)
money_surf.fill((94, 252, 141))
surface.blit(money_surf, money_rectangle.topleft)
# money text
money_text_pos = _move_pos(money_rectangle.topleft, (box_width/2, text_height_from_top))
surface.blit(fetch_text(f"{clamp(self.visible_money, 0, 69420)}", font),
fetch_text(f"{clamp(self.visible_money, 0, 69420)}", font).get_rect(midtop=money_text_pos))
surface.blit(get_image(join("images", "money.png")), money_rectangle.topleft)
# milk border
milk_rectangle = pygame.Rect(player_info_rect.left+40+spacing_x, player_info_rect.top, box_width, box_height)
pygame.draw.rect(surface, (77, 77, 77), expand_rect(milk_rectangle, 4).move(0, 4))
pygame.draw.rect(surface, (0, 0, 0), expand_rect(milk_rectangle, 4))
milk_surf = pygame.Surface(milk_rectangle.size)
milk_surf.fill((163, 247, 255))
surface.blit(milk_surf, milk_rectangle.topleft)
# milk text
milk_text_pos = _move_pos(milk_rectangle.topleft, (box_width/2, text_height_from_top))
surface.blit(fetch_text(f"{clamp(self.visible_milk, 0, 69420)}", font), fetch_text(f"{clamp(self.visible_milk, 0, 69420)}", font).get_rect(midtop=milk_text_pos))
surface.blit(get_image(join("images", "milk.png")), milk_rectangle.topleft)
# hay border
hay_rectangle = pygame.Rect(player_info_rect.left+(40+spacing_x)*2, player_info_rect.top, box_width, box_height)
pygame.draw.rect(surface, (77, 77, 77), expand_rect(hay_rectangle, 4).move(0, 4))
pygame.draw.rect(surface, (0, 0, 0), expand_rect(hay_rectangle, 4))
hay_surf = pygame.Surface(hay_rectangle.size)
hay_surf.fill((245, 230, 99))
surface.blit(hay_surf, hay_rectangle.topleft)
# hay text
hay_text_pos = _move_pos(hay_rectangle.topleft, (box_width/2, text_height_from_top))
surface.blit(fetch_text(f"{clamp(self.visible_hay, 0, 69420)}", font), fetch_text(f"{clamp(self.visible_hay, 0, 69420)}", font).get_rect(midtop=hay_text_pos))
surface.blit(get_image(join("images", "hay.png")), hay_rectangle.topleft)
# discard pile
if len(self.discard_pile) > 0:
discard_rect = pygame.Rect(pygame.display.get_surface().get_width()-160,
pygame.display.get_surface().get_height()-130, 20, 20)
discard_top_card_surf = get_image(join("images", "cards", self.discard_pile[len(self.discard_pile)-1].image), (0.3, 0.3))
surface.blit(discard_top_card_surf, discard_top_card_surf.get_rect(topleft=discard_rect.topleft))
surface.blit(fetch_text(f"Discard Pile", font), discard_rect.move(0, -25).topleft)
# set the scraping land amount
new_coll = get_pause_menu().land_scrape_accuracy.selected_option
if land_collision_accuracy != new_coll:
set_land_coll_acc(new_coll)
# set the rcm width
set_rcm_width(get_pause_menu().rcm_width.selected_option)
# hover cards in fake cards
hand_card_image_name = None
card_hover = None
inhabitants = []
if hand_card_image_name is None:
if len(self.drawing_fake_cards) > 0:
tmp = self.drawing_fake_cards[0]
if tmp.get_rect().collidepoint(pygame.mouse.get_pos()):
if tmp.anim > 0.5 and tmp.gy == tmp.sy:
hand_card_image_name = tmp.image
card_hover = self.drawing_fake_cards[0].real_card
# hover card in hand cards
if hand_card_image_name is None:
for count, card in enumerate(self.hand.cards):
self.hand.anim[id(card)] = self.hand.anim.get(id(card), 0)
in_anim_sum = sum([cserp(self.hand.in_anim.get(id(in_card), 0)) for in_card in self.hand.cards])
log_part = 1
if not in_anim_sum == 0:
log_part = log2(in_anim_sum+1)
if log_part == 0:
log_part = 1
x = surface.get_width()/2 # start at center
x -= in_anim_sum*125/log_part # offset to the left
x += count*250/log_part # move to the right based on enum count
card_rect = pygame.Rect(x, surface.get_height()-180-cserp(self.hand.anim[id(card)])*145, 250, 325)
if card_rect.collidepoint(pygame.mouse.get_pos()): # hovering over hand card
hand_card_image_name = card.image
card_hover = card
# hover card in field cards
if hand_card_image_name is None:
for card in self.get_cards_recursively().__reversed__():
if card.get_rect().collidepoint(pygame.mouse.get_pos()): # hovering over field card
hand_card_image_name = card.image
card_hover = card
if len(inhabitants) == 0:
inhabitants = card.equipped.copy()
break
# draw if hover card exists
if hand_card_image_name is not None:
if get_pause_menu().hover_opacity.selected_option == "Invisible":
return
hover_img = get_image(join("images", "cards", hand_card_image_name), (0.8, 0.8), 0.1).copy()
if get_pause_menu().hover_opacity.selected_option == "Translucent":
hover_img.set_alpha(90)
hover_rect = hover_img.get_rect(midright=(surface.get_width()-10, surface.get_height()/2))
surface.blit(hover_img, hover_rect)
card_type_dict = {TYPE_ANIMAL: "animal", TYPE_TALISMAN: "talisman", TYPE_LAND: "land",
TYPE_EQUIPMENT: "equipment", TYPE_INCANTATION: "incantation"}
card_type_text = fetch_text(f"card type: {card_type_dict[card_hover.type]}", font)
surface.blit(card_type_text, card_type_text.get_rect(midtop=_move_pos(hover_rect.midtop, (0, 10))))
def class_to_string(thing) -> str:
thing = str(type(thing))[13:-2]
newthing = ""
for count_, letter in enumerate(thing):
letter: str
if not count_ == 0 and letter.isupper():
newthing += " " + letter.lower()
continue
newthing += letter
continue
return newthing
# add animal inhabitants
on_land: list[int] = []
if card_hover in self.field.cards:
for card_inhab in card_hover.get_residents():
inhabitants.append(card_inhab)
on_land.append(id(card_inhab))
# do inhabitants and equipments (naming is scuffed)
if len(inhabitants) > 0:
for inhab_count, card_inhab in enumerate(inhabitants):
if id(card_inhab) in on_land:
card_type_text = fetch_text(f"{class_to_string(card_inhab)} lives here", font)
else:
card_type_text = fetch_text(f"+ {class_to_string(card_inhab)}", font)
surface.blit(card_type_text,
card_type_text.get_rect(
midtop=_move_pos(hover_rect.midbottom, (0, 30*inhab_count+10))))
def draw_fake_cards(self, surface: pygame.Surface, framerate: int):
# draw the pick up cards
if len(self.drawing_fake_cards) > 0:
self.drawing_fake_cards[0].draw(surface, framerate)
if get_debug():
draw_border_of_rect(surface, self.drawing_fake_cards[0].get_rect())
kill_list = []
for card in self.discarding_fake_cards:
card.draw(surface, framerate)
if card.anim == 1:
get_local_player().discard_pile.append(card.real_card)
kill_list.append(card)
if len(self.drawing_fake_cards) > 0:
fake_card = self.drawing_fake_cards[0]
if fake_card.get_rect().collidepoint(pygame.mouse.get_pos()):
if fake_card.grot == 0:
fake_card.reveal(0.6)
for card_kill in kill_list:
self.discarding_fake_cards.remove(card_kill)
# noinspection PyTypeChecker
def update_cursor_image(self):
if self.doing_input_action:
pygame.mouse.set_cursor(pygame.cursors.Cursor(pygame.SYSTEM_CURSOR_CROSSHAIR))
else:
pygame.mouse.set_cursor(pygame.cursors.Cursor(pygame.SYSTEM_CURSOR_ARROW))
def handle_events(self, event: pygame.event.Event):
# prevent doing anything if getting input action
if self.doing_input_action:
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
for card in self.get_cards_recursively().__reversed__():
if card.get_rect().collidepoint(pygame.mouse.get_pos()):
action = self.action_queue[0]
card_type_interpreter = {
PICK_CARD: lambda _: True,
PICK_COW: lambda _: _.card_is_cow,
PICK_PLAYER: lambda _: False,
PICK_LAND: lambda _: _.type == TYPE_LAND,
PICK_ANIMAL: lambda _: _.type == TYPE_ANIMAL
}
if card_type_interpreter[action.choose](card):
self.doing_input_action = False
self.action_queue.pop(0)
self.clear_queue()
self.update_cursor_image()
get_statistics_manager().last_cow_chosen = card
else:
add_popup("You can't do that!")
return True
# handling the fake cards
if len(self.drawing_fake_cards) > 0:
fake_card = self.drawing_fake_cards[0]
if fake_card.get_rect().collidepoint(pygame.mouse.get_pos()):
if fake_card.grot == 0:
pass
elif fake_card.anim >= 0.5:
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
self.hand.cards.append(fake_card.real_card)
self.drawing_fake_cards.remove(fake_card)
play_sound_path(join("sounds", "cardplay.mp3"), 0.5)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE: # draw instantly
self.hand.cards.append(fake_card.real_card)
self.drawing_fake_cards.remove(fake_card)
play_sound_path(join("sounds", "cardplay.mp3"), 0.5)
return True
# grabbing a card from the hand
card = self.hand.handle_events(event)
if card:
if self.hand.cards.__contains__(card):
for index_count, card_index_find in enumerate(self.hand.cards):
if card_index_find == card:
self.index_of_grab = index_count
self.hand.cards.remove(card)
card.x, card.y = pygame.mouse.get_pos()
card.grab_off = (-125, -162)
card.selected = True
self.field.cards.append(card)
return True
# grabbing and letting go of card in field
card_field = self.field.handle_events(event)
if self.field.cards.__contains__(card_field):
if isinstance(card_field, Card):
# let go of card
if pygame.mouse.get_pos()[1] > pygame.display.get_surface().get_height()-170:
# on the hand area
if not card_field.was_on_field:
self.hand.cards.insert(self.index_of_grab, card_field)
self.field.cards.remove(card_field)
if self.step != "use":
play_sound_path(join("sounds", "error.mp3"))
else:
# on your field
if get_local_player().step == "use":
if not card_field.was_on_field: # has not payed for it yet
if not has_required_cash(card_field.cost_currency, card_field.cost_amount):
self.field.cards.remove(card_field)
self.hand.cards.insert(self.index_of_grab, card_field)
add_popup("You don't have enough wealth")
play_sound_path(join("sounds", "error.mp3"))
return True
if card_field.type == TYPE_INCANTATION:
for ability in card_field.abilities:
if isinstance(ability, list):
for ab2 in ability:
ab2.activate()
else:
ability.activate()
get_local_player().clear_queue()
self.field.discard_card(card_field)
else:
if card_field.type == TYPE_EQUIPMENT:
if not self.attempt_equip_card(card_field):
return True
remove_currency_if_has(card_field.cost_currency, card_field.cost_amount)
card_field.was_on_field = True
play_sound_path(join("sounds", "cardfold.mp3"), 0.4)
self.handle_card_actions(GE_SELF_PLAY_CARD)
else:
if not card_field.was_on_field:
self.field.cards.remove(card_field)
self.hand.cards.insert(self.index_of_grab, card_field)
play_sound_path(join("sounds", "error.mp3"))
if get_local_player().step == "collect":
add_popup("You must draw a card first!")
return True
if isinstance(card_field, bool):
return True
# prevent grabbing multiple cards at once (e.g. with auto clicker or low debounce time)
if sum([int(card.selected) for card in self.field.cards]) > 1:
one_done = False
kill_list = []
for card_prevent_grab in self.field.cards:
if card_prevent_grab.selected:
if not one_done:
one_done = True
else:
kill_list.append(card_prevent_grab)
for hit in kill_list:
self.field.cards.remove(hit)
self.hand.cards.append(hit)
def attempt_equip_card(self, card_find) -> bool:
card_find: Card
card_find.selected = False
if card_find.type == TYPE_EQUIPMENT:
for card in self.field.cards.__reversed__():
if id(card) != id(card_find):
if card.get_rect().collidepoint(pygame.mouse.get_pos()): # card dragged on card
if self.field.cards.__contains__(card_find): # assert is not null
good_types = (card_find.equipment_can_go_on if isinstance(card_find.equipment_can_go_on, tuple) else (card_find.equipment_can_go_on,))
if good_types.__contains__(card.type):
# equipment cow exclusive check
if not card.card_is_cow:
if card_find.equipment_is_cow_exclusive:
continue
else:
add_popup("This is cow exclusive!")
# do the deed
self.field.cards.remove(card_find)
card.equipped.append(card_find)
for action in card_find.handle_action(GE_THIS_CARD_EQUIPPED):
execute_action(action)
return True
# could not find a card to go on top of
if self.field.cards.__contains__(card_find): # assert is not null (same as above)
self.field.cards.remove(card_find)
self.hand.cards.append(card_find)
add_popup(f"You cannot do that there!")
play_sound_path(join("sounds", "error.mp3"))
return False
def next_turn_step(self):
# wait for other turn
if not self.is_my_turn:
add_popup("Not your turn!")
return True
# valid cards check
if self.do_validity_check():
return True
# change step
self.step = "collect" if self.step == "use" else "use"
get_local_player().update_visible_currencies()
# draw step stuff
if self.step == "use":
get_statistics_manager().turns_passed += 1
self.draw_card()
# collect step stuff
if self.step == "collect":
self.hay = 0
self.handle_card_actions(GE_SELF_TURN_START)
self.reset_abilities()
return False
def do_validity_check(self) -> bool:
"""Returns true if cards are in an invalid state (e.g. incantations/equipments on their own)"""
width, height = pygame.display.get_surface().get_size()
def camera_to_card(_):
get_local_player().camera.x = -width/2+_.x+150
get_local_player().camera.y = -height/2+_.y+162
# solo incantations and equipments
for card in self.field.cards:
if card.type in (TYPE_INCANTATION, TYPE_EQUIPMENT):
add_popup("This needs to go on a card" * (card.type == TYPE_EQUIPMENT) +
"How tf you do that?????" * (card.type == TYPE_INCANTATION))
camera_to_card(card)
return True
# overcrowding on lands:
for card in [_ for _ in self.field.cards if _.type == TYPE_LAND and _.was_on_field]:
if card.land_max_capacity is not None:
if len([res for res in card.get_residents() if res.card_is_cow or not card.land_only_holds_cows]) > card.land_max_capacity:
camera_to_card(card)
if card.land_max_capacity == 0:
camera_to_card(card)
add_popup("This land can't have any animals!")
return True
add_popup("Too many animals on this land!")
return True
# animals without a home
not_homeless_cards = []
for card in [_ for _ in self.field.cards if _.type != TYPE_ANIMAL]:
not_homeless_cards.extend(card.get_residents())
not_homeless_cards.append(card)
if len(self.field.cards) > len(not_homeless_cards):
for card in self.field.cards:
if not not_homeless_cards.__contains__(card):
if not card.has_equipment(FluxCapacitor):
camera_to_card(card)
add_popup("This animal needs a home!")
return True
elif len(self.field.cards) < len(not_homeless_cards):
add_popup("Card is on two lands at once!")
return True
return False
def get_cards_recursively(self, rec_list=None):
rec_list: list[Card]
total_cards = rec_list.copy() if rec_list is not None else []
if rec_list is None:
rec_list = self.field.cards
for card in rec_list:
total_cards.append(card)
for card_rec in rec_list:
rec = self.get_cards_recursively(card_rec.equipped)
total_cards.extend(rec)
return total_cards
def draw_starting_hand(self):
"""Draws two cards (weightedly) randomly.
Draws one land card (unweighted). If no lands found, draws random weighted card instead.
Draws one talisman card (unweighted). If no talismans found, draws random weighted card instead."""
self.draw_card(2)
if len([ct for ct in list(self.loot_pool.keys()) if ct.type == TYPE_LAND]): # at least one type land card in there
card_var = randchoice([ct for ct in list(self.loot_pool.keys()) if ct.type == TYPE_LAND])[0]()
width, height = pygame.display.get_surface().get_size()
# noinspection PyTypeChecker
self.drawing_fake_cards.append(FakeCard(card_var.image, (width/2-125, -250), (width/2-125, height/2-162),
anim_time=0.6, real_card=card_var))
else:
self.draw_card()
if len([ct for ct in list(self.loot_pool.keys()) if ct.type == TYPE_TALISMAN]): # at least one type land card in there
card_var = randchoice([ct for ct in list(self.loot_pool.keys()) if ct.type == TYPE_TALISMAN])[0]()
width, height = pygame.display.get_surface().get_size()
# noinspection PyTypeChecker
self.drawing_fake_cards.append(FakeCard(card_var.image, (width/2-125, -250), (width/2-125, height/2-162),
anim_time=0.6, real_card=card_var))
else:
self.draw_card()
def draw_card(self, amount=1, card_class=None):
width, height = pygame.display.get_surface().get_size()
if card_class is None:
cards = list(self.loot_pool.keys())
weights = list(self.loot_pool.values())
for card_drawn in randchoice(cards, weights=weights, k=amount):
card_var = card_drawn()
# noinspection PyTypeChecker
self.drawing_fake_cards.append(FakeCard(card_var.image, (width/2-125, -250), (width/2-125, height/2-162),
anim_time=0.6, real_card=card_var))
else:
for _ in range(amount):
# noinspection PyTypeChecker
self.drawing_fake_cards.append(FakeCard(card_class.image, (width/2-125, -250), (width/2-125, height/2-162),
anim_time=0.6, real_card=card_class()))
def can_pay_for(self, currency: int, cost: int) -> bool:
"""If the player can pay for a certain item, return true"""
current_amount = (int(currency == DOLLAR) * self.dollar
+ int(currency == MILK) * self.milk
+ int(currency == HAY) * self.hay)
if current_amount >= cost:
return True
return False
def handle_card_actions(self, action: int):
if action in (GE_SELF_TURN_START,):
self.handle_card_actions(GE_ANY_TURN_START)
# run delayed actions
delayed_action_kill_list = []
for delayed_action in self.delayed_action_queue:
if delayed_action.wait_for == action:
execute_action(Action(delayed_action.card, delayed_action.action, delayed_action.param1))
delayed_action_kill_list.append(delayed_action)
for kill_me in delayed_action_kill_list:
self.delayed_action_queue.remove(kill_me)
# see if each action is valued by thing
total_actions: list[Action, DelayedAction, InputAction] = []
for card in self.get_cards_recursively():
actions = card.handle_action(action)
if actions in (None, []):
continue
for action_add in actions:
total_actions.append(action_add)
# sort the actions
def sort_actions(_: Action):
return _.action
# sort actions by number and execute them in order
total_actions.sort(key=sort_actions)
for action in total_actions:
if isinstance(action, DelayedAction):
self.delayed_action_queue.append(action)
else:
self.action_queue.append(action)
self.clear_queue()
def clear_queue(self):
"""Run through the queue and clear as many actions from it as possible (before it hits an InputAction)"""
kill_list = []
for action in self.action_queue:
if isinstance(action, Action):
execute_action(action)
kill_list.append(action)
elif isinstance(action, InputAction):
self.doing_input_action = True
self.update_cursor_image()
for _ in kill_list:
self.action_queue.remove(_)
def reset_abilities(self):
for card in self.get_cards_recursively():
card.reset_abilities()
for card in self.discard_pile:
card.reset_abilities()
for card in self.hand.cards:
card.reset_abilities()
class StatisticsManager:
def __init__(self):
"""Keeps track of statistics throughout the game. Only for tracking stats of the local player, other's stats are gotten through packets (maybe)"""
self.turns_passed = 0
self.last_cow_chosen = None
def get_num_cows(self):
return len([card_cow for card_cow in get_local_player().get_cards_recursively() if card_cow.card_is_cow])
def get_num_players(self):
return 1
def get_last_cow_chosen(self):
return self.last_cow_chosen
def get_num_animals(self):
return len([card_cow for card_cow in get_local_player().get_cards_recursively() if card_cow.type == TYPE_ANIMAL])
# player + stats
local_player = Player("quasar098")
stat_man = StatisticsManager()
# other
card_LOD = 60 # card distance apart (lift off distance) when equipments are equipped
land_collision_accuracy = 3 # how accurate to be with collision when scraping (scrape) the edge of lands against other lands
def set_land_coll_acc(val):
global land_collision_accuracy
land_collision_accuracy = val
# special effects
currency_particles: list[CurrencyParticle] = []
circle_particles: list[CircleParticle] = []
# debug
debug = False
def get_currency_particles():
return currency_particles
def get_circle_particles():
return circle_particles
def get_parent(card_find):
card_find: Card
for card in get_local_player().field.cards:
if card.equipped.__contains__(card_find):
return card
def toggle_debug() -> bool:
global debug
debug = not debug
return debug
def get_debug() -> bool:
return debug
def get_local_player() -> Player:
return local_player
def get_statistics_manager() -> StatisticsManager:
return stat_man
def draw_border_of_rect(surf: pygame.Surface, rect: pygame.rect.Rect, color: tuple[int, int, int] = (0, 0, 0)) -> None:
"""Draws the lines around the pygame rectangle"""
pygame.draw.line(surf, color, rect.topleft, rect.topright, 5)
pygame.draw.line(surf, color, rect.bottomright, rect.topright, 5)
pygame.draw.line(surf, color, rect.bottomright, rect.bottomleft, 5)
pygame.draw.line(surf, color, rect.topleft, rect.bottomleft, 5)
def mod_x(x):
return x-get_local_player().camera.x
def replace_placeholder(var_placeholder: int):
if var_placeholder == PL_SELF_TURNS_PASSED:
return get_statistics_manager().turns_passed
if var_placeholder == PL_SELF_DOLLAR_AMOUNT:
return get_local_player().dollar
if var_placeholder == PL_SELF_MILK_AMOUNT:
return get_local_player().milk
if var_placeholder == PL_SELF_HAY_AMOUNT:
return get_local_player().hay
if var_placeholder == PL_SELF_NUM_COWS_ON_FIELD:
return get_statistics_manager().get_num_cows()
if var_placeholder == PL_SELF_NUM_ANIMAL_ON_FIELD:
return get_statistics_manager().get_num_animals()
if var_placeholder == PL_SELF_NUM_CARDS_ON_FIELD:
return len(get_local_player().get_cards_recursively())
if var_placeholder == PL_NUM_PLAYERS:
return get_statistics_manager().get_num_players()
if var_placeholder == PL_LAST_CARD_CHOSEN:
return get_statistics_manager().last_cow_chosen
if var_placeholder == PL_SELF_NUM_CARDS_IN_HAND:
return len(get_local_player().hand.cards)
return var_placeholder
def mod_y(y):
return y-get_local_player().camera.y
def mod_pos(x, y, inv=False):
if not inv:
return mod_x(x), mod_y(y)
else:
return x+get_local_player().camera.x, y+get_local_player().camera.y
def has_required_cash(currency_type: int, amount: int) -> bool:
return get_local_player().currencies[currency_type] >= amount
def remove_currency_if_has(currency_type: int, amount: int) -> bool:
"""Returns true if the currency has been removed from the players total balance"""
def create_loss_particles(pos: tuple[float, float], am: int):
for _ in range(am):
get_circle_particles().append(CircleParticle(pos, color=(250, 60, 60)))
width, height = pygame.display.get_surface().get_size()
if currency_type == DOLLAR:
if get_local_player().dollar >= amount:
get_local_player().dollar -= amount
get_local_player().visible_money -= amount
create_loss_particles((27, height-135), amount*2)
return True
if currency_type == MILK:
if get_local_player().milk >= amount:
get_local_player().milk -= amount
get_local_player().visible_milk -= amount
create_loss_particles((85, height-135), amount*2)
return True
if currency_type == HAY:
if get_local_player().hay >= amount:
get_local_player().hay -= amount
get_local_player().visible_hay -= amount
create_loss_particles((145, height-135), amount*2)
return True
if currency_type is None:
return True
play_sound_path(join("sounds", "error.mp3"))
return False
def execute_action(action: Union[Action, DelayedAction, InputAction]) -> None:
if action.conditional is not None:
if not action.conditional.is_true():
return
if isinstance(action, Action):
# substitute the real amount in for a placeholder (e.g. NUM_COWS -> [actual number of cows])
amount = replace_placeholder(action.param1)
# particle position
particle_pos = _move_pos(action.card.mod_pos(), (125, 162))
# add X particles where X is the amount
multiplier = 1
_s = action.card.get_land_im_on(get_local_player())
if _s is not None:
_s = _s.land_buff_animal_multipliers
for mul_class in _s:
if isinstance(action.card, mul_class):
multiplier *= _s[mul_class]
if action.action == DO_RUN_FUNCTION:
action.param1()
return
for _ in range(amount*multiplier):
if action.action == DO_SELF_DRAW_CARD:
get_local_player().draw_card(action.param1)
return
if action.action == DO_RECOLLECT_INHABITANTS:
res = get_local_player().get_cards_recursively(action.card.get_residents())
max_cupoc = action.card.land_max_capacity
assert action.card.land_max_capacity is not None
for count, card in enumerate(res):
if count+1 > max_cupoc: # so the player cannot drag all cows onto black market and go crazy
return
actions = card.handle_action(GE_SELF_TURN_START)
for action in actions:
execute_action(action)
return
if action.action == DO_SELF_DUPLICATE_CARD:
get_local_player().hand.cards.append(type(get_parent(action.card))())
if action.action == DO_SELF_GIVE_DOLLAR:
get_local_player().dollar += 1
currency_particles.append(CurrencyParticle(particle_pos, DOLLAR))
if action.action == DO_SELF_GIVE_MILK:
get_local_player().milk += 1
currency_particles.append(CurrencyParticle(particle_pos, MILK))
if action.action == DO_SELF_GIVE_HAY:
get_local_player().hay += 1
currency_particles.append(CurrencyParticle(particle_pos, HAY))
if action.action == DO_STEAL_DOLLAR_FROM_ALL_OPPONENTS:
get_local_player().dollar += get_statistics_manager().get_num_players() * action.param1
# todo: remove money from other players
if action.action == DO_SELF_DRAW_DAIRY_COW:
get_local_player().draw_card(action.param1, DairyCow)
if action.action == DO_SELF_DRAW_MANURE:
get_local_player().draw_card(action.param1, Manure)
if action.action == DO_TAKE_TOP_DISCARD_CARD:
if len(get_local_player().discard_pile) >= 1:
revived = get_local_player().discard_pile[len(get_local_player().discard_pile)-1]
revived.was_on_field = False
revived.reset_abilities()
get_local_player().hand.cards.append(revived)
get_local_player().discard_pile.pop(len(get_local_player().discard_pile)-1)
if action.action == DO_TAKE_ALL_DISCARD_CARDS:
outcome = random() < action.param1 / 100
if outcome:
for card in get_local_player().discard_pile:
card.was_on_field = False