Skip to content

Commit 6f3ce4d

Browse files
committed
Fix ruff issues
1 parent 9c85151 commit 6f3ce4d

5 files changed

Lines changed: 25 additions & 45 deletions

File tree

codeclash/arenas/bridge/bridge.py

Lines changed: 14 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import json
44
import shlex
55
import subprocess
6-
from collections import Counter
76
from concurrent.futures import ThreadPoolExecutor, as_completed
87

98
from tqdm.auto import tqdm
@@ -53,10 +52,7 @@ def validate_code(self, agent: Player) -> tuple[bool, str | None]:
5352
content = agent.environment.execute(f"cat {self.submission}")["output"]
5453

5554
# Check for required function definitions
56-
required_functions = [
57-
"def get_bid(",
58-
"def play_card("
59-
]
55+
required_functions = ["def get_bid(", "def play_card("]
6056

6157
missing = []
6258
for func in required_functions:
@@ -86,7 +82,7 @@ def _run_single_simulation(self, agents: list[Player], idx: int, cmd: str):
8682

8783
def execute_round(self, agents: list[Player]):
8884
"""Execute a round of Bridge games."""
89-
sims = self.game_config.get('sims_per_round', 10)
85+
sims = self.game_config.get("sims_per_round", 10)
9086
self.logger.info(f"Running {sims} Bridge simulations with 4 players")
9187

9288
# Build agent paths for the command
@@ -100,12 +96,7 @@ def execute_round(self, agents: list[Player]):
10096
# Run simulations in parallel
10197
with ThreadPoolExecutor(max_workers=8) as executor:
10298
futures = [
103-
executor.submit(
104-
self._run_single_simulation,
105-
agents,
106-
idx,
107-
f"{cmd} --seed {idx} --dealer {idx % 4}"
108-
)
99+
executor.submit(self._run_single_simulation, agents, idx, f"{cmd} --seed {idx} --dealer {idx % 4}")
109100
for idx in range(sims)
110101
]
111102
for future in tqdm(as_completed(futures), total=len(futures), desc="Bridge simulations"):
@@ -114,11 +105,11 @@ def execute_round(self, agents: list[Player]):
114105
def get_results(self, agents: list[Player], round_num: int, stats: RoundStats):
115106
"""Parse results and determine winners."""
116107
# Initialize team scores
117-
team_scores = {'NS': 0.0, 'EW': 0.0}
108+
team_scores = {"NS": 0.0, "EW": 0.0}
118109
games_played = 0
119110

120111
# Parse all simulation logs
121-
for idx in range(self.game_config.get('sims_per_round', 10)):
112+
for idx in range(self.game_config.get("sims_per_round", 10)):
122113
log_file = self.log_round(round_num) / f"sim_{idx}.json"
123114

124115
if not log_file.exists():
@@ -130,15 +121,15 @@ def get_results(self, agents: list[Player], round_num: int, stats: RoundStats):
130121
result = json.load(f)
131122

132123
# Check for error
133-
if 'error' in result:
124+
if "error" in result:
134125
self.logger.warning(f"Simulation {idx} had error: {result['error']}")
135126
continue
136127

137128
# Extract VP scores for each team
138-
vp_scores = result.get('normalized_score', {})
129+
vp_scores = result.get("normalized_score", {})
139130
if vp_scores:
140-
team_scores['NS'] += vp_scores.get('NS', 0.0)
141-
team_scores['EW'] += vp_scores.get('EW', 0.0)
131+
team_scores["NS"] += vp_scores.get("NS", 0.0)
132+
team_scores["EW"] += vp_scores.get("EW", 0.0)
142133
games_played += 1
143134
except (json.JSONDecodeError, KeyError) as e:
144135
self.logger.warning(f"Error parsing {log_file}: {e}")
@@ -153,20 +144,20 @@ def get_results(self, agents: list[Player], round_num: int, stats: RoundStats):
153144
return
154145

155146
# Average the scores
156-
team_scores['NS'] /= games_played
157-
team_scores['EW'] /= games_played
147+
team_scores["NS"] /= games_played
148+
team_scores["EW"] /= games_played
158149

159150
# Determine winning team
160-
if abs(team_scores['NS'] - team_scores['EW']) < 0.01: # Tie threshold
151+
if abs(team_scores["NS"] - team_scores["EW"]) < 0.01: # Tie threshold
161152
stats.winner = RESULT_TIE
162-
elif team_scores['NS'] > team_scores['EW']:
153+
elif team_scores["NS"] > team_scores["EW"]:
163154
stats.winner = f"{agents[0].name}/{agents[2].name}"
164155
else:
165156
stats.winner = f"{agents[1].name}/{agents[3].name}"
166157

167158
# Assign scores to individual players based on their team
168159
for position, agent in enumerate(agents):
169-
team = 'NS' if position % 2 == 0 else 'EW'
160+
team = "NS" if position % 2 == 0 else "EW"
170161
score = team_scores[team]
171162
stats.scores[agent.name] = score
172163
stats.player_stats[agent.name].score = score

codeclash/arenas/figgie/figgie.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,9 @@ def __init__(self, config, **kwargs):
6161

6262
def execute_round(self, agents: list[Player]) -> None:
6363
args = [f"/{agent.name}/{self.submission}" for agent in agents]
64-
cmd = f"python engine.py {' '.join(args)} -r {self.game_config['sims_per_round']} > {self.log_env / FIGGIE_LOG};"
64+
cmd = (
65+
f"python engine.py {' '.join(args)} -r {self.game_config['sims_per_round']} > {self.log_env / FIGGIE_LOG};"
66+
)
6567
self.logger.info(f"Running game: {cmd}")
6668
assert_zero_exit_code(self.environment.execute(cmd))
6769

codeclash/arenas/gomoku/gomoku.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ def __init__(self, config, **kwargs):
2828

2929
def execute_round(self, agents: list[Player]) -> None:
3030
args = [f"/{agent.name}/{self.submission}" for agent in agents]
31-
cmd = f"python engine.py {' '.join(args)} -r {self.game_config['sims_per_round']} > {self.log_env / GOMOKU_LOG};"
31+
cmd = (
32+
f"python engine.py {' '.join(args)} -r {self.game_config['sims_per_round']} > {self.log_env / GOMOKU_LOG};"
33+
)
3234
self.logger.info(f"Running game: {cmd}")
3335
assert_zero_exit_code(self.environment.execute(cmd))
3436

@@ -75,7 +77,7 @@ def validate_code(self, agent: Player) -> tuple[bool, str | None]:
7577
return (
7678
False,
7779
f"{self.submission} must define a get_move(board, color) function. "
78-
"See the game description for the required signature."
80+
"See the game description for the required signature.",
7981
)
8082

8183
return True, None

tests/arenas/test_bridge.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,6 @@ def get_bid(game_state):
105105
assert "def play_card(" in error
106106

107107

108-
109108
class TestBridgeRequirements:
110109
"""Test Bridge-specific requirements."""
111110

@@ -119,11 +118,7 @@ def test_requires_4_players(self, minimal_config, tmp_log_dir):
119118
]
120119

121120
with pytest.raises(ValueError, match="Bridge requires exactly 4 players"):
122-
BridgeArena(
123-
config,
124-
tournament_id="test_tournament",
125-
local_output_dir=tmp_log_dir
126-
)
121+
BridgeArena(config, tournament_id="test_tournament", local_output_dir=tmp_log_dir)
127122

128123
def test_accepts_4_players(self):
129124
"""Test that Bridge accepts exactly 4 players by checking class properties."""

tests/arenas/test_figgie.py

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -101,26 +101,16 @@ def test_rejects_invalid_player_count(self, minimal_config, tmp_log_dir):
101101
]
102102

103103
with pytest.raises(ValueError, match="Figgie requires 4 or 5 players"):
104-
FiggieArena(
105-
config,
106-
tournament_id="test_tournament",
107-
local_output_dir=tmp_log_dir
108-
)
104+
FiggieArena(config, tournament_id="test_tournament", local_output_dir=tmp_log_dir)
109105

110106
def test_rejects_6_players(self, minimal_config, tmp_log_dir):
111107
"""Test that Figgie rejects 6 players."""
112108
config = minimal_config.copy()
113109
config["game"]["name"] = "Figgie"
114-
config["players"] = [
115-
{"name": f"p{i}", "agent": "dummy"} for i in range(6)
116-
]
110+
config["players"] = [{"name": f"p{i}", "agent": "dummy"} for i in range(6)]
117111

118112
with pytest.raises(ValueError, match="Figgie requires 4 or 5 players"):
119-
FiggieArena(
120-
config,
121-
tournament_id="test_tournament",
122-
local_output_dir=tmp_log_dir
123-
)
113+
FiggieArena(config, tournament_id="test_tournament", local_output_dir=tmp_log_dir)
124114

125115
def test_accepts_4_or_5_players(self):
126116
"""Test that Figgie accepts 4 or 5 players by checking class properties."""

0 commit comments

Comments
 (0)