Write a table football simulator and 5 different agents to play matches. Run a tournament of the agents against each other and visualise the results in a Python notebook.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, this is a fun challenge! We'll create a simplified 2D table football (foosball) simulation.
Core Components:
Game Environment:
Field (dimensions, goals).
Ball (position, velocity).
Rods (fixed X-positions, controllable Y-positions, players on rods).
Physics (ball movement, collisions with walls, collisions with players).
Scoring.
Agents:
A base Agent class.
5 different agent implementations with varying strategies.
Tournament:
Round-robin play.
Score tracking.
Visualization:
Using matplotlib and pandas in a Jupyter Notebook. We won't do real-time animation of the game itself to keep complexity manageable for this format, but rather visualize tournament results. A simple text-based render during a single game can be added for debugging.
Let's start by defining the game environment.
python
# Python Notebook Setup (run this cell first)
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import random
import time
from IPython.display import clear_output
# Game Constants
FIELD_WIDTH = 100
FIELD_HEIGHT = 60
GOAL_WIDTH = 20 # Centered on the y-axis
GOAL_DEPTH = 5 # How far "behind" the goal line the goal extends (for reset)
BALL_RADIUS = 1.5
ROD_THICKNESS = 1 # For collision detection
PLAYER_SPAN_ON_ROD = 12 # How much y-space a "player" on a rod covers
MAX_ROD_SPEED = 4 # Max units a rod can move in Y per step
KICK_POWER_FORWARD = 6
KICK_POWER_SIDE_INFLUENCE = 0.2 # How much hitting edge of player affects y-velocity
KICK_POWER_RANDOM_Y = 0.5
BALL_FRICTION = 0.985 # Multiplier for ball velocity each step
MAX_BALL_SPEED = 15
# Rod X-positions (from left edge of field)
# Team 0 defends left goal, attacks right goal
# Team 1 defends right goal, attacks left goal
# Simplified: Goalie, Defender, Attacker for each team
ROD_X_POSITIONS_TEAM0 = [15, 40, 70] # Goalie, Mid, Fwd
ROD_X_POSITIONS_TEAM1 = [FIELD_WIDTH - 15, FIELD_WIDTH - 40, FIELD_WIDTH - 70] # Goalie, Mid, Fwd
NUM_RODS_PER_TEAM = len(ROD_X_POSITIONS_TEAM0)
# Goal Y-boundaries
GOAL_Y_MIN = (FIELD_HEIGHT - GOAL_WIDTH) / 2
GOAL_Y_MAX = (FIELD_HEIGHT + GOAL_WIDTH) / 2
SCORE_TO_WIN = 5
MAX_STEPS_PER_GAME = 3000 # To prevent infinitely long games
class Ball:
def __init__(self):
self.reset()
def reset(self, direction=0): # direction: 0=center, 1=team0 kickoff, -1=team1 kickoff
self.x = FIELD_WIDTH / 2
self.y = FIELD_HEIGHT / 2
if direction == 0:
self.vx = 0
self.vy = 0
else: # Kickoff
self.vx = KICK_POWER_FORWARD / 2 * direction
self.vy = (random.random() - 0.5) * 2
def move(self):
self.x += self.vx
self.y += self.vy
self.vx *= BALL_FRICTION
self.vy *= BALL_FRICTION
# Cap speed
speed = np.sqrt(self.vx**2 + self.vy**2)
if speed > MAX_BALL_SPEED:
self.vx = (self.vx / speed) * MAX_BALL_SPEED
self.vy = (self.vy / speed) * MAX_BALL_SPEED
class TableFootballGame:
def __init__(self, agent0, agent1, verbose=False):
self.ball = Ball()
self.agents = [agent0, agent1]
self.rod_y_positions = [
[FIELD_HEIGHT / 2] * NUM_RODS_PER_TEAM, # Team 0
[FIELD_HEIGHT / 2] * NUM_RODS_PER_TEAM # Team 1
]
self.scores = [0, 0]
self.verbose = verbose
self.current_step = 0
def reset_game(self, kickoff_team_idx=None):
if kickoff_team_idx is None: # Start of match
self.ball.reset(direction=0)
elif kickoff_team_idx == 0: # Team 0 scored on Team 1, so Team 1 kicks off
self.ball.reset(direction=-1)
else: # Team 1 scored on Team 0, so Team 0 kicks off
self.ball.reset(direction=1)
self.rod_y_positions = [
[FIELD_HEIGHT / 2] * NUM_RODS_PER_TEAM,
[FIELD_HEIGHT / 2] * NUM_RODS_PER_TEAM
]
self.current_step = 0
def get_game_state(self, team_id):
# Provide necessary info for an agent to make a decision
opponent_team_id = 1 - team_id
state = {
"ball_x": self.ball.x,
"ball_y": self.ball.y,
"ball_vx": self.ball.vx,
"ball_vy": self.ball.vy,
"my_team_id": team_id,
"my_rod_y": list(self.rod_y_positions[team_id]), # Send a copy
"opponent_rod_y": list(self.rod_y_positions[opponent_team_id]), # Send a copy
"my_rod_x": ROD_X_POSITIONS_TEAM0 if team_id == 0 else ROD_X_POSITIONS_TEAM1,
"opponent_rod_x": ROD_X_POSITIONS_TEAM1 if team_id == 0 else ROD_X_POSITIONS_TEAM0,
"field_width": FIELD_WIDTH,
"field_height": FIELD_HEIGHT,
"goal_y_min": GOAL_Y_MIN,
"goal_y_max": GOAL_Y_MAX,
"score_to_win": SCORE_TO_WIN,
"my_score": self.scores[team_id],
"opponent_score": self.scores[opponent_team_id]
}
return state
def _update_rod_positions(self, actions):
for team_id in range(2):
if actions[team_id] is None or len(actions[team_id]) != NUM_RODS_PER_TEAM:
# Agent might provide partial or no action, handle gracefully (e.g., do nothing)
# For simplicity, we'll assume valid actions for now or raise error.
# Let's allow agents to not return action for some rods.
if actions[team_id] is None: continue
# if len(actions[team_id]) != NUM_RODS_PER_TEAM:
# print(f"Warning: Agent {team_id} provided malformed action: {actions[team_id]}")
# continue
for r_idx, target_y in enumerate(actions[team_id]):
if target_y is None: continue # Agent chose not to move this rod
current_y = self.rod_y_positions[team_id][r_idx]
delta_y = target_y - current_y
# Limit speed
move_amount = np.clip(delta_y, -MAX_ROD_SPEED, MAX_ROD_SPEED)
new_y = current_y + move_amount
# Keep rods within field bounds (considering player span)
rod_min_y = PLAYER_SPAN_ON_ROD / 2
rod_max_y = FIELD_HEIGHT - PLAYER_SPAN_ON_ROD / 2
self.rod_y_positions[team_id][r_idx] = np.clip(new_y, rod_min_y, rod_max_y)
def _handle_collisions(self):
# Ball with Walls
if self.ball.y - BALL_RADIUS < 0:
self.ball.y = BALL_RADIUS
self.ball.vy *= -1
elif self.ball.y + BALL_RADIUS > FIELD_HEIGHT:
self.ball.y = FIELD_HEIGHT - BALL_RADIUS
self.ball.vy *= -1
# Ball with Rods/Players
for team_id in range(2):
rod_x_coords = ROD_X_POSITIONS_TEAM0 if team_id == 0 else ROD_X_POSITIONS_TEAM1
for r_idx, rod_x in enumerate(rod_x_coords):
rod_y = self.rod_y_positions[team_id][r_idx]
# Check for x-overlap
if abs(self.ball.x - rod_x) < BALL_RADIUS + ROD_THICKNESS / 2:
# Check for y-overlap (player on rod)
player_y_min = rod_y - PLAYER_SPAN_ON_ROD / 2
player_y_max = rod_y + PLAYER_SPAN_ON_ROD / 2
if player_y_min < self.ball.y < player_y_max:
# Collision!
if self.verbose: print(f"Step {self.current_step}: Ball hit by Team {team_id}, Rod {r_idx}")
# Move ball slightly out of rod to prevent sticking
if self.ball.x < rod_x : # Ball coming from left
self.ball.x = rod_x - (BALL_RADIUS + ROD_THICKNESS/2 + 0.1)
else: # Ball coming from right
self.ball.x = rod_x + (BALL_RADIUS + ROD_THICKNESS/2 + 0.1)
# Determine kick direction based on team
kick_direction_x = 1 if team_id == 0 else -1 # Team 0 kicks right, Team 1 kicks left
self.ball.vx = kick_direction_x * KICK_POWER_FORWARD
# Influence y-velocity based on where it hit the player
hit_offset_y = (self.ball.y - rod_y) / (PLAYER_SPAN_ON_ROD / 2) # Normalized: -1 to 1
self.ball.vy += hit_offset_y * KICK_POWER_SIDE_INFLUENCE * KICK_POWER_FORWARD
self.ball.vy += (random.random() - 0.5) * 2 * KICK_POWER_RANDOM_Y
return # Only one collision per step for simplicity
# Ball with Side Walls (potential goal)
goal_scored = False
scoring_team_idx = -1
if self.ball.x + BALL_RADIUS > FIELD_WIDTH: # Potential goal for Team 0
if GOAL_Y_MIN < self.ball.y < GOAL_Y_MAX:
self.scores[0] += 1
scoring_team_idx = 0
if self.verbose: print(f"Step {self.current_step}: GOAL for Team 0! Score: {self.scores[0]}-{self.scores[1]}")
goal_scored = True
else: # Hit side wall (not goal)
self.ball.x = FIELD_WIDTH - BALL_RADIUS
self.ball.vx *= -1
elif self.ball.x - BALL_RADIUS < 0: # Potential goal for Team 1
if GOAL_Y_MIN < self.ball.y < GOAL_Y_MAX:
self.scores[1] += 1
scoring_team_idx = 1
if self.verbose: print(f"Step {self.current_step}: GOAL for Team 1! Score: {self.scores[0]}-{self.scores[1]}")
goal_scored = True
else: # Hit side wall (not goal)
self.ball.x = BALL_RADIUS
self.ball.vx *= -1
if goal_scored:
if self.scores[0] >= SCORE_TO_WIN or self.scores[1] >= SCORE_TO_WIN:
return True # Game over
else:
self.reset_game(kickoff_team_idx=scoring_team_idx) # Reset ball for kickoff
return False # Game not over due to score
def step(self):
self.current_step += 1
# 1. Get actions from agents
action0 = self.agents[0].get_action(self.get_game_state(0))
action1 = self.agents[1].get_action(self.get_game_state(1))
# 2. Update rod positions based on actions
self._update_rod_positions([action0, action1])
# 3. Move ball
self.ball.move()
# 4. Handle collisions and goals
game_over_by_score = self._handle_collisions()
if game_over_by_score:
return True, "score"
if self.current_step >= MAX_STEPS_PER_GAME:
return True, "timeout"
return False, None # Game not over
def play_match(self):
self.reset_game() # Full reset for a new match
game_over = False
reason = None
while not game_over:
game_over, reason = self.step()
if self.verbose and self.current_step % 50 == 0: # Basic text render
self.render()
# time.sleep(0.01) # Slow down for viewing
# clear_output(wait=True)
if self.verbose:
print(f"Match Over! Reason: {reason}. Final Score: {self.scores[0]} - {self.scores[1]}")
return self.scores[0], self.scores[1]
def render(self): # Simple text render
print(f"Step: {self.current_step}, Score: {self.scores[0]}-{self.scores[1]}, Ball: ({self.ball.x:.1f},{self.ball.y:.1f}) v=({self.ball.vx:.1f},{self.ball.vy:.1f})")
# Add rod positions if needed
# for team_id in range(2):
# print(f" Team {team_id} Rods Y: {[round(y,1) for y in self.rod_y_positions[team_id]]}")
Now for the Agents:
python
Now, let's set up the tournament.
python
Finally, visualization in the notebook.
python
# Visualization
plt.style.use('seaborn-v0_8-whitegrid') # Using a seaborn style
# 1. Bar chart of Points
fig, ax = plt.subplots(figsize=(10, 6))
summary_df_sorted_pts = summary_df.sort_values("Pts", ascending=True) # For horizontal bar chart
ax.barh(summary_df_sorted_pts.index, summary_df_sorted_pts["Pts"], color='skyblue')
ax.set_xlabel("Points (3 for Win, 1 for Draw)")
ax.set_title("Tournament Points per Agent")
plt.tight_layout()
plt.show()
# 2. Bar chart of Wins
fig, ax = plt.subplots(figsize=(10, 6))
summary_df_sorted_wins = summary_df.sort_values("W", ascending=True)
ax.barh(summary_df_sorted_wins.index, summary_df_sorted_wins["W"], color='lightcoral')
ax.set_xlabel("Number of Wins")
ax.set_title("Tournament Wins per Agent")
plt.tight_layout()
plt.show()
# 3. Goal Difference
fig, ax = plt.subplots(figsize=(10, 6))
summary_df_sorted_gd = summary_df.sort_values("GD", ascending=True)
colors = ['tomato' if x < 0 else 'mediumseagreen' for x in summary_df_sorted_gd["GD"]]
ax.barh(summary_df_sorted_gd.index, summary_df_sorted_gd["GD"], color=colors)
ax.set_xlabel("Goal Difference (GF - GA)")
ax.set_title("Tournament Goal Difference per Agent")
ax.axvline(0, color='black', linewidth=0.8, linestyle='--') # Line at GD=0
plt.tight_layout()
plt.show()
# 4. Heatmap of Head-to-Head Scores (Average Goals For)
# We need to aggregate scores for AgentA vs AgentB
# Create a matrix for average goals scored by row_agent against col_agent
agent_names = [agent.name for agent in agents_list]
h2h_gf_matrix = pd.DataFrame(index=agent_names, columns=agent_names, dtype=float).fillna(0.0)
h2h_matches_played = pd.DataFrame(index=agent_names, columns=agent_names, dtype=int).fillna(0)
for _, row in results_df.iterrows():
# We care about who was AgentA and AgentB in the original pairing for this matrix
# 'AgentA' in results_df is the original AgentA for that row pairing
h2h_gf_matrix.loc[row["AgentA"], row["AgentB"]] += row["ScoreA"]
h2h_matches_played.loc[row["AgentA"], row["AgentB"]] += 1
# Also for the reverse (AgentB vs AgentA)
h2h_gf_matrix.loc[row["AgentB"], row["AgentA"]] += row["ScoreB"]
h2h_matches_played.loc[row["AgentB"], row["AgentA"]] += 1
# Calculate average goals
avg_h2h_gf_matrix = h2h_gf_matrix / h2h_matches_played.replace(0,1) # Avoid division by zero if a pairing somehow didn't play
avg_h2h_gf_matrix = avg_h2h_gf_matrix.fillna(0) # Fill diagonal NaNs if any
plt.figure(figsize=(10, 8))
import seaborn as sns
sns.heatmap(avg_h2h_gf_matrix, annot=True, cmap="YlGnBu", fmt=".1f", cbar_kws={'label': 'Avg Goals Scored By Row Agent'})
plt.title("Head-to-Head Average Goals For (Row Agent vs Col Agent)")
plt.ylabel("Attacking Agent (Row)")
plt.xlabel("Defending Agent (Column)")
plt.tight_layout()
plt.show()
print("\nRaw Match Results:")
print(results_df)
To Run This:
Open a new Jupyter Notebook.
Copy and paste each Python code block into a separate cell.
Run the cells in order.
Explanation of Agents:
RandomAgent: Moves its rods to random Y positions. This is a baseline to see if other strategies are better than pure chance.
DefensiveAgent: All its rods try to follow the ball's Y coordinate. A simple reactive defense.
ClosestRodDefensiveAgent: Only the rod that is horizontally closest to the ball tracks the ball's Y position. Other rods stay in a default central position. This aims to be slightly more efficient than all rods moving.
OffensiveBiasAgent: All rods track the ball's Y position. It relies on the game's kick mechanics to propel the ball forward. The "bias" is simply that all rods are active, hoping one of the front ones will hit.
SmartHeuristicAgent:
If the ball is in its own half, it plays defensively (all rods track ball's Y).
If the ball is in the opponent's half:
The goalie rod takes a mixed position between ball Y and center Y.
The midfield rod tracks ball Y.
The forward rod tracks ball Y and tries a very simple "aim" by slightly shifting its Y position to angle the shot towards the center of the opponent's goal.
This simulation is still quite simplified (e.g., no spinning, no detailed player shapes on rods, kicks are somewhat fixed in power), but it provides a framework for testing different agent strategies. The results will show which of these simple heuristics perform best against each other. The SmartHeuristicAgent is expected to perform relatively well.
class BaseAgent:
def __init__(self, name="BaseAgent"):
self.name = name
def get_action(self, game_state):
"""
Args:
game_state (dict): Current state of the game.
Returns:
list: A list of target Y positions for each rod, e.g., [y_rod0, y_rod1, y_rod2]
or None for a rod if no specific action.
"""
raise NotImplementedError
class RandomAgent(BaseAgent):
def __init__(self, name="RandomAgent"):
super().__init__(name)
def get_action(self, game_state):
actions = []
for _ in range(NUM_RODS_PER_TEAM):
# Target a random Y position within the operational range of a rod
min_y_target = PLAYER_SPAN_ON_ROD / 2
max_y_target = game_state["field_height"] - PLAYER_SPAN_ON_ROD / 2
actions.append(random.uniform(min_y_target, max_y_target))
return actions
class DefensiveAgent(BaseAgent):
"""All rods try to track the ball's Y position."""
def __init__(self, name="DefensiveAgent"):
super().__init__(name)
def get_action(self, game_state):
target_y = game_state["ball_y"]
return [target_y] * NUM_RODS_PER_TEAM
class ClosestRodDefensiveAgent(BaseAgent):
"""Only the rod closest (in X) to the ball tracks its Y. Others stay central."""
def __init__(self, name="ClosestRodDefensiveAgent"):
super().__init__(name)
def get_action(self, game_state):
ball_x = game_state["ball_x"]
ball_y = game_state["ball_y"]
my_rod_x_positions = game_state["my_rod_x"]
closest_rod_idx = -1
min_dist_x = float('inf')
for i, rod_x in enumerate(my_rod_x_positions):
dist_x = abs(ball_x - rod_x)
if dist_x < min_dist_x:
min_dist_x = dist_x
closest_rod_idx = i
actions = [None] * NUM_RODS_PER_TEAM # Start with no action for any rod
# Default position for rods not tracking the ball
default_y = game_state["field_height"] / 2
for i in range(NUM_RODS_PER_TEAM):
if i == closest_rod_idx:
actions[i] = ball_y
else:
actions[i] = default_y # Other rods stay central or a predefined defensive spot
return actions
class OffensiveBiasAgent(BaseAgent):
"""
Rods track ball_y. If ball is near an attacking rod, it tries to hit.
Goalie stays more defensive.
"""
def __init__(self, name="OffensiveBiasAgent"):
super().__init__(name)
def get_action(self, game_state):
ball_y = game_state["ball_y"]
actions = [None] * NUM_RODS_PER_TEAM
# Team 0: Goalie=0, Mid=1, Fwd=2
# Team 1: Goalie=0, Mid=1, Fwd=2 (indices are local to team)
# Rod X positions are already given from team's perspective in game_state["my_rod_x"]
# Goalie (rod 0) is purely defensive
actions[0] = ball_y
# Midfielder (rod 1) tracks ball Y
actions[1] = ball_y
# Forward (rod 2) tracks ball Y aggressively
actions[2] = ball_y
# This agent doesn't explicitly "aim" yet, just positions rods.
# The kick mechanics handle the forward motion.
# A smarter version would adjust Y slightly to aim.
return actions
class SmartHeuristicAgent(BaseAgent):
"""
- Defensive stance if ball is in own half.
- Offensive stance if ball is in opponent's half.
- Tries to aim shots slightly.
"""
def __init__(self, name="SmartHeuristicAgent"):
super().__init__(name)
def get_action(self, game_state):
ball_x = game_state["ball_x"]
ball_y = game_state["ball_y"]
my_team_id = game_state["my_team_id"]
my_rod_x = game_state["my_rod_x"]
field_width = game_state["field_width"]
field_height = game_state["field_height"]
actions = [None] * NUM_RODS_PER_TEAM
# Determine if ball is in my half or opponent's half
# Team 0: own half x < FW/2, opp half x > FW/2
# Team 1: own half x > FW/2, opp half x < FW/2
in_my_half = (my_team_id == 0 and ball_x < field_width / 2) or \
(my_team_id == 1 and ball_x > field_width / 2)
# Rod indices: 0=Goalie, 1=Mid, 2=Fwd
if in_my_half:
# Defensive: All rods track ball_y
for i in range(NUM_RODS_PER_TEAM):
actions[i] = ball_y
else:
# Offensive:
# Goalie (rod 0) stays somewhat central but biased to ball_y
actions[0] = (ball_y + field_height / 2) / 2
# Midfielder (rod 1) tracks ball_y, maybe slightly aims pass/shot
# For simplicity, just tracks ball_y to set up for a kick
actions[1] = ball_y
# Forward (rod 2) tracks ball_y and tries to "aim"
# Aiming: shift rod y slightly opposite to ball_y relative to goal center
# to try and angle shot towards center of goal.
goal_center_y = field_height / 2
aim_offset = (goal_center_y - ball_y) * 0.1 # Small adjustment
actions[2] = ball_y + aim_offset
actions[2] = np.clip(actions[2], PLAYER_SPAN_ON_ROD / 2, field_height - PLAYER_SPAN_ON_ROD / 2)
return actions
# Instantiate Agents
agents_list = [
RandomAgent(),
DefensiveAgent(),
ClosestRodDefensiveAgent(),
OffensiveBiasAgent(),
SmartHeuristicAgent()
]
# Tournament Setup
tournament_results = [] # List of match results
# For a more robust tournament, play each pair multiple times (e.g., home and away)
NUM_MATCHES_PER_PAIRING = 2 # Each agent plays other once as P0, once as P1
print("Starting Tournament...")
for i, agent_a_class in enumerate(agents_list):
for j, agent_b_class in enumerate(agents_list):
if i == j: # Agents don't play themselves
continue
for k in range(NUM_MATCHES_PER_PAIRING):
print(f"\nMatch: {agent_a_class.name} (Team 0) vs {agent_b_class.name} (Team 1) - Game {k+1}")
# Create fresh instances for each match to reset any internal state
# (though our current agents are stateless between matches)
agent_a = type(agent_a_class)(name=agent_a_class.name)
agent_b = type(agent_b_class)(name=agent_b_class.name)
if k % 2 == 0: # First game of pair
game = TableFootballGame(agent_a, agent_b, verbose=False) # Set verbose=True for detailed game logs
else: # Second game, swap sides
game = TableFootballGame(agent_b, agent_a, verbose=False)
# Ensure names are correct for logging
print(f"(Sides swapped: {agent_b.name} (Team 0) vs {agent_a.name} (Team 1))")
score_a, score_b = game.play_match()
# Original agent_a and agent_b for consistent stat tracking
original_agent_a_name = agent_a_class.name
original_agent_b_name = agent_b_class.name
if k % 2 == 0: # agent_a was Team 0
gf_a, ga_a = score_a, score_b
gf_b, ga_b = score_b, score_a
else: # agent_b was Team 0 (agent_a was Team 1)
gf_a, ga_a = score_b, score_a # score_b is agent_a's score
gf_b, ga_b = score_a, score_b # score_a is agent_b's score
tournament_results.append({
"AgentA": original_agent_a_name, "AgentB": original_agent_b_name,
"ScoreA": gf_a, "ScoreB": ga_b, # Scores relative to AgentA and AgentB
"PlayedAsTeam0": agent_a.name if k%2==0 else agent_b.name # Who was actually Team0
})
print(f"Result: {original_agent_a_name} {gf_a} - {ga_b} {original_agent_b_name}")
print("\nTournament Finished!")
# Process results into a summary table
results_df = pd.DataFrame(tournament_results)
# Initialize summary statistics
summary = {agent.name: {"P":0, "W":0, "D":0, "L":0, "GF":0, "GA":0, "GD":0, "Pts":0} for agent in agents_list}
for _, row in results_df.iterrows():
agent_a_name = row["AgentA"]
agent_b_name = row["AgentB"]
score_a = row["ScoreA"]
score_b = row["ScoreB"]
# Update stats for Agent A
summary[agent_a_name]["P"] += 1
summary[agent_a_name]["GF"] += score_a
summary[agent_a_name]["GA"] += score_b
if score_a > score_b:
summary[agent_a_name]["W"] += 1
summary[agent_a_name]["Pts"] += 3
elif score_a < score_b:
summary[agent_a_name]["L"] += 1
else:
summary[agent_a_name]["D"] += 1
summary[agent_a_name]["Pts"] += 1
# Update stats for Agent B
summary[agent_b_name]["P"] += 1
summary[agent_b_name]["GF"] += score_b
summary[agent_b_name]["GA"] += score_a
if score_b > score_a:
summary[agent_b_name]["W"] += 1
summary[agent_b_name]["Pts"] += 3
elif score_b < score_a:
summary[agent_b_name]["L"] += 1
else:
summary[agent_b_name]["D"] += 1
summary[agent_b_name]["Pts"] += 1
for agent_name in summary:
summary[agent_name]["GD"] = summary[agent_name]["GF"] - summary[agent_name]["GA"]
summary_df = pd.DataFrame.from_dict(summary, orient='index')
summary_df = summary_df.sort_values(by=["Pts", "GD", "GF"], ascending=False)
print("\nTournament Summary Table:")
print(summary_df)