Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixxed chrashes caused by detectors #91

Merged
merged 1 commit into from
Feb 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions bot/HarstemsAunt/build_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

# pylint: disable=E0402
from .army_group import ArmyGroup
from .common import ALL_STRUCTURES,INITIAL_TECH,DT_TIMING
from .common import ALL_STRUCTURES,INITIAL_TECH,DT_TIMING, DEBUG,DEBUG_FONT_SIZE

class InstructionType(Enum):
"""Enumeration containing InstructionTypes """
Expand Down Expand Up @@ -260,9 +260,9 @@ async def update(self):
group.requested_units.remove(requested_unit)

self.bot.client.debug_text_screen(f"{self.next_instruction()} instruction {self.step}", \
(0.01, 0.15), color=(255,255,255), size=15)
(0.01, 0.15), color=(255,255,255), size=DEBUG_FONT_SIZE)
self.bot.client.debug_text_screen(f"next struct in Buffer: {self.get_next_in_buffer()}", \
(0.01, 0.20), color=(255,255,255), size=15)
(0.01, 0.20), color=(255,255,255), size=DEBUG_FONT_SIZE)

def debug_build_pos(self, pos:Union[Point2, Point3]):
"""debug method to show the current build pos """
Expand Down
3 changes: 2 additions & 1 deletion bot/HarstemsAunt/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
from sc2.ids.unit_typeid import UnitTypeId

SECTORS: int = 10
DEBUG: bool = False
DEBUG: bool = True
DEBUG_FONT_SIZE = 7
RUN_BY_SIZE: int = 4
DT_TIMING: float = 480
MIN_SHIELD_AMOUNT: float = 0.5
Expand Down
39 changes: 23 additions & 16 deletions bot/HarstemsAunt/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from .pathing import Pathing
from .army_group import ArmyGroup
from .map_sector import MapSector
from .common import WORKER_IDS,SECTORS,ATTACK_TARGET_IGNORE,DEBUG,logger
from .common import WORKER_IDS,SECTORS,ATTACK_TARGET_IGNORE,DEBUG,DEBUG_FONT_SIZE, logger
from .speedmining import get_speedmining_positions,split_workers, micro_worker


Expand All @@ -43,14 +43,13 @@ class HarstemsAunt(BotAI):
# Ground Units
zealots: Zealot
stalkers: Stalkers

# Scouting Units
observer : Observer

def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.name = "HarstemsAunt"
self.version = "1.1 alpha"
self.version = "1.1_dev"
self.race:Race = Race.Protoss

self.base_count = 0
Expand Down Expand Up @@ -128,9 +127,9 @@ async def on_before_start(self) -> None:
# Create Folders to save data for analysis
self.create_folders()

if DEBUG:
await self.client.debug_fast_build()
await self.client.debug_all_resources()
# if DEBUG:
# await self.client.debug_fast_build() Buildings take no time
# await self.client.debug_all_resources() Free minerals and gas

# set Edge Points
top_right = Point2((self.game_info.playable_area.right, self.game_info.playable_area.top))
Expand All @@ -143,7 +142,7 @@ async def on_before_start(self) -> None:
for y in range(SECTORS):
upper_left: Point2 = Point2((0+(sector_width*x), 0+bottom_right.y+(sector_width*(y))))
lower_right: Point2 = Point2((0+(sector_width*(x+1)),0+bottom_right.y+(sector_width*(y+1))))
logger.info(f"upper_left {upper_left} lower_right {lower_right}")
# logger.info(f"upper_left {upper_left} lower_right {lower_right}")
sector: MapSector = MapSector(self, upper_left, lower_right)
self.map_sectors.append(sector)

Expand All @@ -161,11 +160,17 @@ async def on_start(self) -> None:

await self.chat_send(self.greeting)

if DEBUG:
await self.client.debug_show_map()
await self.client.debug_create_unit([[UnitTypeId.RAVEN, 5, self._game_info.map_center, 1]])
await self.client.debug_create_unit([[UnitTypeId.RAVEN, 5, self._game_info.map_center, 2]])


for sector in self.map_sectors:
sector.build_sector()
split_workers(self)

initial_army_group:ArmyGroup = ArmyGroup(self, "Peter", [],[],pathing=self.pathing)
initial_army_group:ArmyGroup = ArmyGroup(self, "HA_alpha", [],[],pathing=self.pathing)
#run_by_group:ArmyGroup = ArmyGroup(self, [], [], self.pathing, GroupTypeId.RUN_BY)
self.army_groups.append(initial_army_group)
#self.army_groups.append(run_by_group)
Expand All @@ -182,10 +187,10 @@ async def on_step(self, iteration:int):
color = (0, 0, 255)
else:
color = (0, 255, 0)
self.client.debug_text_screen(f"{labels[i]}: {value}", \
(0, 0.025+(i*0.025)), color=color, size=20)
self.client.debug_text_screen(f"{labels[i]}: {round(value,3)}", \
(0, 0.025+(i*0.025)), color=color, size=DEBUG_FONT_SIZE)

threads: list = []
threads: ist = []
for i, sector in enumerate(self.map_sectors):
t_0 = threading.Thread(target=sector.update())
threads.append(t_0)
Expand All @@ -209,18 +214,17 @@ async def on_step(self, iteration:int):
await self.chat_send("Stop hiding and fight like a honorable ... \
ähm... Robot?\ndo computers have honor ?")


self.pathing.update(iteration)

for j, group in enumerate(self.army_groups):
await group.update(self.get_attack_target)
self.client.debug_text_screen(f"{group.GroupTypeId}: {group.attack_target}",\
(.25+(j*0.25), 0.025), color=(255,255,255), size=20)
(.25+(j*0.25), 0.025), color=(255,255,255), size=DEBUG_FONT_SIZE)
self.client.debug_text_screen(f"Supply:{group.supply}\
Enemysupply:{group.enemy_supply_in_proximity}",\
(.25+(j*0.27), 0.05), color=(255,255,255), size=20)
(.25+(j*0.27), 0.05), color=(255,255,255), size=DEBUG_FONT_SIZE)
self.client.debug_text_screen(f"requested:{group.requested_units}",\
(.25+(j*0.27), 0.075), color=(255,255,255), size=20)
(.25+(j*0.27), 0.075), color=(255,255,255), size=DEBUG_FONT_SIZE)

if self.townhalls and self.units:
self.transfer_from: List[Unit] = []
Expand Down Expand Up @@ -254,7 +258,8 @@ async def on_step(self, iteration:int):
return

if self.last_tick == 0:
await self.chat_send(f"GG, you are probably a hackcheating smurf cheat hacker anyway also \
await self.chat_send\
(f"GG, you are probably a hackcheating smurf cheat hacker anyway also\
{self.enemy_race} is IMBA")
self.last_tick = iteration
elif self.last_tick == iteration - 120:
Expand Down Expand Up @@ -303,6 +308,7 @@ async def on_enemy_unit_left_vision(self, unit_tag:int):
pass

async def on_unit_created(self, unit:Unit) -> None:

""" Coroutine that gets called when Unit is created
- adds created Units to the ArmyGroup

Expand Down Expand Up @@ -383,3 +389,4 @@ async def on_end(self,game_result:Result):
csv_writer.writerow(data)

await self.client.leave()

29 changes: 16 additions & 13 deletions bot/HarstemsAunt/pathing.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
from map_analyzer import MapData
from .common import ALL_STRUCTURES, INFLUENCE_COSTS, logger

RANGE_BUFFER: float = 2.00
RANGE_BUFFER: float = 2.22

class Pathing:
""" Pathing class """
def __init__(self, bot:BotAI, debug:bool, fade_rate:float = 3.0) -> None:
self.bot: BotAI = bot
self.debug: bool = debug
Expand All @@ -26,29 +27,29 @@ def __init__(self, bot:BotAI, debug:bool, fade_rate:float = 3.0) -> None:
self.ground_grid: np.ndarray = self.map_data.get_pyastar_grid()
self.detection_grid: np.ndarray = self.map_data.get_pyastar_grid()
self.air_grid: np.ndarray = self.map_data.get_clean_air_grid()
self.influence_fade_rate: float = fade_rate
self.influence_fade_rate:float = fade_rate

def update(self, iteration) -> None:

""" runs every frame """
last_ground_grid:np.ndarray = self.ground_grid
last_air_grid:np.ndarray = self.air_grid
last_detection_grid: np.ndarray = self.detection_grid
last_detection_grid:np.ndarray = self.detection_grid

last_ground_grid[last_ground_grid != 0] /= self.influence_fade_rate
last_air_grid[last_air_grid != 0] /= self.influence_fade_rate
last_detection_grid[last_detection_grid != 0] /=self.influence_fade_rate
#last_detection_grid[last_detection_grid != 0] /=self.influence_fade_rate

self.ground_grid = self.map_data.get_pyastar_grid() + last_ground_grid
self.air_grid = self.map_data.get_clean_air_grid() + last_air_grid
self.detection_grid = self.map_data.get_pyastar_grid() + last_detection_grid
#self.detection_grid = self.map_data.get_pyastar_grid() + last_detection_grid

for unit in self.bot.all_enemy_units:
if unit.type_id in ALL_STRUCTURES:
self._add_structure_influence(unit)
else:
self._add_unit_influence(unit)

self.add_positional_costs()
# self.add_positional_costs()

#if not iteration%100:
#self.save_plot(iteration)
Expand Down Expand Up @@ -103,7 +104,7 @@ def find_path_next_point(
def is_position_safe(
grid: np.ndarray,
position: Point2,
weight_safety_limit: float = 1.0,
weight_safety_limit: float = 1.0
) -> bool:
"""
Checks if the current position is dangerous by
Expand Down Expand Up @@ -154,11 +155,11 @@ def _add_unit_influence(self, enemy: Unit) -> None:
)

if enemy.is_detector:
(self.detection_grid) = self._add_cost_to_multiple_grids(
(self.detection_grid) = self._add_cost(
enemy.position,
12,
enemy.detect_range + RANGE_BUFFER,
[self.detection_grid]
self.detection_grid
)

def _add_structure_influence(self, structure: Unit) -> None:
Expand Down Expand Up @@ -234,7 +235,7 @@ def _add_cost_to_multiple_grids(
return grids

#TODO: #36 Add weights to points close to the edges, and points on Ramps
def add_positional_costs(self):
def _add_positional_costs(self):
pass

def save_plot(self, iteration:int):
Expand All @@ -243,10 +244,12 @@ def save_plot(self, iteration:int):
influence_map = self.ground_grid
fig, ax = plt.subplots()
plt.imshow(influence_map, cmap='jet')
plt.scatter(x_positions, y_positions, color='green', marker='x', s=10)
plt.scatter(x_positions, y_positions, color='green', marker='x', s=1)
plt.grid(True)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title('Influence Map')
plt.plot()
plt.savefig(f"{self.bot.data_path}/influence_map_at_{iteration}.png")
plt.savefig(f"{self.bot.data_path}/influence_{iteration}.png")


11 changes: 10 additions & 1 deletion bot/Unit_Classes/Immortal.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
"""make linter shut up"""
# pylint: disable=C0103
# pylint: disable=E0401

from sc2.unit import Unit
from sc2.units import Units
from Unit_Classes.baseClassGround import BaseClassGround


class Immortals(BaseClassGround):
""" Extension of BaseClassGround """
""" Extension of BaseClassGround """

async def handle_attackers(self, units: Units, attack_targer: Point2) -> None:
"""
Handles Attackers
"""

1 change: 1 addition & 0 deletions bot/Unit_Classes/baseClassGround.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,4 @@ def pick_enemy_target(enemies: Units, attacker:Unit) -> Unit:
enemies,
key=lambda e: (e.health + e.shield, e.tag),
)

7 changes: 6 additions & 1 deletion readME.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,12 @@ We tried to get a bot to play like Harstem by scanning the brain of his Aunt - s
<details>
<summary>Version 1.1</summary>

### Currently under development
#### Currently under development

#### Version 1.1.0
- reworked build order
- reworked unit Movement & targeting
- fixxed various bugs and crashes

</details>

Expand Down