-
Notifications
You must be signed in to change notification settings - Fork 0
/
player_analyser.py
executable file
·199 lines (159 loc) · 5.37 KB
/
player_analyser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#!/usr/bin/env python3
from enum import Enum
import json
import html
import re
import os
import sys
import requests
# Analyse user's opening strategy
class GameType(Enum):
ALL = "all"
STANDARD = "std"
FOG = "fog"
HIGH_FUNDS = "hf"
def get_user_replays(username: str, game_type: GameType = GameType.ALL):
response = requests.get(
f"https://awbw.amarriner.com/gamescompleted.php?start=1&username={username}&type={game_type.value}",
cookies=cookie,
)
content = html.unescape(response.text)
pattern = re.compile(r'2030.php\?games_id=(\d+)&ndx=0')
game_ids = []
for game_id in re.findall(pattern, content):
game_ids.append(game_id)
return game_ids
def get_map_replays(map_id: str, game_type: GameType = GameType.ALL):
response = requests.get(
f"https://awbw.amarriner.com/gamescompleted.php?maps_id={map_id}",
cookies=cookie,
)
content = html.unescape(response.text)
pattern = re.compile(r'2030.php\?games_id=(\d+)&ndx=0')
game_ids = []
for game_id in re.findall(pattern, content):
game_ids.append(game_id)
return game_ids
def analyse_game(game_id: str, player: str, turns: int):
# Get the first turn, so we can find info like player name, CO, etc.
body = {
"gameId": game_id,
"turn": 0,
}
response = requests.post(
"https://awbw.amarriner.com/api/game/load_replay.php",
cookies=cookie,
json=body,
)
try:
players = list(response.json()["gameState"]["players"].values())
except Exception:
return {}
if player == "0" or player == players[0]["users_username"]:
player_num = 0
else:
player_num = 1
player_co = players[player_num]["co_name"]
print(f"ANALYSING GAME {game_id}. {player} playing as {player_co}")
all_units = {}
unit_count = 0
for turn in range(0 + player_num, (turns * 2) + player_num, 2):
units, captures, income = analyse_turn(game_id, turn)
if units is None:
if turn <= 1:
print("No game info")
return {}
break
for unit, num in units.items():
if unit == "Infantry":
continue
unit_count += num
if unit not in all_units:
all_units[unit] = num
else:
all_units[unit] += num
unit_ratios = {}
for key, val in all_units.items():
unit_ratios[key] = str(round(val / unit_count * 100, 2)) + "%"
print(f"=={turns}-TURN RATIOS==")
print(unit_ratios or "No non-infantry units produced")
print()
return unit_ratios
def analyse_turn(game_id: str, turn: int):
body = {
"gameId": game_id,
"turn": turn,
}
response = requests.post(
"https://awbw.amarriner.com/api/game/load_replay.php",
cookies=cookie,
json=body,
)
if response.status_code != 200:
return None, None, None
if "err" in response.json():
print(response.json()["message"])
return None, None, None
units_built, captures = analyse_actions(response.json())
# Funds leftover from LAST turn
pid = str(response.json()["gameState"]["currentTurnPId"])
player_info = response.json()["gameState"]["players"][pid]
funds = player_info["players_funds"]
income = player_info["players_income"]
print(f"Day {turn//2}. ${funds - income} leftover + ${income}. Captures: {captures}.")
return units_built, captures, income
def analyse_actions(response):
units_built = {}
captures = 0
for action in response["actions"]:
action_type = action["action"]
# BUILD
if action_type == "Build":
unit_name = action["newUnit"]["units_name"]
if unit_name in units_built:
units_built[unit_name] += 1
else:
units_built[unit_name] = 1
# CAPTURE
if action_type == "Capt":
if action["buildingInfo"]["buildings_capture"] == 20:
captures += 1
return units_built, captures
def debug_action(action):
action_type = action["action"]
if action_type == "Build":
unit_name = action["newUnit"]["units_name"]
print(f"Build {unit_name}.")
elif action_type == "Move":
unit_name = action["unit"]["units_name"]
print(f"Move {unit_name}.")
def setup():
script_dir = os.path.dirname(os.path.abspath(__file__))
cookie = json.load(open(script_dir + "/creds.json"))
if cookie["awbw_password"] is None:
print(
"Please get a password using F12 dev tools.\n",
"It should start with '%2A' or '*', followed by 40 hex characters.\n",
"Put it in creds.json."
)
exit(1)
return cookie
if __name__ == "__main__":
cookie = setup()
if len(sys.argv) > 1:
if sys.argv[1] in ("--help", "-h"):
print("Usage: {} [username]".format(sys.argv[0]))
sys.exit(1)
player_name = sys.argv[1]
else:
player_name = cookie["awbw_username"]
# TODO - arg to change mode, or turn numbers
replays = get_user_replays(player_name, GameType.FOG)
if not replays:
print("Could not find any games to analyse")
try:
for replay in replays:
analyse_game(replay, player_name, 12)
except Exception as e:
print("Exception. Exiting.")
print(e)