| 1 | """Print paired duplicate-deal results as CSV using the project's referee.""" |
| 2 | |
| 3 | import csv |
| 4 | import os |
| 5 | import sys |
| 6 | from contextlib import contextmanager |
| 7 | from pathlib import Path |
| 8 | |
| 9 | import rlcard |
| 10 | |
| 11 | ROUTE = Path(__file__).resolve().parent |
| 12 | sys.path.insert(0, str(ROUTE.parents[1] / "referee")) |
| 13 | from play import game, player |
| 14 | |
| 15 | DEALS = range(1, 21) |
| 16 | SEATS = ("landlord", "farmer_down", "farmer_up") |
| 17 | |
| 18 | |
| 19 | class CheckedPlayer: |
| 20 | """Fail on a move the referee would otherwise replace with a fallback.""" |
| 21 | |
| 22 | def __init__(self, child, name): |
| 23 | self.child = child |
| 24 | self.name = name |
| 25 | |
| 26 | def ask(self, message): |
| 27 | move = self.child.ask(message) |
| 28 | if move not in message["raw_obs"]["actions"]: |
| 29 | raise RuntimeError(f"{self.name} returned no legal move: {move!r}") |
| 30 | return move |
| 31 | |
| 32 | |
| 33 | @contextmanager |
| 34 | def checked_player(folder, name): |
| 35 | child = player(folder) |
| 36 | try: |
| 37 | yield CheckedPlayer(child, name) |
| 38 | finally: |
| 39 | child.close() |
| 40 | |
| 41 | |
| 42 | def compare(writer, focal, opponent): |
| 43 | focal_name, focal_folder = focal |
| 44 | opponent_name, opponent_folder = opponent |
| 45 | env = rlcard.make("doudizhu") |
| 46 | with checked_player(focal_folder, focal_name) as me, checked_player( |
| 47 | opponent_folder, opponent_name |
| 48 | ) as them: |
| 49 | for deal in DEALS: |
| 50 | for seat, role in enumerate(SEATS): |
| 51 | seats = [them] * len(SEATS) |
| 52 | seats[seat] = me |
| 53 | points, _ = game(env, seats, deal) |
| 54 | writer.writerow((focal_name, opponent_name, deal, role, points[seat])) |
| 55 | |
| 56 | |
| 57 | def main(): |
| 58 | if os.environ.get("PYTHONHASHSEED") != "0" or sys.flags.ignore_environment: |
| 59 | sys.exit("Run with PYTHONHASHSEED=0 python3 -s compare.py") |
| 60 | writer = csv.writer(sys.stdout, lineterminator="\n") |
| 61 | writer.writerow(("focal", "opponent", "deal", "seat", "points")) |
| 62 | starter = ("starter", ROUTE.parent) |
| 63 | rule = ("rule", ROUTE) |
| 64 | compare(writer, starter, rule) |
| 65 | compare(writer, rule, starter) |
| 66 | |
| 67 | |
| 68 | if __name__ == "__main__": |
| 69 | main() |