QDpy
Loading...
Searching...
No Matches
game_rock_paper_scissors.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Use win and draw probabilities as opponent-specific behaviour descriptors."""
6
7from itertools import product
8
9import numpy as np
10
11from qdpy.algorithms import MatchResult, game_search
12
13
14def probabilities(genome):
15 """Normalise three strategy weights, using uniform play for a zero vector."""
16 weights = np.asarray(genome)
17 total = weights.sum()
18 return weights / total if total else np.full(3, 1 / 3)
19
20
21def play(red, blue):
22 """Return each side's expected payoff and its win and draw probabilities."""
23 red = probabilities(red)
24 blue = probabilities(blue)
25 red_win = red @ np.roll(blue, 1)
26 blue_win = blue @ np.roll(red, 1)
27 draw = red @ blue
28 payoff = red_win - blue_win
29 return MatchResult((payoff, -payoff), ((red_win, draw), (blue_win, draw)))
30
31
32def score_against_panel(round_result):
33 """Measure coverage and worst payoff for the uniform elite mixture."""
34 panel = np.eye(3)
35 side = 0 if round_result.side == "red" else 1
36 payoffs = np.empty((len(round_result.representatives), len(panel)))
37 cells = set()
38 for row, opponent_index in product(range(len(payoffs)), range(len(panel))):
39 strategy = round_result.representatives[row].genome
40 opponent = panel[opponent_index]
41 match = play(strategy, opponent) if side == 0 else play(opponent, strategy)
42 payoffs[row, opponent_index] = match.fitness[side]
43 cell = tuple(min(7, int(value * 8)) for value in match.descriptors[side])
44 cells.add(cell)
45 return len(cells), float(payoffs.mean(axis=0).min())
46
47
48if __name__ == "__main__":
49 result = game_search(play, dimensions=(3, 3), rounds=2, matches_per_round=24,
50 task_count=3, cells_per_task=4, seed=42)
51 print(f"Search matches: {result.search_attempts}")
52 print(f"Bootstrap matches: {result.tournament_attempts}")
53 for round_result in result.rounds:
54 coverage, worst_payoff = score_against_panel(round_result)
55 print(f"{round_result.side.title()}: {len(round_result.representatives)} strategies, "
56 f"{coverage}/64 panel cells, worst panel payoff {worst_payoff:.3f}")