|
| 1 | +import json |
| 2 | +import shlex |
| 3 | +import subprocess |
| 4 | + |
| 5 | +from codeclash.agents.player import Player |
| 6 | +from codeclash.arenas.arena import CodeArena, RoundStats |
| 7 | +from codeclash.constants import RESULT_TIE |
| 8 | +from codeclash.utils.environment import assert_zero_exit_code |
| 9 | + |
| 10 | +RESULTS_JSON = "bomberland_results.json" |
| 11 | +CRASH_SCORE = -1_000_000.0 |
| 12 | + |
| 13 | + |
| 14 | +class BomberlandArena(CodeArena): |
| 15 | + name: str = "Bomberland" |
| 16 | + submission: str = "bomberland_agent.py" |
| 17 | + description: str = """Bomberland is a Bomberman-style multi-agent arena based on Coder One's Bomberland competition. |
| 18 | +
|
| 19 | +Your bot is a Python file named `bomberland_agent.py` that defines a callable named `next_actions`. |
| 20 | +The callable receives a game-state dictionary and should return a dictionary mapping unit ids to actions: |
| 21 | +
|
| 22 | + def next_actions(game_state): |
| 23 | + return {"unit_0": "up"} |
| 24 | +
|
| 25 | +Valid actions are `up`, `down`, `left`, `right`, `bomb`, `stay`, and `detonate` (to blow up one of |
| 26 | +your own bombs early, e.g. the string `"detonate:x,y"` or `{"type": "detonate", "coordinates": [x, y]}`; |
| 27 | +bombs also explode automatically after their timer). Each round runs several deterministic seeded |
| 28 | +games. Your units move on a destructible grid, place bombs, destroy blocks, damage opposing units, |
| 29 | +and score by survival, damage, kills, and block destruction. Bomb blasts (`x` entities) stay active |
| 30 | +briefly and damage any unit standing on or moving into them. |
| 31 | +""" |
| 32 | + default_args: dict = { |
| 33 | + "sims_per_round": 4, |
| 34 | + "ticks": 80, |
| 35 | + "width": 11, |
| 36 | + "height": 11, |
| 37 | + "unit_count": 3, |
| 38 | + "agent_timeout": 0.25, |
| 39 | + "validation_timeout": 5, |
| 40 | + "timeout": 180, |
| 41 | + } |
| 42 | + |
| 43 | + def __init__(self, config: dict, **kwargs): |
| 44 | + player_count = len(config.get("players", [])) |
| 45 | + if player_count != 2: |
| 46 | + raise ValueError("Bomberland requires exactly two players") |
| 47 | + game_config = config.get("game", {}) |
| 48 | + game_args = game_config.get("args", {}) |
| 49 | + sims_per_round = int( |
| 50 | + game_args.get("sims_per_round", game_config.get("sims_per_round", self.default_args["sims_per_round"])) |
| 51 | + ) |
| 52 | + if sims_per_round % 2 != 0: |
| 53 | + raise ValueError("Bomberland requires an even sims_per_round so both players get paired starting sides") |
| 54 | + super().__init__(config, **kwargs) |
| 55 | + |
| 56 | + def _game_arg(self, key: str): |
| 57 | + nested_args = self.game_config.get("args", {}) |
| 58 | + return nested_args.get(key, self.game_config.get(key, self.default_args[key])) |
| 59 | + |
| 60 | + def _sims_per_round(self) -> int: |
| 61 | + return int(self._game_arg("sims_per_round")) |
| 62 | + |
| 63 | + def validate_code(self, agent: Player) -> tuple[bool, str | None]: |
| 64 | + quoted_submission = shlex.quote(self.submission) |
| 65 | + file_check = agent.environment.execute(f"test -f {quoted_submission} && echo exists") |
| 66 | + if "exists" not in file_check["output"]: |
| 67 | + return False, f"Submission file `{self.submission}` not found in the workspace root" |
| 68 | + |
| 69 | + content = agent.environment.execute(f"cat {quoted_submission}")["output"] |
| 70 | + if not content.strip(): |
| 71 | + return False, f"`{self.submission}` is empty" |
| 72 | + |
| 73 | + syntax_check = agent.environment.execute(f"python -m py_compile {quoted_submission}") |
| 74 | + if syntax_check["returncode"] != 0: |
| 75 | + return False, f"Python syntax error in `{self.submission}`:\n{syntax_check['output']}" |
| 76 | + |
| 77 | + validation_timeout = int(self._game_arg("validation_timeout")) |
| 78 | + try: |
| 79 | + import_check = agent.environment.execute( |
| 80 | + "python - <<'PY'\n" |
| 81 | + "import importlib.util\n" |
| 82 | + f"spec = importlib.util.spec_from_file_location('submission_agent', {self.submission!r})\n" |
| 83 | + "module = importlib.util.module_from_spec(spec)\n" |
| 84 | + "spec.loader.exec_module(module)\n" |
| 85 | + "assert hasattr(module, 'next_actions'), 'next_actions callable not found'\n" |
| 86 | + "assert callable(module.next_actions), 'next_actions must be callable'\n" |
| 87 | + "state = {\n" |
| 88 | + " 'connection': {'agent_id': 'Alice'},\n" |
| 89 | + " 'agents': {'Alice': {'unit_ids': ['u0']}},\n" |
| 90 | + " 'unit_state': {'u0': {'agent_id': 'Alice', 'hp': 3, 'coordinates': [1, 1]}},\n" |
| 91 | + " 'entities': [],\n" |
| 92 | + " 'world': {'width': 5, 'height': 5},\n" |
| 93 | + " 'tick': 0,\n" |
| 94 | + "}\n" |
| 95 | + "result = module.next_actions(state)\n" |
| 96 | + "assert result is None or isinstance(result, dict), 'next_actions must return a dict or None'\n" |
| 97 | + "PY", |
| 98 | + timeout=validation_timeout, |
| 99 | + ) |
| 100 | + except subprocess.TimeoutExpired: |
| 101 | + return False, f"`next_actions` validation exceeded {validation_timeout}s timeout" |
| 102 | + if import_check["returncode"] != 0: |
| 103 | + return False, f"Could not import or call `next_actions` from `{self.submission}`:\n{import_check['output']}" |
| 104 | + |
| 105 | + return True, None |
| 106 | + |
| 107 | + def execute_round(self, agents: list[Player]) -> None: |
| 108 | + agent_args = [] |
| 109 | + for agent in agents: |
| 110 | + agent_args.extend(["--agent", f"{agent.name}=/{agent.name}/{self.submission}"]) |
| 111 | + |
| 112 | + cmd = [ |
| 113 | + "python", |
| 114 | + "run_bomberland.py", |
| 115 | + "--sims", |
| 116 | + str(self._sims_per_round()), |
| 117 | + "--ticks", |
| 118 | + str(self._game_arg("ticks")), |
| 119 | + "--width", |
| 120 | + str(self._game_arg("width")), |
| 121 | + "--height", |
| 122 | + str(self._game_arg("height")), |
| 123 | + "--unit-count", |
| 124 | + str(self._game_arg("unit_count")), |
| 125 | + "--agent-timeout", |
| 126 | + str(self._game_arg("agent_timeout")), |
| 127 | + "--output", |
| 128 | + str(self.log_env / RESULTS_JSON), |
| 129 | + *agent_args, |
| 130 | + ] |
| 131 | + full_cmd = " ".join(shlex.quote(part) for part in cmd) |
| 132 | + self.logger.info(f"Running game: {full_cmd}") |
| 133 | + try: |
| 134 | + response = self.environment.execute(full_cmd, timeout=int(self._game_arg("timeout"))) |
| 135 | + except subprocess.TimeoutExpired as exc: |
| 136 | + raise RuntimeError("Bomberland round timed out") from exc |
| 137 | + assert_zero_exit_code(response, logger=self.logger) |
| 138 | + |
| 139 | + def get_results(self, agents: list[Player], round_num: int, stats: RoundStats): |
| 140 | + result_file = self.log_round(round_num) / RESULTS_JSON |
| 141 | + if not result_file.exists(): |
| 142 | + self.logger.error(f"Missing result file: {result_file}") |
| 143 | + stats.winner = RESULT_TIE |
| 144 | + for agent in agents: |
| 145 | + stats.scores[agent.name] = CRASH_SCORE |
| 146 | + stats.player_stats[agent.name].score = CRASH_SCORE |
| 147 | + stats.details.append( |
| 148 | + json.dumps( |
| 149 | + { |
| 150 | + "player": agent.name, |
| 151 | + "score": CRASH_SCORE, |
| 152 | + "status": "error", |
| 153 | + "error": f"missing Bomberland result file: {result_file}", |
| 154 | + }, |
| 155 | + sort_keys=True, |
| 156 | + ) |
| 157 | + ) |
| 158 | + return |
| 159 | + |
| 160 | + with open(result_file) as f: |
| 161 | + result = json.load(f) |
| 162 | + |
| 163 | + scores = {agent.name: CRASH_SCORE for agent in agents} |
| 164 | + for player, score in result.get("average_scores", {}).items(): |
| 165 | + if player in scores: |
| 166 | + scores[player] = float(score) |
| 167 | + |
| 168 | + stats.scores = scores |
| 169 | + stats.details = result.get("details", []) |
| 170 | + for player, score in scores.items(): |
| 171 | + stats.player_stats[player].score = score |
| 172 | + |
| 173 | + if not scores: |
| 174 | + stats.winner = RESULT_TIE |
| 175 | + return |
| 176 | + |
| 177 | + top_score = max(scores.values()) |
| 178 | + winners = [player for player, score in scores.items() if score == top_score] |
| 179 | + stats.winner = winners[0] if len(winners) == 1 else RESULT_TIE |
0 commit comments