-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathmatch.py
More file actions
189 lines (158 loc) · 5.84 KB
/
match.py
File metadata and controls
189 lines (158 loc) · 5.84 KB
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
import asyncio
import time
from collections import Counter
from dataclasses import dataclass
from games import game
from jsonStream import FetchError, fetch
from logs import getLogger, getMatchLogger
from state import Chat, Client, Match, Message
from status import ClientStatus, MatchStatus
from utils import clock, ping
MOVE_TIME_LIMIT = 3
RETRY_TIME = 3
log = getLogger("match")
@dataclass
class Player:
client: Client
errors: list
index: int
def __init__(self, client: Client, index):
self.client = client
self.errors = []
self.index = index
@property
def lives(self):
return 3 - self.badMoves
@property
def badMoves(self):
return len(self.errors)
def kill(self, msg, matchState, move):
self.errors.append({"message": msg, "state": matchState, "move": move})
def __str__(self):
return str(self.client)
async def runMatch(Game, match: Match, tempo: float):
if any(
[
not r
for r in await asyncio.gather(*[ping(client) for client in match.clients])
]
):
return
log = getMatchLogger(match)
match.status = MatchStatus.RUNNING
log.info("Match Started")
states = Counter()
match.start = time.time()
players = [Player(client, i) for i, client in enumerate(match.clients)]
winner = None
matchState, next = Game([client.name for client in match.clients])
matchState["current"] = 0
match.state = matchState
chat = Chat()
match.chat = chat
current = None
other = None
states.update([str(match.state)])
def kill(player, msg, move):
log.warning(msg)
player.kill(msg, matchState, move)
chat.addMessage(Message(name="Admin", message=msg))
try:
tic = clock(period=tempo)
while all([player.lives != 0 for player in players]):
await tic()
current = players[matchState["current"]]
other = players[(matchState["current"] + 1) % 2]
try:
request = {
"request": "play",
"lives": current.lives,
"errors": current.errors,
"state": matchState,
}
response, responseTime = await fetch(
current.client, request, timeout=MOVE_TIME_LIMIT * 1.1
)
current.client.status = ClientStatus.READY
if "message" in response:
chat.addMessage(
Message(name=str(current), message=str(response["message"]))
)
if response["response"] == "move":
move = response["move"]
log.debug("{} play {}".format(current, move))
try:
matchState = next(matchState, move)
match.state = matchState
match.moves += 1
# Loop detection
k = str(match.state)
if states[k] > 2:
msg = "LOOP DETECTED !!!"
log.info(msg)
chat.addMessage(Message(name="Admin", message=msg))
raise game.GameLoop(match.state)
states.update([k])
if responseTime > MOVE_TIME_LIMIT * 1.1:
kill(
current,
"{} take too long to respond: {}s".format(
current, responseTime
),
move,
)
except game.BadMove as e:
kill(current, "This is a Bad Move. " + str(e), move)
elif response["response"] == "giveup":
msg = "{} Give Up".format(current)
log.info(msg)
chat.addMessage(Message(name="Admin", message=msg))
raise game.GameWin(other.index, matchState)
else:
kill(
current,
"response['response'] can't be {}".format(response["response"]),
None,
)
except FetchError as e:
kill(
current,
"{} unavailable ({}). Wait for {} seconds".format(
current, e, RETRY_TIME
),
None,
)
await asyncio.sleep(RETRY_TIME)
except (TypeError, KeyError) as e:
kill(
current,
"Error in the turn of {}: {}. Wait for {} seconds".format(
current, e, RETRY_TIME
),
None,
)
await asyncio.sleep(RETRY_TIME)
assert current is not None
assert other is not None
msg = "{} has done too many Bad Moves".format(current)
log.warning(msg)
chat.addMessage(Message(name="Admin", message=msg))
raise game.GameWin(other.index, matchState)
except game.GameWin as e:
match.moves += 1
winner = players[e.winner]
match.winner = winner.client
msg = "Match Done. {} Won".format(winner.client.name)
log.info(msg)
chat.addMessage(Message(name="Admin", message=msg))
except game.GameDraw:
match.moves += 1
winner = None
msg = "Match Done with no winner"
log.info(msg)
chat.addMessage(Message(name="Admin", message=msg))
match.state = None
match.end = time.time()
for i, player in enumerate(players):
match.badMoves[i] = player.badMoves
match.status = MatchStatus.DONE