streak-hunting-spreadsheet/endgames.py

70 lines
2.1 KiB
Python
Raw Normal View History

2023-11-11 01:38:37 +01:00
import json
import re
import subprocess
from typing import Dict
from pathlib import Path
DATA_FILE = Path('endgame-data.json')
if not DATA_FILE.exists():
DATA_FILE.write_text('{}')
with open(DATA_FILE, 'r') as f:
DATA: Dict = json.loads(f.read())
def analyze_game(game_id: int):
probabilities = {}
for deck_size in range(1, 16):
try:
result = subprocess.run(['./endgame-analyzer', '-g', str(game_id), '-d', str(deck_size), '-i', '0'], stdout=subprocess.PIPE, timeout=30)
except subprocess.TimeoutExpired:
return probabilities
output = result.stdout.decode('utf-8')
m = re.search('Probability with optimal play: .*/.* ~ ([0-9.]+)', output)
2023-11-11 04:20:41 +01:00
if m:
probabilities[str(deck_size)] = m.group(1)
2023-11-11 01:38:37 +01:00
return probabilities
2023-11-11 04:20:41 +01:00
2023-11-11 01:38:37 +01:00
def full_analyze_game(game_id: int):
probabilities = {}
try:
2023-11-11 04:20:41 +01:00
result = subprocess.run(['./endgame-analyzer', '-g', str(game_id), '-d', str(10), '-i', '0', '--all-clues', '-r', '--quiet'], stdout=subprocess.PIPE, timeout=180)
except subprocess.TimeoutExpired:
2023-11-11 01:38:37 +01:00
return probabilities
output = result.stdout.decode('utf-8')
2023-11-11 04:20:41 +01:00
print(output)
for m in re.finditer('Probability with ([0-9]+) cards left in deck and [0-8] clues \((.[0-8])\).*: .*/.* ~ ([0-9.]*)', output):
if m.group(1) not in probabilities.keys():
probabilities[m.group(1)] = {}
probabilities[m.group(1)][m.group(2)] = m.group(3)
2023-11-11 01:38:37 +01:00
return probabilities
2023-11-11 04:20:41 +01:00
2023-11-11 01:38:37 +01:00
def full_analyze_game_cached(game_id: int):
cached = DATA.get('all', {}).get(str(game_id), None)
if cached is not None:
return cached
result = full_analyze_game(game_id)
2023-11-11 04:20:41 +01:00
if 'all' not in DATA.keys():
DATA['all'] = {}
2023-11-11 01:38:37 +01:00
DATA['all'][game_id] = result
save_cache()
return result
def analyze_game_cached(game_id: int):
cached = DATA['normal'].get(str(game_id), None)
if cached is not None:
return cached
result = analyze_game(game_id)
DATA['normal'][game_id] = result
save_cache()
return result
def save_cache():
with open(DATA_FILE, 'w') as f:
f.writelines(json.dumps(DATA, indent=2))