forked from elu-lab/SpyGame
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.py
More file actions
286 lines (235 loc) · 6.03 KB
/
util.py
File metadata and controls
286 lines (235 loc) · 6.03 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import json
from agent import *
from typing import List, Union
from numpy.random import randint
from dataclasses import dataclass
from collections import defaultdict
import pandas as pd
ERR_TOLERANCE = 4
@dataclass
class Chat:
speaker: Agent
utterance: str
@dataclass
class Question:
questioner: Player
answerer: Player
question: str
@dataclass
class Accusation:
accuser: Player
suspect: Player
overt_reason: str
@dataclass
class Guess:
guessed: bool
location: str
@dataclass
class Answer:
questioner: Player
answerer: Player
question: str
answer: str
@dataclass
class Vote:
voter: Player
vote: bool
underlying_reason: str
@dataclass
class Announcement:
announcer: Host
utterance: str
@dataclass
class TurnResult:
ended: bool
end_type: Union["Accusation", "Guess", None]
winner: Union["Spy", "Citizen", None]
next_turn_leader: Union[None, Player]
class VoteResult:
def __init__(self, vote_list: List[Vote]):
for vote in vote_list:
if not vote.vote:
self.unanimity = False
return
self.unanimity = True
def build_chat_history(chat_list: List[Chat]):
chat_history = ""
for chat in chat_list:
chat_history += f"""
{chat.speaker.name}: {chat.utterance}"""
return chat_history
def cut_formatted_response(formatted_response: str):
start = formatted_response.find("{")
end = formatted_response.rfind("}")
if start > -1 and end > -1:
return formatted_response[start : end + 1]
else:
return formatted_response
def save_game_info(
game_id: str, player_list, location: str, citizen_llm: str, spy_llm: str
):
import os
txt_dir = "log/" + game_id + "/"
if not os.path.exists(txt_dir):
os.makedirs(txt_dir)
txt_dir = txt_dir + "game_info.txt"
f = open(txt_dir, "a")
f.write(
f"""
==========
GAME INFO
=========="""
)
f.write(f"\ncitizen llm: {citizen_llm}\nspy_llm: {spy_llm}")
f.write(f"\nlocation: {location}\n==========")
for player in player_list:
f.write(
f"\nName: {player.name}, role: {player.role}, virtual role: {player.virtual_role}"
)
f.write("\n")
f.write("=" * 10)
f.close()
def save_failed_game_info(game_id: str, err: str):
import os
txt_dir = "log/" + game_id + "/"
end_condition = "Fail"
if not os.path.exists(txt_dir):
os.makedirs(txt_dir)
txt_dir = txt_dir + "game_info.txt"
f = open(txt_dir, "a")
f.write(
f"""
==========
GAME END CONDITION
==========
{end_condition}
==========
Failed Error
==========
{err}
==========
"""
)
f.close()
def save_successed_game_info(game_id: str, spy, winner: str, end_turn: int):
end_condition = "Success"
import os
txt_dir = "log/" + game_id + "/"
if not os.path.exists(txt_dir):
os.makedirs(txt_dir)
txt_dir = txt_dir + "game_info.txt"
f = open(txt_dir, "a")
f.write(
f"""
==========
GAME END CONDITION
==========
{end_condition}
END TURN: {end_turn}
WINNER: {winner}
SPY FIRST NOTICED LOCATION TURN: {spy.first_noticed_location_turn}
SPY FIRST NOTICED LOCATION (GUESSING): {spy.first_noticed_location}
==========
"""
)
def save_chat_log(game_id, chat_list: List[Chat]):
import os
txt_dir = "log/" + game_id + "/"
if not os.path.exists(txt_dir):
os.makedirs(txt_dir)
txt_dir = txt_dir + "conversation.txt"
f = open(txt_dir, "a")
for chat in chat_list:
f.write(
f"\n{chat.speaker.name}({chat.speaker.role})({chat.speaker.virtual_role}): {chat.utterance}\n"
)
f.close()
def save_accusation_log(game_id, accusation_list):
import os
txt_dir = "log/" + game_id + "/"
if not os.path.exists(txt_dir):
os.makedirs(txt_dir)
txt_dir = txt_dir + "game_info.txt"
f = open(txt_dir, "a")
f.write(
f"""
==========
Accusation Log
=========="""
)
for log in accusation_list:
accuser = log[0]
accused = log[1]
f.write(
f"""\nAccuser: {accuser.name}({accuser.role}), Accused: {accused.name}({accused.role})"""
)
f.write(
f"""
=========="""
)
f.close()
def init_csv(game_id: str):
import os
csv_dir = "log/" + game_id + "/"
if not os.path.exists(csv_dir):
os.makedirs(csv_dir)
csv_dir = csv_dir + "log.csv"
pd.DataFrame(
{
"speaker": [],
"role": [],
"virtual_role": [],
"raw_response": [],
"formatted_response": [],
"utterance": [],
"trial": [],
}
).to_csv(csv_dir, index=False)
return
def update_csv(
game_id: str,
speaker: str,
role: str,
virtual_role,
raw_response: str,
formatted_response: str,
utterance: str,
trial: int,
):
csv_dir = "log/" + game_id + "/log.csv"
new_data = {
"speaker": [speaker],
"role": [role],
"virtual_role": [virtual_role],
"raw_response": [raw_response],
"formatted_response": [formatted_response],
"utterance": [utterance],
"trial": [trial],
}
df = pd.DataFrame(new_data)
df.to_csv(csv_dir, mode="a", index=False, header=False)
return
def set_env(location_id: int):
f = open("cards.json")
cards = json.load(f)
f.close()
location: str = cards["location"][location_id]
roles: List[str] = cards["role"][location_id]
return location, roles
def set_agents(citizen_llm: str, spy_llm: str, virtual_role_list: List[str]):
mafia_id = randint(1, 8)
citizen_list = []
spy = None
for i in range(1, 8):
if i == mafia_id:
spy = Spy("Player" + str(i), spy_llm)
else:
citizen_list.append(
Citizen("Player" + str(i), citizen_llm, virtual_role_list[i - 1])
)
return citizen_list, spy
def get_agent_by_name(name: str, player_list: List[Player]):
for player in player_list:
if player.name == name:
return player
return None