-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai
More file actions
1118 lines (900 loc) · 34 KB
/
ai
File metadata and controls
1118 lines (900 loc) · 34 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
[main.py]:
import pygame
import sys
from world import World
from gui.simulation_frame import SimulationFrame
def main():
try:
pygame.init()
pygame.display.set_caption("World Simulation")
print("Pygame initialized")
# Świat i interfejs
size = 20
world = World("Simulation", size, size)
frame = SimulationFrame(size, size, world)
world.set_simulation_frame(frame)
# Debugowanie inicjalizacji
print(f"Screen size: {frame.screen.get_size()}")
print(f"Grid size: {frame.grid_width}x{frame.grid_height}")
print(f"World map size: {len(world.map)}x{len(world.map[0])}")
# Start
world.start()
print("World started")
# Główna pętla
clock = pygame.time.Clock()
while frame.running:
frame._handle_events()
frame._draw()
pygame.display.flip()
clock.tick(60)
except Exception as e:
print(f"\nCritical error: {str(e)}")
import traceback
traceback.print_exc()
finally:
pygame.quit()
print("Game closed")
if __name__ == "__main__":
main()
[organism.py]:
from abc import ABC, abstractmethod
class Organism(ABC):
def __init__(self, x: int, y: int, world):
self.x = x
self.y = y
self.strength = 0
self.initiative = 0
self.symbol = ' '
self.name = ""
self.age = 0
self.world = world
self.is_alive = True
@abstractmethod
def action(self):
pass
@abstractmethod
def respond_to_collision(self, other: 'Organism') -> bool:
pass
def die(self):
self.is_alive = False
self.world.map[self.x][self.y] = '.'
if hasattr(self, 'is_human') and self.is_human:
self.world.handle_human_death()
def move(self, new_x: int, new_y: int):
self.x = new_x
self.y = new_y
def increase_age(self):
self.age += 1
def __str__(self):
return f"{self.name}({self.x},{self.y})"
[world.py]:
import pygame # Add this at the top with other imports
import pickle
import random
from typing import List, Dict, Optional
from animals.human import Human
from utils.organism_factory import OrganismFactory
class World:
def __init__(self, name: str, size_x: int, size_y: int):
self.name = name
self.size_x = max(size_x, 10)
self.size_y = max(size_y, 10)
self.turn = 0
# Zmiana kolejności - pierwszy indeks to y (wiersz), drugi to x (kolumna)
self.map = [['.' for _ in range(self.size_x)] for _ in range(self.size_y)]
self.organisms = []
self.human = None
self.human_made_move = False
self.simulation_frame = None
def set_simulation_frame(self, frame):
self.simulation_frame = frame
def debug(self, message: str):
if self.simulation_frame:
self.simulation_frame.add_debug_message(f"[TURN {self.turn}] {message}")
def start(self):
print("World start initialization...")
try:
self.map = [['.' for _ in range(self.size_x)] for _ in range(self.size_y)]
# Dodaj człowieka
x, y = self.find_empty_position()
human = Human(x, y, self)
self.human = human
self.add_organism(human)
# Dodaj inne organizmy
species = ["Wolf", "Sheep", "Fox", "Turtle", "Antelope",
"Belladona", "Dandelion", "Guarana", "Grass", "Hogweed"]
for species_name in species:
count = random.randint(1, 3)
for _ in range(count):
x, y = self.find_empty_position()
organism = OrganismFactory.create_by_name(species_name, x, y, self)
self.add_organism(organism)
self.human_made_move = True
print("World initialization completed successfully")
except Exception as e:
print(f"World init failed: {str(e)}")
raise
def print_map_state(self):
print("\nCurrent map state:")
for row in self.map:
print(' '.join(row))
print()
def find_empty_position(self):
max_attempts = self.size_x * self.size_y * 2
for _ in range(max_attempts):
x = random.randint(0, self.size_x - 1)
y = random.randint(0, self.size_y - 1)
if not self.get_occupance(x, y):
return x, y
# Jeśli nie znajdzie wolnego miejsca, przeszukaj sekwencyjnie
for x in range(self.size_x):
for y in range(self.size_y):
if not self.get_occupance(x, y):
return x, y
raise Exception("No empty positions available in the world")
def add_organism(self, organism):
print(f"Adding {organism.name} at ({organism.x},{organism.y})")
self.organisms.append(organism)
x, y = organism.x, organism.y
if 0 <= y < len(self.map) and 0 <= x < len(self.map[y]):
print(f"Setting map[{y}][{x}] = {organism.symbol}")
self.map[y][x] = organism.symbol
else:
print(f"Invalid position for {organism.name}!")
def get_organism_at(self, x: int, y: int) -> Optional['Organism']:
"""Zwraca organizm na podanych współrzędnych lub None jeśli brak"""
for org in self.organisms:
if org.x == x and org.y == y and org.is_alive:
return org
return None
def next_turn(self):
print("\nStarting turn", self.turn+1)
if not self.human or not self.human.is_alive:
print("Human dead - ending game")
return False
if not self.human_made_move:
print("Human hasn't moved yet!")
return False
# Procesowanie organizmów
for org in sorted(self.organisms, key=lambda o: (-o.initiative, -o.age)):
if org.is_alive and org != self.human:
org.action()
# Aktualizacje
for org in self.organisms:
org.increase_age()
if self.human:
self.human.decrease_special_ability()
self.turn += 1
self.human_made_move = False
self.human.waiting_for_input = True
print(f"Turn {self.turn} completed")
return True
def save_to_file(self, filename: str):
with open(filename, 'wb') as f:
pickle.dump(self, f)
@staticmethod
def load_from_file(filename: str, frame) -> Optional['World']:
try:
with open(filename, 'rb') as f:
world = pickle.load(f)
world.simulation_frame = frame
return world
except Exception as e:
print(f"Error loading world: {e}")
return None
def get_occupance(self, x: int, y: int) -> bool:
return 0 <= x < self.size_x and 0 <= y < self.size_y and self.map[x][y] != '.'
def handle_human_death(self):
if self.simulation_frame:
self.simulation_frame.show_game_over()
def is_in_bounds(self, x: int, y: int) -> bool:
return 0 <= x < self.size_x and 0 <= y < self.size_y
[__init__.py]:
__all__ = ['World', 'Organism']
[animal.py]:
from __future__ import annotations
from organism import Organism
from utils.direction import Direction
import random
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from world import World
class Animal(Organism):
def __init__(self, x: int, y: int, world):
super().__init__(x, y, world)
self.symbol = 'A'
self.name = "Animal"
def action(self):
old_x, old_y = self.x, self.y # Zapisz starą pozycję
new_x, new_y = self.try_move()
# Zawsze czyść starą pozycję
self.world.map[old_x][old_y] = '.'
if self.world.get_occupance(new_x, new_y):
for other in self.world.organisms:
if other.x == new_x and other.y == new_y:
self.collision(other)
break
else:
self.move(new_x, new_y)
self.world.map[self.x][self.y] = self.symbol
def try_move(self):
while True:
direction = Direction.random()
new_x, new_y = self.x, self.y
if direction == Direction.UP and self.y > 0:
new_y -= 1
elif direction == Direction.DOWN and self.y < self.world.size_y - 1:
new_y += 1
elif direction == Direction.LEFT and self.x > 0:
new_x -= 1
elif direction == Direction.RIGHT and self.x < self.world.size_x - 1:
new_x += 1
else:
continue
return new_x, new_y
def respond_to_collision(self, other: 'Organism') -> bool:
return False
def collision(self, other: 'Organism'):
if other.symbol == self.symbol:
self.breed(other)
elif not other.respond_to_collision(self):
self.fight(other)
def fight(self, other: 'Organism'):
if self.strength >= other.strength:
other.die()
self.world.map[self.x][self.y] = '.'
self.move(other.x, other.y)
self.world.map[self.x][self.y] = self.symbol
else:
self.die()
def breed(self, other: 'Organism'):
positions = [
(self.x-1, self.y), (self.x+1, self.y),
(self.x, self.y-1), (self.x, self.y+1),
(other.x-1, other.y), (other.x+1, other.y),
(other.x, other.y-1), (other.x, other.y+1)
]
random.shuffle(positions)
for new_x, new_y in positions:
if (0 <= new_x < self.world.size_x and
0 <= new_y < self.world.size_y and
not self.world.get_occupance(new_x, new_y)):
self.add_organism(new_x, new_y)
return
# Jeśli nie znajdzie miejsca, nie rozmnaża się
def add_organism(self, x: int, y: int):
pass # To be overridden by child classes
def move(self, new_x: int, new_y: int):
# Aktualizacja mapy
self.world.map[self.y][self.x] = '.'
self.x = new_x
self.y = new_y
self.world.map[self.y][self.x] = self.symbol
[antelope.py]:
from .animal import Animal
import random
class Antelope(Animal):
def __init__(self, x: int, y: int, world):
super().__init__(x, y, world)
self.strength = 4
self.initiative = 4
self.symbol = 'A'
self.name = "Antelope"
def action(self):
super().action() # Pierwszy ruch
super().action() # Drugi ruch (antylopa porusza się 2x w turze)
def collision(self, other):
if random.randint(0, 1) == 0: # 50% szans na ucieczkę
super().collision(other)
else:
self.escape()
def find_escape_position(self):
"""Znajduje losowe sąsiednie wolne pole do ucieczki"""
directions = [
(0, 1), (1, 0), (0, -1), (-1, 0), # podstawowe kierunki
(1, 1), (1, -1), (-1, 1), (-1, -1) # przekątne (antylopa może uciekać na skos)
]
random.shuffle(directions)
for dx, dy in directions:
new_x, new_y = self.x + dx, self.y + dy
if (0 <= new_x < self.world.size_x and
0 <= new_y < self.world.size_y and
not self.world.get_occupance(new_x, new_y)):
return new_x, new_y
return self.x, self.y # jeśli nie znajdzie wolnego miejsca, zostaje
def escape(self):
"""Próbuje uciec na losowe sąsiednie wolne pole"""
new_x, new_y = self.find_escape_position()
if new_x != self.x or new_y != self.y:
self.world.map[self.x][self.y] = '.'
self.x, self.y = new_x, new_y
self.world.map[self.x][self.y] = self.symbol
self.world.debug(f"Antelope escaped to ({new_x},{new_y})")
def create_offspring(self, x, y):
return Antelope(x, y, self.world)
[fox.py]:
from .animal import Animal
import random
from utils.direction import Direction
class Fox(Animal):
def __init__(self, x: int, y: int, world):
super().__init__(x, y, world)
self.strength = 3
self.initiative = 7
self.symbol = 'F'
self.name = "Fox"
def action(self):
for _ in range(10): # Limited attempts
dx, dy = random.choice([(0,1), (1,0), (0,-1), (-1,0)])
new_x, new_y = self.x + dx, self.y + dy
if (0 <= new_x < self.world.size_x and
0 <= new_y < self.world.size_y):
other = self.world.get_organism_at(new_x, new_y)
if not other: # Wolne pole
self.move(new_x, new_y)
return
elif other and hasattr(other, 'strength') and other.strength <= self.strength:
self.collision(other)
return
def create_offspring(self, x, y):
return Fox(x, y, self.world)
[human.py]:
from animals.animal import Animal
from utils.human_direction import HumanDirection
import pygame
class Human(Animal):
def __init__(self, x: int, y: int, world):
super().__init__(x, y, world)
self._base_strength = 5
self._strength = self._base_strength
self.initiative = 4
self.symbol = 'C'
self.name = "Human"
self.waiting_for_input = True
self.special_ability_active = False
self.ability_cooldown = 0
self.ability_duration = 0
self.is_human = True
self.is_alive = True
print(f"Human created at ({x},{y})")
@property
def strength(self):
return self._strength + (5 if self.special_ability_active else 0)
@strength.setter
def strength(self, value):
self._strength = value
def die(self):
if not self.is_alive:
return
print(f"Human dying at ({self.x},{self.y})")
self.is_alive = False
self.world.map[self.x][self.y] = '.'
self.world.handle_human_death()
def collision(self, other: 'Organism'):
print(f"Collision between Human and {other.name}")
if other.respond_to_collision(self):
return
if self.strength >= other.strength:
print(f"Human defeats {other.name}")
other.die()
self.x, self.y = other.x, other.y
else:
print(f"Human defeated by {other.name}")
self.die()
def activate_special_ability(self):
if self.ability_cooldown <= 0:
self.special_ability_active = True
self.ability_duration = 5
self.ability_cooldown = 10
self.world.debug("Human activated special ability!")
def decrease_special_ability(self):
if self.special_ability_active:
self.ability_duration -= 1
if self.ability_duration <= 0:
self.special_ability_active = False
self.world.debug("Human special ability expired")
if self.ability_cooldown > 0:
self.ability_cooldown -= 1
def can_use_special_ability(self):
return self.ability_cooldown <= 0 and not self.special_ability_active
def action(self):
self.waiting_for_input = True
self.world.debug("Your turn! Move with WASD")
def handle_player_input(self, dx, dy):
if not self.waiting_for_input:
print("Human not waiting for input!")
return False
new_x = self.x + dx
new_y = self.y + dy
if not self.world.is_in_bounds(new_x, new_y):
print("Move outside bounds!")
return False
print(f"Attempting move from ({self.x},{self.y}) to ({new_x},{new_y})")
# Clear old position
self.world.map[self.y][self.x] = '.'
# Handle collision or move
other = self.world.get_organism_at(new_x, new_y)
if other:
self.collision(other)
else:
self.x, self.y = new_x, new_y
# Update new position
self.world.map[self.y][self.x] = self.symbol
self.waiting_for_input = False
self.world.human_made_move = True
print(f"Human moved to ({self.x},{self.y})")
return True
[sheep.py]:
from .animal import Animal
class Sheep(Animal):
def __init__(self, x: int, y: int, world):
super().__init__(x, y, world)
self.strength = 4
self.initiative = 4
self.symbol = 'S'
self.name = "Sheep"
def create_offspring(self, x, y):
return Sheep(x, y, self.world)
[turtle.py]:
from .animal import Animal
import random
class Turtle(Animal):
def __init__(self, x: int, y: int, world):
super().__init__(x, y, world)
self.strength = 2
self.initiative = 1
self.symbol = 'T'
self.name = "Turtle"
def action(self):
if random.randint(0, 3) == 0: # 25% szans na ruch
super().action()
def respond_to_collision(self, other):
return other.strength < 5 # Odbija ataki słabsze niż 5
def create_offspring(self, x, y):
return Turtle(x, y, self.world)
[wolf.py]:
from .animal import Animal
class Wolf(Animal):
def __init__(self, x: int, y: int, world):
super().__init__(x, y, world)
self.strength = 9
self.initiative = 5
self.symbol = 'W'
self.name = "Wolf"
def create_offspring(self, x, y):
return Wolf(x, y, self.world)
[__init__.py]:
__all__ = ['Animal', 'Wolf', 'Sheep', 'Fox', 'Turtle', 'Antelope', 'Human']
[animal.cpython-312.pyc]:
[PLIK BINARNY LUB BRAK UPRAWNIEŃ]
[antelope.cpython-312.pyc]:
[PLIK BINARNY LUB BRAK UPRAWNIEŃ]
[fox.cpython-312.pyc]:
[PLIK BINARNY LUB BRAK UPRAWNIEŃ]
[human.cpython-312.pyc]:
[PLIK BINARNY LUB BRAK UPRAWNIEŃ]
[sheep.cpython-312.pyc]:
[PLIK BINARNY LUB BRAK UPRAWNIEŃ]
[turtle.cpython-312.pyc]:
[PLIK BINARNY LUB BRAK UPRAWNIEŃ]
[wolf.cpython-312.pyc]:
[PLIK BINARNY LUB BRAK UPRAWNIEŃ]
[__init__.cpython-312.pyc]:
[PLIK BINARNY LUB BRAK UPRAWNIEŃ]
[custom_grid.py]:
import pygame
from typing import List, Tuple, Optional
class CustomGrid:
def __init__(self, rows, cols, world, screen):
self.rows = rows
self.cols = cols
self.world = world
self.screen = screen
self.grid_data = [['.' for _ in range(cols)] for _ in range(rows)]
self.color_data = [[(200, 200, 200) for _ in range(cols)] for _ in range(rows)]
self.selected_point = None
self._init_colors()
try:
self.font = pygame.font.SysFont('Arial', 24)
except:
try:
self.font = pygame.font.SysFont(None, 24)
except:
self.font = pygame.Font(None, 24)
def _init_colors(self):
self.color_map = {
'.': (240, 240, 240), # Puste pole
'W': (101, 67, 33), # Wilk
'S': (255, 255, 255), # Owca
'F': (255, 165, 0), # Lis
'T': (0, 128, 0), # Żółw
'A': (255, 215, 0), # Antylopa
'C': (220, 20, 60), # Człowiek
'G': (144, 238, 144), # Trawa
'D': (255, 255, 0), # Mlecz
'P': (255, 105, 180), # Guarana
'B': (75, 0, 130), # Wilcze jagody
'H': (139, 0, 0) # Barszcz
}
def update_grid(self):
try:
for y in range(self.rows):
for x in range(self.cols):
# Odwrócona kolejność indeksów - y pierwsze
if y < len(self.world.map) and x < len(self.world.map[y]):
symbol = self.world.map[y][x]
self.grid_data[y][x] = symbol
self.color_data[y][x] = self.color_map.get(symbol, (200, 200, 200))
except Exception as e:
print(f"Update grid error: {e}")
raise
def draw(self, screen_rect=None):
try:
if screen_rect is None:
screen_rect = pygame.Rect(0, 0, self.screen.get_width(), self.screen.get_height())
cell_width = screen_rect.width // self.cols
cell_height = screen_rect.height // self.rows
for y in range(self.rows):
for x in range(self.cols):
x_pos = screen_rect.x + x * cell_width
y_pos = screen_rect.y + y * cell_height
# Rysowanie tła
pygame.draw.rect(
self.screen,
self.color_data[y][x],
(x_pos, y_pos, cell_width, cell_height)
)
# Obramowanie
pygame.draw.rect(
self.screen,
(100, 100, 100),
(x_pos, y_pos, cell_width, cell_height),
1
)
# Symbol organizmu
symbol = str(self.grid_data[y][x])
if symbol != '.':
text_color = (0, 0, 0)
if symbol == 'C': # Człowiek na czerwonym tle
text_color = (255, 255, 255)
text = self.font.render(symbol, True, text_color)
text_rect = text.get_rect(
center=(x_pos + cell_width//2, y_pos + cell_height//2))
self.screen.blit(text, text_rect)
except Exception as e:
print(f"Draw grid error: {e}")
raise
def set_selected_point(self, x: int, y: int):
if 0 <= x < self.rows and 0 <= y < self.cols:
self.selected_point = (x, y)
def clear_selection(self):
self.selected_point = None
[simulation_frame.py]:
import pygame
from pygame.locals import *
from typing import Optional
from gui.custom_grid import CustomGrid
class SimulationFrame:
def __init__(self, rows: int, cols: int, world: 'World'):
pygame.init()
self.rows = rows
self.cols = cols
self.world = world
self.human = world.human
# Inicjalizacja ekranu z większą przestrzenią na UI
self.cell_size = 40 # Zwiększona komórka dla lepszej widoczności
self.grid_width = cols * self.cell_size
self.grid_height = rows * self.cell_size
self.screen_width = self.grid_width + 400 # Więcej miejsca na sidebar
self.screen_height = self.grid_height + 100
self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))
pygame.display.set_caption("World Simulation")
# Inicjalizacja gridu
self.grid = CustomGrid(rows, cols, world, self.screen)
# UI i debug
self.clock = pygame.time.Clock()
self.running = True
self.debug_messages = []
# Inicjalizacja czcionki z fallbackami
try:
self.font = pygame.font.SysFont('Arial', 18)
self.button_font = pygame.font.SysFont('Arial', 16)
except:
try:
self.font = pygame.font.SysFont(None, 18)
self.button_font = pygame.font.SysFont(None, 16)
except:
self.font = pygame.Font(None, 18)
self.button_font = pygame.Font(None, 16)
# Przyciski
self._init_buttons()
# Wymuś pierwsze renderowanie
self._force_redraw()
def _init_buttons(self):
button_y = self.grid_height + 20
button_params = [
("Next Turn", (50, button_y), (120, 40)),
("Special Ability", (200, button_y), (150, 40)),
("Save Game", (380, button_y), (120, 40)),
("Load Game", (530, button_y), (120, 40))
]
self.buttons = []
for text, pos, size in button_params:
btn_rect = pygame.Rect(pos[0], pos[1], size[0], size[1])
self.buttons.append({
'rect': btn_rect,
'text': text,
'active': True
})
def _force_redraw(self):
self.grid.update_grid()
self._draw()
pygame.display.flip()
def _handle_events(self):
for event in pygame.event.get():
if event.type == QUIT:
self.running = False
elif event.type == KEYDOWN:
self._handle_keyboard(event)
elif event.type == MOUSEBUTTONDOWN:
self._handle_mouse_click()
def _handle_keyboard(self, event):
if not self.human or not self.human.is_alive:
return
if event.key == K_r and self.human.can_use_special_ability():
self.human.activate_special_ability()
self.add_debug_message("Special ability activated!")
return
# Obsługa WASD
direction_handled = False
if event.key == K_w: # Góra
direction_handled = self.human.handle_player_input(0, -1)
elif event.key == K_s: # Dół
direction_handled = self.human.handle_player_input(0, 1)
elif event.key == K_a: # Lewo
direction_handled = self.human.handle_player_input(-1, 0)
elif event.key == K_d: # Prawo
direction_handled = self.human.handle_player_input(1, 0)
if direction_handled:
self.add_debug_message(f"Human moved to ({self.human.x},{self.human.y})")
self._force_redraw() # Wymuś natychmiastowe odświeżenie
def _handle_mouse_click(self):
pos = pygame.mouse.get_pos()
for btn in self.buttons:
if btn['rect'].collidepoint(pos):
if btn['text'] == "Next Turn":
self._handle_next_turn()
def _handle_next_turn(self):
if self.world.next_turn():
self.add_debug_message(f"Turn {self.world.turn} completed")
else:
self.add_debug_message("Cannot proceed - human needs to move first")
def _draw(self):
# Tło
self.screen.fill((240, 240, 240))
# Aktualizuj i rysuj grid
self.grid.update_grid()
grid_rect = pygame.Rect(0, 0, self.grid_width, self.grid_height)
self.grid.draw(grid_rect)
# UI
self._draw_sidebar()
self._draw_buttons()
pygame.display.flip() # Wymuś odświeżenie
def _draw_sidebar(self):
sidebar_rect = pygame.Rect(
self.grid_width + 5,
0,
self.screen_width - self.grid_width - 10,
self.grid_height
)
pygame.draw.rect(self.screen, (220, 220, 220), sidebar_rect)
# Debug messages
y_pos = 10
for msg in self.debug_messages[-15:]: # Ostatnie 15 wiadomości
try:
text = self.font.render(str(msg), True, (0, 0, 0))
self.screen.blit(text, (self.grid_width + 10, y_pos))
y_pos += 25
except Exception as e:
print(f"Error rendering debug text: {e}")
def _draw_buttons(self):
for btn in self.buttons:
color = (100, 200, 100) if btn['active'] else (200, 200, 200)
pygame.draw.rect(self.screen, color, btn['rect'])
pygame.draw.rect(self.screen, (0, 0, 0), btn['rect'], 2)
text = self.button_font.render(btn['text'], True, (0, 0, 0))
text_rect = text.get_rect(center=btn['rect'].center)
self.screen.blit(text, text_rect)
def add_debug_message(self, message: str):
self.debug_messages.append(f"[TURN {self.world.turn}] {message}")
print(message) # Również wypisz w konsoli
[__init__.py]:
__all__ = ['CustomGrid', 'SimulationFrame']
[custom_grid.cpython-312.pyc]:
[PLIK BINARNY LUB BRAK UPRAWNIEŃ]
[simulation_frame.cpython-312.pyc]:
[PLIK BINARNY LUB BRAK UPRAWNIEŃ]
[__init__.cpython-312.pyc]:
[PLIK BINARNY LUB BRAK UPRAWNIEŃ]
[belladona.py]:
from .plant import Plant
class Belladona(Plant):
def __init__(self, x: int, y: int, world):
super().__init__(x, y, world)
self.strength = 99
self.symbol = 'B'
self.name = "Belladona"
self.chance_of_spread = 5
def respond_to_collision(self, other):
other.die() # Zabija każdego kto ją zje
return True
def create_offspring(self, x, y):
return Belladona(x, y, self.world)
[dandelion.py]:
from .plant import Plant
class Dandelion(Plant):
def __init__(self, x: int, y: int, world):
super().__init__(x, y, world)
self.symbol = 'D'
self.name = "Dandelion"
self.chance_of_spread = 30
def action(self):
for _ in range(3): # 3 próby rozprzestrzenienia
super().action()
def create_offspring(self, x, y):
return Dandelion(x, y, self.world)
[grass.py]:
from .plant import Plant
class Grass(Plant):
def __init__(self, x: int, y: int, world):
super().__init__(x, y, world)
self.symbol = 'G'
self.name = "Grass"
self.chance_of_spread = 20
def create_offspring(self, x, y):
return Grass(x, y, self.world)
[guarana.py]:
from .plant import Plant
class Guarana(Plant):
def __init__(self, x: int, y: int, world):
super().__init__(x, y, world)
self.symbol = 'P'
self.name = "Guarana"
self.chance_of_spread = 15
def respond_to_collision(self, other):
other.strength += 3 # Zwiększa siłę zjadacza
return super().respond_to_collision(other)
def create_offspring(self, x, y):
return Guarana(x, y, self.world)
[hogweed.py]:
from .plant import Plant
class Hogweed(Plant):
def __init__(self, x: int, y: int, world):
super().__init__(x, y, world)
self.strength = 10
self.symbol = 'H'
self.name = "Hogweed"
self.chance_of_spread = 10
def action(self):
super().action()
self.kill_nearby_animals()
def kill_nearby_animals(self):
for dx, dy in [(0,1), (1,0), (0,-1), (-1,0)]:
x, y = self.x + dx, self.y + dy
if 0 <= x < self.world.size_x and 0 <= y < self.world.size_y:
org = self.world.get_organism_at(x, y)
if org and hasattr(org, 'strength'): # Czy to zwierzę
org.die()
def create_offspring(self, x, y):
return Hogweed(x, y, self.world)
[plant.py]:
from organism import Organism
from abc import ABC, abstractmethod
import random
class Plant(Organism):
def __init__(self, x: int, y: int, world):
super().__init__(x, y, world)
self.initiative = 0
self.chance_of_spread = 20 # Domyślna szansa na rozprzestrzenienie
def action(self):
if random.randint(0, 99) < self.chance_of_spread:
self.spread()
def spread(self):
for _ in range(10): # Limited attempts
dx, dy = random.choice([(0,1), (1,0), (0,-1), (-1,0)])
x, y = self.x + dx, self.y + dy
if (0 <= x < self.world.size_x and
0 <= y < self.world.size_y and
not self.world.get_occupance(x, y)):
offspring = self.create_offspring(x, y)
self.world.add_organism(offspring)
return