koehandel / scripts /play.py
lukehola's picture
Upload folder using huggingface_hub (part 6)
08d876f verified
Raw History Blame Contribute Delete
3.1 kB
#!/usr/bin/env python3
"""Play Koehandel against the bots in your terminal.
python scripts/play.py # 1 human vs 3 heuristics
python scripts/play.py --checkpoint runs/v1/checkpoints/latest.pt # vs trained bots
python scripts/play.py --humans 2 --players 4 # 2 humans + 2 bots (local)
Hidden information is respected: when you respond to a cow-trade, the opponent's offer
is face-down (you won't see the amount) — bluffing is part of the game.
"""
import argparse
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from koehandel.agents import HeuristicAgent # noqa: E402
from koehandel.agents.human_agent import HumanAgent # noqa: E402
from koehandel.agents.neural_agent import NeuralAgent # noqa: E402
from koehandel.engine.game import KoehandelGame # noqa: E402
from koehandel.engine.scoring import final_scores # noqa: E402
def build_bots(count, checkpoint):
if checkpoint:
model = NeuralAgent.from_checkpoint(checkpoint, deterministic=True).model
return [NeuralAgent(model, deterministic=True, name=f"bot{i}") for i in range(count)]
return [HeuristicAgent(seed=100 + i) for i in range(count)]
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--players", type=int, default=4)
p.add_argument("--humans", type=int, default=1)
p.add_argument("--checkpoint", default=None)
p.add_argument("--seed", type=int, default=None)
args = p.parse_args()
if not 3 <= args.players <= 5:
sys.exit("players must be 3-5")
if not 0 <= args.humans <= args.players:
sys.exit("humans must be between 0 and players")
humans = [HumanAgent(player_label=f"Human {i+1}") for i in range(args.humans)]
bots = build_bots(args.players - args.humans, args.checkpoint)
agents = humans + bots # humans take the first seats
state = KoehandelGame.new_game(num_players=args.players, seed=args.seed)
for a in agents:
a.reset()
print(f"\nNew game: {args.humans} human(s) + {len(bots)} bot(s). "
f"Bots: {'neural' if args.checkpoint else 'heuristic'}.\n")
log_shown = 0
while not KoehandelGame.is_terminal(state):
# Show any new public log entries (what just happened).
while log_shown < len(state.log):
print(" · " + state.log[log_shown])
log_shown += 1
agent = agents[state.current_player]
action = agent.act(state)
KoehandelGame.step(state, action)
while log_shown < len(state.log):
print(" · " + state.log[log_shown])
log_shown += 1
scores = final_scores(state)
print("\n" + "=" * 60)
print("GAME OVER — final scores:")
ranking = sorted(range(args.players), key=lambda i: scores[i], reverse=True)
for rank, pi in enumerate(ranking, 1):
who = agents[pi].name
print(f" {rank}. P{pi} ({who}): {scores[pi]}")
winner = ranking[0]
print(f"\nWinner: P{winner} ({agents[winner].name})!")
if __name__ == "__main__":
main()