Skip to content
Merged
Show file tree
Hide file tree
Changes from 36 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
9830868
docs: updated training log after run n1
pallaresrod Jun 27, 2026
dbabe7d
docs: updated command parametes
pallaresrod Jun 27, 2026
c033ca2
feat: evaluation parameters
pallaresrod Jun 27, 2026
66c14b7
del: parameters of configs that are now being random for better training
pallaresrod Jun 27, 2026
ecdd6b7
fix: path to save models
pallaresrod Jun 27, 2026
538e14b
feat: evaluations results r2
pallaresrod Jun 27, 2026
48f708f
docs: update after run n3
pallaresrod Jun 27, 2026
2fd3a6c
fix: reward system. excess food collection gives 0.0 reward
pallaresrod Jun 27, 2026
ece8401
feat: added more info
pallaresrod Jun 27, 2026
2ed0075
docs: update after run n4
pallaresrod Jun 27, 2026
40d0dee
docs: update after run n5
pallaresrod Jun 27, 2026
fdb3866
docs: separated plan from log
pallaresrod Jun 27, 2026
2999009
docs: removed sum of timestps
pallaresrod Jun 27, 2026
44fa218
docs: update after run n6
pallaresrod Jun 27, 2026
cb89b31
docs: update after run n8
pallaresrod Jun 27, 2026
ac16607
fix: tick acceleration
pallaresrod Jun 27, 2026
ed25237
docs: update after run n9
pallaresrod Jun 27, 2026
864c0f6
fix: broadcasting problems
pallaresrod Jun 27, 2026
b23052a
docs: update after run n11
pallaresrod Jun 27, 2026
db9361a
docs: update after run n12
pallaresrod Jun 27, 2026
6597ac6
fix: overwrote the redundant food count copy to store the teammate's …
pallaresrod Jun 27, 2026
deee911
fix: understanding encantation
pallaresrod Jun 27, 2026
cb8834e
docs: update after run n13
pallaresrod Jun 27, 2026
09678c4
fix: penalty for not going towards broadcast
pallaresrod Jun 27, 2026
8f75b59
docs: update after run n14
pallaresrod Jun 27, 2026
ff3ef66
docs: update after run n14
pallaresrod Jun 27, 2026
6460d71
fix: take food reward
pallaresrod Jun 27, 2026
616952e
docs: update after run n15
pallaresrod Jun 27, 2026
09f10f5
fix: 50 episodes in eval, +2 reward for taking food
pallaresrod Jun 28, 2026
0911c30
docs: update after run n16
pallaresrod Jun 28, 2026
fa7e2f4
fix: hybrid ai
pallaresrod Jun 28, 2026
a9c3832
chore: updated gitignore
pallaresrod Jun 28, 2026
d5a1386
feat: training results
pallaresrod Jun 28, 2026
e165759
docs: update after run n20
pallaresrod Jun 28, 2026
d2eb1f0
feat: updates after run 23
pallaresrod Jun 28, 2026
6ee73a6
docs: update after run n24
pallaresrod Jun 28, 2026
c2d6938
feat: 2 best models
pallaresrod Jun 28, 2026
5543eb6
Merge branch 'main' into 322-feat-broadcast-logic-ai-heuristic
GerardPolloRebozado Jun 28, 2026
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
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -148,5 +148,3 @@ devenv.local.yaml

# pre-commit
.pre-commit-config.yaml

results
859 changes: 801 additions & 58 deletions ai/docs/training_log.md

Large diffs are not rendered by default.

49 changes: 49 additions & 0 deletions ai/docs/training_plan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Zappy AI Training Roadmap

> [!NOTE]
> **Training vs. Evaluation Settings**:
> Under the hood, the library training environment (`LibZappyEnv`) dynamically randomizes the map size, team count, and players per team on every reset. This "Domain Randomization" prevents overfitting and teaches the AI general skills.
> The parameters listed below (like **Map Size** and **Configuration**) represent the **target settings we use during evaluation** (via `evaluate_ai.py`) to measure if the phase was successful.

---

## AI Training Roadmap

```mermaid
graph TD
Phase1[Phase 1: Basic Survival] -->|Learn to eat & navigate| Phase2[Phase 2: Single-Agent Elevation]
Phase2 -->|Learn to collect stones & incant| Phase3[Phase 3: Coordination & Radio]
Phase3 -->|Learn to fork, broadcast & gather teammates| Phase4[Phase 4: Full Scale Competitive]
```

### Phase 1: Basic Survival & Navigation
* **Objective**: Teach the neural network to walk, search the map, check its inventory, and consume food when hungry. It must learn not to starve.
* **Map Size**: `10x10`
* **Configuration**: `total_teams=1`, `frequency=1000`
* **Expected Result**: Survives average of 10,000+ turns, remains Level 1.
* **Timesteps**: `200,000`
* **Target Model Name**: `zappy_survival_v1`

### Phase 2: Single-Agent Elevation (Level 2 Competence)
* **Objective**: Train the agent to search for Linemate stones, drop them on a tile, and execute the `Incantation` command to elevate itself to Level 2.
* **Map Size**: `12x12`
* **Configuration**: Load `zappy_survival_v1`, `total_teams=1`, `frequency=1000`
* **Expected Result**: Reaches Level 2 consistently.
* **Timesteps**: `300,000`
* **Target Model Name**: `zappy_level2_v1`

### Phase 3: Coordination & Radio Broadcasts (Level 3-4 Competence)
* **Objective**: Level 3 requires multiple players. Agents must learn to use `FORK` to spawn teammates, `BROADCAST` messages to coordinate, and navigate towards teammate coordinates when an incantation is initiated.
* **Map Size**: `15x15`
* **Configuration**: Load `zappy_level2_v1`, `total_teams=1` (with 2 players), `frequency=1000`
* **Expected Result**: Reaches Level 3/4.
* **Timesteps**: `500,000`
* **Target Model Name**: `zappy_coordination_v1`

### Phase 4: Competitive Multi-Team Play (Level 5-8 Competence)
* **Objective**: Train in the presence of rival teams. Learn to manage resource scarcity, handle ejection, and optimize team-wide ascension to Level 8.
* **Map Size**: `20x20`
* **Configuration**: Load `zappy_coordination_v1`, `total_teams=2` (each with 2-3 players), `frequency=1000`
* **Expected Result**: Master coordination, reaching Level 5+ consistently.
* **Timesteps**: `1,000,000`
* **Target Model Name**: `zappy_master_v1`
2 changes: 1 addition & 1 deletion ai/run_bots.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# Configuration variables
PORT=8080
MODEL="../zappy_ai_model"
MODEL="training/models/zappy_level2_v2"

# Loop through the list of teams
for team in "team01" "team02"; do
Expand Down
12 changes: 12 additions & 0 deletions ai/src/client/lib_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,18 @@ def inventory(self):
return resp

def broadcast(self, text):
# Translate teammate standard broadcasts to PPO format so the learning agent can parse them
if (
hasattr(self, "name")
and isinstance(self.name, str)
and self.name.startswith("TeammateBot_")
):
team = getattr(self, "team_name", "team1")
if "Incantation" in text:
text = f"{team}|ZAPPY_SEC|INCANT"
else:
text = f"{team}|ZAPPY_SEC|COME"

cmd = f"Broadcast {text}\n".encode("utf-8")
self.lib.zappy_send_command(self.server_ptr, self.player_id, cmd)
return self.wait_for_response()
Expand Down
66 changes: 47 additions & 19 deletions ai/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ class EnvObserver(ObservationZappyEnv):
def __init__(self, client):
self.client = client

def _get_real_observation(self):
obs = super()._get_real_observation()
obs[79] = 0
return obs

CAN_RUN_AI = True
except ImportError:
CAN_RUN_AI = False
Expand Down Expand Up @@ -78,6 +83,9 @@ def execute_action(client, action_id, handler):

def run_hybrid_ai(client, team_name, model_path):
"""heuristic helps ai decisions."""
from src.strategy.state_machine import get_hybrid_action
from training.training_env.ZappyEnv import parse_look

full_path = model_path if model_path.endswith(".zip") else f"{model_path}.zip"
if not os.path.exists(full_path):
print(f"[Error]: None module found {full_path}")
Expand All @@ -93,33 +101,53 @@ def run_hybrid_ai(client, team_name, model_path):
except Exception:
obs = np.zeros(657, dtype=np.int32)

try:
current_level = client.level
inv = client.inventory()
except Exception:
current_level = 1
inv = None

try:
look_resp = client.look()
vision_list = (
parse_look(look_resp)
if isinstance(look_resp, str) and look_resp.startswith("[")
else look_resp
)
except Exception:
vision_list = []

messages = (
client.get_unread_messages()
if hasattr(client, "get_unread_messages")
else []
)
best_h = {"score": 0, "task": "IGNORE", "dir": 0}
best_h = {"score": 0, "task": "IGNORE", "dir": 0, "text": ""}
for msg in messages:
h = handler.calculate_heuristic(msg["dir"], msg["text"])
if h["score"] > best_h["score"]:
best_h = {**h, "dir": msg["dir"]}

override = False
if best_h["score"] >= 70:
override = True
if best_h["dir"] in [1, 2, 8]:
client.forward()
elif best_h["dir"] in [3, 4, 5]:
client.left()
elif best_h["dir"] in [6, 7]:
client.right()
elif best_h["score"] == 50 and best_h["task"] == "FLEE_FROM_DIR":
override = True
client.right()

if not override:
action, _ = model.predict(obs, deterministic=True)
execute_action(client, action, handler)
best_h = {**h, "dir": msg["dir"], "text": msg["text"]}

# Check if flee condition is active
if best_h["score"] == 50 and best_h["task"] == "FLEE_FROM_DIR":
action = int(ControllerAction.RIGHT)
else:
best_dir = best_h["dir"] if best_h["score"] >= 70 else 0
best_text = best_h["text"] if best_h["score"] >= 70 else ""

action, _ = get_hybrid_action(
client=client,
parsed_inv=inv,
vision_list=vision_list,
current_level=current_level,
best_dir=best_dir,
best_text=best_text,
model=model,
obs=obs,
)

execute_action(client, action, handler)


def main():
Expand Down
Loading
Loading