Добавил систему задач для юнитов, она реализована в методе update класса Creature. Подчистил код, пофиксил по мелочам баги. Остался ещё техдолг Егору и задачи из main.

This commit is contained in:
shiva404
2026-03-05 16:35:08 +03:00
parent dafa95989f
commit 45f2c71cb8
6 changed files with 266 additions and 95 deletions

View File

@@ -1,5 +1,5 @@
from common import os, json, uuid, deepcopy, random
from common import dataclass, field
from common import dataclass, field, partial
from common import pygame, pygame_gui
import eb_objects
import eb_terrain_objects
@@ -46,7 +46,8 @@ class Map:
cam_x: int = 0
cam_y: int = 0
cell_dist: int = 1
#effects[]
#action_time_multiplier
def __post_init__(self):
@@ -55,7 +56,7 @@ class Map:
buff = json.load(file)
for line in range(len(buff)):
self.cells[line] = []
for cell in buff[str(line)]:
for col, cell in enumerate(buff[str(line)]):
final_cell = Cell(cell_classes[cell["terrain_obj"]["sprite_name"]](**cell["terrain_obj"]))
if cell["item_obj"]:
@@ -63,6 +64,7 @@ class Map:
if cell["creature_obj"]:
final_cell.creature_obj = cell_classes[cell["creature_obj"]["sprite_name"]](**cell["creature_obj"])
final_cell.creature_obj.grid_pos = (line, col)
self.cells[line].append(final_cell)
@@ -90,6 +92,7 @@ class Map:
setattr(source_cell, type, None)
setattr(dest_cell, type, obj)
#obj.grid_pos = goal
return True
def get_cell_at_mouse(self, mouse_pos):
@@ -113,7 +116,7 @@ class Map:
def update_map(self, time_delta):
for j in range(len(self.cells)):
for cell in self.cells[j]:
if cell.creature_obj and cell.creature_obj.current_target:
if cell.creature_obj:
cell.creature_obj.update(time_delta, self.cell_size, self) # self!
def draw_map(self, screen, current_frame, grid=True):
@@ -293,8 +296,17 @@ class Engine:
mem_before = process.memory_info().rss / 1024
NUM_ELVES = 1000
NUM_ELVES = 2000
elf_count = 0
space_pressed = False
spawn = False
def spawn_elf():
elf = eb_objects.Creature(id=f"elf_{random.randint(1000,9999)}", name="Elf", sprite_name="elf_watching", grid_pos = (0, 0))
r_move_short = eb_objects.Action(sprite_name="elf_watching", func = partial(elf.patrol, easy_map.cells, 3), duration = 0.01)
r_move_long = eb_objects.Action(sprite_name="elf_watching", func = partial(elf.move_rand, easy_map.cells, 0, 99), duration = 0.01)
elf.tasks.append([r_move_short, r_move_short, r_move_short, r_move_short, r_move_short, r_move_long])
easy_map.cells[0][0].creature_obj = elf
while running:
@@ -305,12 +317,29 @@ class Engine:
mem_after = process.memory_info().rss / 1024
print(f"Leak: {mem_after - mem_before:.1f} KB per 1000 frames")
if global_counter % 100 == 0 and spawn == True:
spawn_elf()
elf_count += 1
# poll for events
# pygame.QUIT event means the user clicked X to close your window
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and elf_count < NUM_ELVES and not space_pressed:
#spawn_elf()
#elf_count += 1
if spawn == False:
spawn = True
else: spawn = False
space_pressed = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
space_pressed = False
if event.type == pygame.MOUSEWHEEL:
scroll_y = event.y
@@ -372,41 +401,39 @@ class Engine:
if keys[pygame.K_d]:
easy_map.cam_x -= self.camera_step
#if keys[pygame.K_q]:
# easy_map.scale += self.scale_step
# self.spr_scale += self.scale_step
# self.scale_sprites()
#if keys[pygame.K_e] and easy_map.scale >= self.scale_step:
# easy_map.scale -= self.scale_step
# self.spr_scale -= self.scale_step
# self.scale_sprites()
if keys[pygame.K_SPACE] and elf_count < NUM_ELVES:
# Находим свободные клетки
# ★ МАССОВЫЙ СПАВН 50 эльфов
free_cells = []
for j in range(len(easy_map.cells)): # ★ ЛИМИТ строк ★
for i in range(len(easy_map.cells[j])): # ★ ЛИМИТ колонок ★
cell = easy_map.cells[j][i]
if (cell.creature_obj is None and
cell.terrain_obj and
cell.terrain_obj.sprite_name == "grass_small"):
free_cells.append((j, i))
spawn_count = min(50, len(free_cells)) # ★ Не больше свободных клеток ★
for _ in range(spawn_count):
row, col = random.choice(free_cells)
elf = eb_objects.Creature(id=f"elf_{random.randint(1000,9999)}", name="Elf", sprite_name="elf_watching")
easy_map.cells[row][col].creature_obj = elf
# ★ БЕЗОПАСНЫЙ выбор цели ★
possible_targets = [c for c in free_cells if c != (row, col)]
if possible_targets:
target_cell = random.choice(possible_targets)
elf.move(easy_map.cells, (row, col), target_cell)
free_cells.remove((row, col)) # Убираем занятые клетки
if keys[pygame.K_q]:
easy_map.scale += self.scale_step
self.spr_scale += self.scale_step
self.scale_sprites()
if keys[pygame.K_e] and easy_map.scale >= self.scale_step:
easy_map.scale -= self.scale_step
self.spr_scale -= self.scale_step
self.scale_sprites()
# # Находим свободные клетки
# # ★ МАССОВЫЙ СПАВН 50 эльфов ★
# free_cells = []
# for j in range(len(easy_map.cells)): # ★ ЛИМИТ строк
# for i in range(len(easy_map.cells[j])): # ★ ЛИМИТ колонок ★
# cell = easy_map.cells[j][i]
# if (cell.creature_obj is None and
# cell.terrain_obj and
# cell.terrain_obj.sprite_name == "grass_small"):
# free_cells.append((j, i))
#
# spawn_count = min(50, len(free_cells)) # ★ Не больше свободных клеток ★
# for _ in range(spawn_count):
# row, col = random.choice(free_cells)
# elf = eb_objects.Creature(id=f"elf_{random.randint(1000,9999)}", name="Elf", sprite_name="elf_watching")
# easy_map.cells[row][col].creature_obj = elf
#
# # ★ БЕЗОПАСНЫЙ выбор цели ★
# possible_targets = [c for c in free_cells if c != (row, col)]
# if possible_targets:
# target_cell = random.choice(possible_targets)
# elf.move(easy_map.cells, (row, col), target_cell)
#
# free_cells.remove((row, col)) # Убираем занятые клетки
@@ -437,7 +464,7 @@ class Engine:
if cell_coords:
#print(f"Движение: {active_cell} -> {cell_coords}")
easy_map.cells[active_cell[0]][active_cell[1]].creature_obj.move(
easy_map.cells, active_cell, cell_coords)
easy_map.cells, cell_coords)
if keys[pygame.K_ESCAPE]:
running = False
@@ -453,6 +480,6 @@ class Engine:
if global_counter % 10 == 0:
current_fps = clock.get_fps()
print(f"Current FPS: {current_fps:.2f}")
print(f"Elves count: {elf_count} - Current FPS: {current_fps:.2f}")
pygame.quit()