ilyassh commited on
Commit
5b8571f
·
verified ·
1 Parent(s): aac7848

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +160 -49
app.py CHANGED
@@ -1,4 +1,4 @@
1
-
2
 
3
  import random
4
  import gradio as gr
@@ -27,18 +27,18 @@ weapons = ["Candlestick", "Dagger", "Lead Pipe", "Revolver", "Rope", "Wrench", "
27
  locations = ["Kitchen", "Ballroom", "Conservatory", "Dining Room", "Library", "Study", "Billiard Room", "Lounge"]
28
 
29
  possible_personalities = [
30
- {"description": "stern and suspicious", "hot_headed": False},
31
- {"description": "charming but evasive", "hot_headed": False},
32
- {"description": "intellectual and nervous", "hot_headed": False},
33
- {"description": "gracious but secretive", "hot_headed": False},
34
- {"description": "amiable yet deceptive", "hot_headed": False},
35
- {"description": "hot-headed and impulsive", "hot_headed": True},
36
- {"description": "calm and collected", "hot_headed": False},
37
- {"description": "mysterious and aloof", "hot_headed": False},
38
- {"description": "jovial but cunning", "hot_headed": False},
39
- {"description": "nervous and jittery", "hot_headed": False},
40
- {"description": "sarcastic and witty", "hot_headed": False},
41
- {"description": "arrogant and dismissive", "hot_headed": True}
42
  ]
43
 
44
  suspects = {}
@@ -50,7 +50,11 @@ game_state = {
50
  "is_game_over": False,
51
  "clues": [],
52
  "history": [],
53
- "accused": False
 
 
 
 
54
  }
55
 
56
  def initialize_game():
@@ -61,37 +65,52 @@ def initialize_game():
61
  game_state["clues"] = []
62
  game_state["history"] = []
63
  game_state["accused"] = False
 
 
 
 
64
  random.shuffle(possible_personalities)
65
  alibi_locations = random.sample(locations, len(suspect_names))
66
- alibis = {}
 
67
  for i, suspect_name in enumerate(suspect_names):
68
  suspect = {
69
  "name": suspect_name,
70
  "is_murderer": suspect_name == game_state["murderer"],
71
  "personality": possible_personalities[i % len(possible_personalities)]["description"],
72
  "hot_headed": possible_personalities[i % len(possible_personalities)]["hot_headed"],
 
73
  "anger_level": 0,
 
74
  "alibi_location": alibi_locations[i],
75
  "alibi_with": [],
76
- "knowledge": ""
 
 
77
  }
78
  suspects[suspect_name] = suspect
79
  for suspect in suspects.values():
80
  others_in_same_location = [s["name"] for s in suspects.values() if s["alibi_location"] == suspect["alibi_location"] and s["name"] != suspect["name"]]
81
  suspect["alibi_with"] = others_in_same_location
 
 
 
 
82
  for suspect in suspects.values():
83
  suspect["knowledge"] = generate_knowledge(suspect)
84
  print(f"Debug: Murderer is {game_state['murderer']}, Weapon is {game_state['weapon']}, Location is {game_state['location']}")
85
  for suspect in suspects.values():
86
- print(f"Debug: {suspect['name']} - Personality: {suspect['personality']}, Hot-headed: {suspect['hot_headed']}, Alibi: {suspect['alibi_location']} with {', '.join(suspect['alibi_with'])}")
87
 
88
  def generate_knowledge(suspect):
 
 
89
  if suspect["is_murderer"]:
90
  suspect["alibi_location"] = random.choice([loc for loc in locations if loc != game_state["location"]])
91
  suspect["alibi_with"] = []
92
- knowledge = "You are the murderer. Lie about your alibi and deflect suspicion. You have no knowledge of the real weapon or location."
93
  else:
94
- knowledge = f"You were in the {suspect['alibi_location']} with {', '.join(suspect['alibi_with'])} during the murder."
95
  if random.choice([True, False]):
96
  knowledge += f" You know that the weapon is the {game_state['weapon']}."
97
  if random.choice([True, False]):
@@ -100,16 +119,32 @@ def generate_knowledge(suspect):
100
 
101
  def get_ai_response(suspect_name, player_input):
102
  suspect = suspects[suspect_name]
103
- suspect["anger_level"] += 1
 
 
 
 
 
 
 
 
 
 
 
104
  personality = suspect["personality"]
105
  knowledge = suspect["knowledge"]
106
  anger_level = suspect["anger_level"]
107
  hot_headed = suspect["hot_headed"]
 
108
  system_prompt = f"You are {suspect_name}, who is {personality}. {knowledge}"
109
- if hot_headed:
110
- system_prompt += f" You are getting angrier each time you are questioned. Your anger level is {anger_level}."
111
  if suspect["is_murderer"]:
112
  system_prompt += " You are the murderer and will lie to protect yourself."
 
 
 
 
113
  user_message = f"The detective asks: \"{player_input}\" As {suspect_name}, respond in first person, staying in character."
114
  messages = [
115
  {"role": "system", "content": system_prompt},
@@ -118,45 +153,48 @@ def get_ai_response(suspect_name, player_input):
118
  response = llm_inference(messages)
119
  return response.strip()
120
 
 
 
 
 
 
 
 
121
  def get_group_response(suspect_names_list, player_input):
122
  responses = []
123
  for suspect_name in suspect_names_list:
124
- suspect = suspects[suspect_name]
125
- suspect["anger_level"] += 1
126
- personality = suspect["personality"]
127
- knowledge = suspect["knowledge"]
128
- anger_level = suspect["anger_level"]
129
- hot_headed = suspect["hot_headed"]
130
- relationships = get_relationships(suspect_name, suspect_names_list)
131
- system_prompt = f"You are {suspect_name}, who is {personality}. {knowledge} {relationships}"
132
- if hot_headed:
133
- system_prompt += f" You are getting angrier each time you are questioned. Your anger level is {anger_level}."
134
- if suspect["is_murderer"]:
135
- system_prompt += " You are the murderer and will lie to protect yourself."
136
- user_message = f"The detective asks: \"{player_input}\" As {suspect_name}, respond in first person, staying in character, and interact with the other suspects present."
137
- messages = [
138
- {"role": "system", "content": system_prompt},
139
- {"role": "user", "content": user_message}
140
- ]
141
- response = llm_inference(messages)
142
  responses.append(f"**{suspect_name}:** {response.strip()}")
143
  return "\n\n".join(responses)
144
 
145
- def get_relationships(suspect_name, suspect_names_list):
146
- other_suspects = [name for name in suspect_names_list if name != suspect_name]
147
- if other_suspects:
148
- relationships = f"You are currently with {', '.join(other_suspects)}. You might have personal opinions about them, and you may attempt to shift blame onto them."
149
- else:
150
- relationships = ""
151
- return relationships
152
-
153
  def process_input(player_input):
154
  if game_state["is_game_over"]:
155
  return "The game is over. Please restart to play again.", game_state["history"]
156
  if game_state["accused"]:
157
  return "You have already made an accusation. Please restart to play again.", game_state["history"]
158
  game_state["history"].append(("Detective", player_input))
159
- if "accuse" in player_input.lower():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  game_state["accused"] = True
161
  result = handle_accusation(player_input)
162
  game_state["history"].append(("System", result))
@@ -192,6 +230,55 @@ def extract_clues(ai_response):
192
  if clue not in game_state["clues"]:
193
  game_state["clues"].append(clue)
194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  def handle_accusation(player_input):
196
  suspect_guess = None
197
  weapon_guess = None
@@ -217,6 +304,22 @@ def handle_accusation(player_input):
217
  game_state["is_game_over"] = True
218
  return f"Incorrect accusation! You lose. The real murderer was {game_state['murderer']} with the {game_state['weapon']} in the {game_state['location']}."
219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  def chat_interface(player_input):
221
  response, history = process_input(player_input)
222
  chat_history = ""
@@ -235,9 +338,12 @@ def get_debug_info():
235
  info += f"Personality: {suspect['personality']}\n"
236
  info += f"Hot-headed: {suspect['hot_headed']}\n"
237
  info += f"Anger Level: {suspect['anger_level']}\n"
 
238
  info += f"Is Murderer: {suspect['is_murderer']}\n"
239
  info += f"Alibi Location: {suspect['alibi_location']}\n"
240
  info += f"Alibi With: {', '.join(suspect['alibi_with'])}\n"
 
 
241
  info += f"Knowledge: {suspect['knowledge']}\n\n"
242
  debug_info += info
243
  return debug_info
@@ -255,6 +361,11 @@ with gr.Blocks() as demo:
255
  gr.Markdown("## Commands")
256
  gr.Markdown("- **Ask a question to a suspect**: Include the suspect's name in your question.\n Example: *\"Miss Scarlett, where were you during the evening?\"*")
257
  gr.Markdown("- **Interrogate multiple suspects**: Include multiple suspects' names in your question.\n Example: *\"Colonel Mustard and Mrs. Peacock, what can you tell me about the night?\"*")
 
 
 
 
 
258
  gr.Markdown("- **Make an accusation**: Include the word *\"accuse\"*.\n Example: *\"I accuse Colonel Mustard with the Rope in the Study.\"*")
259
  player_input = gr.Textbox(lines=1, label="Your Input")
260
  send_button = gr.Button("Send")
 
1
+ # murder_mystery.py
2
 
3
  import random
4
  import gradio as gr
 
27
  locations = ["Kitchen", "Ballroom", "Conservatory", "Dining Room", "Library", "Study", "Billiard Room", "Lounge"]
28
 
29
  possible_personalities = [
30
+ {"description": "stern and suspicious", "hot_headed": False, "anger_threshold": 5},
31
+ {"description": "charming but evasive", "hot_headed": False, "anger_threshold": 7},
32
+ {"description": "intellectual and nervous", "hot_headed": False, "anger_threshold": 6},
33
+ {"description": "gracious but secretive", "hot_headed": False, "anger_threshold": 6},
34
+ {"description": "amiable yet deceptive", "hot_headed": False, "anger_threshold": 8},
35
+ {"description": "hot-headed and impulsive", "hot_headed": True, "anger_threshold": 3},
36
+ {"description": "calm and collected", "hot_headed": False, "anger_threshold": 9},
37
+ {"description": "mysterious and aloof", "hot_headed": False, "anger_threshold": 5},
38
+ {"description": "jovial but cunning", "hot_headed": False, "anger_threshold": 7},
39
+ {"description": "nervous and jittery", "hot_headed": False, "anger_threshold": 5},
40
+ {"description": "sarcastic and witty", "hot_headed": False, "anger_threshold": 6},
41
+ {"description": "arrogant and dismissive", "hot_headed": True, "anger_threshold": 4}
42
  ]
43
 
44
  suspects = {}
 
50
  "is_game_over": False,
51
  "clues": [],
52
  "history": [],
53
+ "accused": False,
54
+ "turns": 0,
55
+ "searched_locations": [],
56
+ "eavesdropped": False,
57
+ "bluffed": False
58
  }
59
 
60
  def initialize_game():
 
65
  game_state["clues"] = []
66
  game_state["history"] = []
67
  game_state["accused"] = False
68
+ game_state["turns"] = 0
69
+ game_state["searched_locations"] = []
70
+ game_state["eavesdropped"] = False
71
+ game_state["bluffed"] = False
72
  random.shuffle(possible_personalities)
73
  alibi_locations = random.sample(locations, len(suspect_names))
74
+ motives = ["inheritance", "jealousy", "revenge", "secret affair", "business rivalry", "blackmail"]
75
+ relationships = ["friends", "colleagues", "family", "rivals", "acquaintances"]
76
  for i, suspect_name in enumerate(suspect_names):
77
  suspect = {
78
  "name": suspect_name,
79
  "is_murderer": suspect_name == game_state["murderer"],
80
  "personality": possible_personalities[i % len(possible_personalities)]["description"],
81
  "hot_headed": possible_personalities[i % len(possible_personalities)]["hot_headed"],
82
+ "anger_threshold": possible_personalities[i % len(possible_personalities)]["anger_threshold"],
83
  "anger_level": 0,
84
+ "trust_level": 5,
85
  "alibi_location": alibi_locations[i],
86
  "alibi_with": [],
87
+ "knowledge": "",
88
+ "motive": random.choice(motives),
89
+ "relationships": {}
90
  }
91
  suspects[suspect_name] = suspect
92
  for suspect in suspects.values():
93
  others_in_same_location = [s["name"] for s in suspects.values() if s["alibi_location"] == suspect["alibi_location"] and s["name"] != suspect["name"]]
94
  suspect["alibi_with"] = others_in_same_location
95
+ for suspect in suspects.values():
96
+ other_suspects = [s["name"] for s in suspects.values() if s["name"] != suspect["name"]]
97
+ for other in other_suspects:
98
+ suspect["relationships"][other] = random.choice(relationships)
99
  for suspect in suspects.values():
100
  suspect["knowledge"] = generate_knowledge(suspect)
101
  print(f"Debug: Murderer is {game_state['murderer']}, Weapon is {game_state['weapon']}, Location is {game_state['location']}")
102
  for suspect in suspects.values():
103
+ print(f"Debug: {suspect['name']} - Personality: {suspect['personality']}, Hot-headed: {suspect['hot_headed']}, Anger Threshold: {suspect['anger_threshold']}, Motive: {suspect['motive']}, Relationships: {suspect['relationships']}")
104
 
105
  def generate_knowledge(suspect):
106
+ details = f"You have a motive of {suspect['motive']}."
107
+ relationship_details = ". ".join([f"You are {relation} with {other}" for other, relation in suspect["relationships"].items()])
108
  if suspect["is_murderer"]:
109
  suspect["alibi_location"] = random.choice([loc for loc in locations if loc != game_state["location"]])
110
  suspect["alibi_with"] = []
111
+ knowledge = f"You are the murderer. Lie about your alibi and deflect suspicion. {details} {relationship_details}"
112
  else:
113
+ knowledge = f"You were in the {suspect['alibi_location']} with {', '.join(suspect['alibi_with'])} during the murder. {details} {relationship_details}"
114
  if random.choice([True, False]):
115
  knowledge += f" You know that the weapon is the {game_state['weapon']}."
116
  if random.choice([True, False]):
 
119
 
120
  def get_ai_response(suspect_name, player_input):
121
  suspect = suspects[suspect_name]
122
+ game_state["turns"] += 1
123
+ tone = analyze_tone(player_input)
124
+ if "accuse" in player_input.lower() or any(word in player_input.lower() for word in ["murderer", "kill", "guilty"]):
125
+ suspect["trust_level"] -= 1
126
+ else:
127
+ suspect["trust_level"] += 1
128
+ suspect["trust_level"] = max(0, min(10, suspect["trust_level"]))
129
+ if tone == "accusatory":
130
+ suspect["anger_level"] += 2
131
+ suspect["trust_level"] -= 1
132
+ else:
133
+ suspect["anger_level"] += 1
134
  personality = suspect["personality"]
135
  knowledge = suspect["knowledge"]
136
  anger_level = suspect["anger_level"]
137
  hot_headed = suspect["hot_headed"]
138
+ trust_level = suspect["trust_level"]
139
  system_prompt = f"You are {suspect_name}, who is {personality}. {knowledge}"
140
+ if hot_headed and anger_level >= suspect["anger_threshold"]:
141
+ system_prompt += f" You are extremely angry and may respond aggressively."
142
  if suspect["is_murderer"]:
143
  system_prompt += " You are the murderer and will lie to protect yourself."
144
+ if trust_level >= 7:
145
+ system_prompt += " You trust the detective and are willing to share information."
146
+ elif trust_level <= 3:
147
+ system_prompt += " You do not trust the detective and may withhold information."
148
  user_message = f"The detective asks: \"{player_input}\" As {suspect_name}, respond in first person, staying in character."
149
  messages = [
150
  {"role": "system", "content": system_prompt},
 
153
  response = llm_inference(messages)
154
  return response.strip()
155
 
156
+ def analyze_tone(player_input):
157
+ accusatory_words = ["did you", "murderer", "kill", "guilty", "crime"]
158
+ if any(word in player_input.lower() for word in accusatory_words):
159
+ return "accusatory"
160
+ else:
161
+ return "neutral"
162
+
163
  def get_group_response(suspect_names_list, player_input):
164
  responses = []
165
  for suspect_name in suspect_names_list:
166
+ response = get_ai_response(suspect_name, player_input)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  responses.append(f"**{suspect_name}:** {response.strip()}")
168
  return "\n\n".join(responses)
169
 
 
 
 
 
 
 
 
 
170
  def process_input(player_input):
171
  if game_state["is_game_over"]:
172
  return "The game is over. Please restart to play again.", game_state["history"]
173
  if game_state["accused"]:
174
  return "You have already made an accusation. Please restart to play again.", game_state["history"]
175
  game_state["history"].append(("Detective", player_input))
176
+ if player_input.lower().startswith("search"):
177
+ location = player_input[7:].strip()
178
+ result = search_location(location)
179
+ game_state["history"].append(("System", result))
180
+ return result, game_state["history"]
181
+ elif player_input.lower().startswith("eavesdrop"):
182
+ result = eavesdrop()
183
+ game_state["history"].append(("System", result))
184
+ return result, game_state["history"]
185
+ elif player_input.lower().startswith("bluff"):
186
+ result = bluff(player_input)
187
+ game_state["history"].append(("System", result))
188
+ return result, game_state["history"]
189
+ elif player_input.lower().startswith("analyze"):
190
+ result = analyze_response()
191
+ game_state["history"].append(("System", result))
192
+ return result, game_state["history"]
193
+ elif player_input.lower().startswith("reveal"):
194
+ result = endgame_reveal(player_input)
195
+ game_state["history"].append(("System", result))
196
+ return result, game_state["history"]
197
+ elif "accuse" in player_input.lower():
198
  game_state["accused"] = True
199
  result = handle_accusation(player_input)
200
  game_state["history"].append(("System", result))
 
230
  if clue not in game_state["clues"]:
231
  game_state["clues"].append(clue)
232
 
233
+ def search_location(location):
234
+ if location not in locations:
235
+ return "That location does not exist."
236
+ if location in game_state["searched_locations"]:
237
+ return "You have already searched this location."
238
+ game_state["searched_locations"].append(location)
239
+ game_state["turns"] += 1
240
+ if location == game_state["location"]:
241
+ found_weapon = f"You found the {game_state['weapon']}!"
242
+ game_state["clues"].append(found_weapon)
243
+ return f"You search the {location} and {found_weapon}"
244
+ else:
245
+ return f"You search the {location} but find nothing of interest."
246
+
247
+ def eavesdrop():
248
+ if game_state["eavesdropped"]:
249
+ return "You have already eavesdropped once."
250
+ game_state["eavesdropped"] = True
251
+ game_state["turns"] += 1
252
+ suspect1, suspect2 = random.sample(suspect_names, 2)
253
+ conversation = f"{suspect1} whispers to {suspect2}: 'I hope the detective doesn't find out about our {suspects[suspect1]['relationships'][suspect2]}.'"
254
+ extract_clues(conversation)
255
+ return f"You overhear a conversation: {conversation}"
256
+
257
+ def bluff(player_input):
258
+ game_state["bluffed"] = True
259
+ game_state["turns"] += 1
260
+ mentioned_suspects = [suspect_name for suspect_name in suspect_names if suspect_name.lower() in player_input.lower()]
261
+ if not mentioned_suspects:
262
+ return "You need to specify a suspect to bluff."
263
+ suspect_name = mentioned_suspects[0]
264
+ suspect = suspects[suspect_name]
265
+ suspect["trust_level"] -= 2
266
+ if suspect["trust_level"] <= 3:
267
+ return f"{suspect_name} doesn't believe your bluff and now trusts you even less."
268
+ else:
269
+ response = f"{suspect_name} seems unsettled by your claim and might reveal more information."
270
+ return response
271
+
272
+ def analyze_response():
273
+ game_state["turns"] += 1
274
+ puzzle = "Solve this riddle to analyze the suspect's response: What has keys but can't open locks?"
275
+ correct_answer = "piano"
276
+ player_answer = gr.Textbox(placeholder="Your Answer").launch()
277
+ if player_answer.strip().lower() == correct_answer:
278
+ return "You successfully detect that the suspect is lying!"
279
+ else:
280
+ return "You fail to detect any lies."
281
+
282
  def handle_accusation(player_input):
283
  suspect_guess = None
284
  weapon_guess = None
 
304
  game_state["is_game_over"] = True
305
  return f"Incorrect accusation! You lose. The real murderer was {game_state['murderer']} with the {game_state['weapon']} in the {game_state['location']}."
306
 
307
+ def endgame_reveal(player_input):
308
+ game_state["turns"] += 1
309
+ correctness = 0
310
+ if game_state["murderer"].lower() in player_input.lower():
311
+ correctness += 1
312
+ if game_state["weapon"].lower() in player_input.lower():
313
+ correctness += 1
314
+ if game_state["location"].lower() in player_input.lower():
315
+ correctness += 1
316
+ if correctness == 3:
317
+ game_state["is_game_over"] = True
318
+ return "Your deductions are spot on! The murderer confesses and the case is closed."
319
+ else:
320
+ game_state["is_game_over"] = True
321
+ return "Your deductions have inaccuracies. The murderer denies your claims and escapes justice."
322
+
323
  def chat_interface(player_input):
324
  response, history = process_input(player_input)
325
  chat_history = ""
 
338
  info += f"Personality: {suspect['personality']}\n"
339
  info += f"Hot-headed: {suspect['hot_headed']}\n"
340
  info += f"Anger Level: {suspect['anger_level']}\n"
341
+ info += f"Trust Level: {suspect['trust_level']}\n"
342
  info += f"Is Murderer: {suspect['is_murderer']}\n"
343
  info += f"Alibi Location: {suspect['alibi_location']}\n"
344
  info += f"Alibi With: {', '.join(suspect['alibi_with'])}\n"
345
+ info += f"Motive: {suspect['motive']}\n"
346
+ info += f"Relationships: {suspect['relationships']}\n"
347
  info += f"Knowledge: {suspect['knowledge']}\n\n"
348
  debug_info += info
349
  return debug_info
 
361
  gr.Markdown("## Commands")
362
  gr.Markdown("- **Ask a question to a suspect**: Include the suspect's name in your question.\n Example: *\"Miss Scarlett, where were you during the evening?\"*")
363
  gr.Markdown("- **Interrogate multiple suspects**: Include multiple suspects' names in your question.\n Example: *\"Colonel Mustard and Mrs. Peacock, what can you tell me about the night?\"*")
364
+ gr.Markdown("- **Search a location**: Type *\"Search [Location]\"*.\n Example: *\"Search Kitchen\"*")
365
+ gr.Markdown("- **Eavesdrop on suspects**: Type *\"Eavesdrop\"*")
366
+ gr.Markdown("- **Bluff a suspect**: Type *\"Bluff [Suspect]\"*")
367
+ gr.Markdown("- **Analyze a response**: Type *\"Analyze\"*")
368
+ gr.Markdown("- **Reveal your deductions**: Type *\"Reveal: [Your deductions]\"*")
369
  gr.Markdown("- **Make an accusation**: Include the word *\"accuse\"*.\n Example: *\"I accuse Colonel Mustard with the Rope in the Study.\"*")
370
  player_input = gr.Textbox(lines=1, label="Your Input")
371
  send_button = gr.Button("Send")