incognitolm commited on
Commit
14b2d0a
·
verified ·
1 Parent(s): 86bf0b6

Delete app (1).py

Browse files
Files changed (1) hide show
  1. app (1).py +0 -386
app (1).py DELETED
@@ -1,386 +0,0 @@
1
- from fastapi import FastAPI, Request, HTTPException
2
- from fastapi.middleware.cors import CORSMiddleware
3
- import uvicorn
4
- import random
5
-
6
- app = FastAPI()
7
-
8
- # Enable CORS
9
- app.add_middleware(
10
- CORSMiddleware,
11
- allow_origins=["*"],
12
- allow_credentials=True,
13
- allow_methods=["*"],
14
- allow_headers=["*"],
15
- )
16
-
17
- games = {}
18
-
19
- @app.post("/api/createGame")
20
- async def create_game(request: Request):
21
- data = await request.json()
22
- pin = data.get("pin")
23
- player_name = data.get("playerName")
24
-
25
- if not pin or not player_name:
26
- raise HTTPException(status_code=400, detail="PIN and player name are required.")
27
-
28
- if pin in games:
29
- raise HTTPException(status_code=400, detail="Game already exists.")
30
-
31
- # Initialize permissions as a dictionary with proper keys.
32
- games[pin] = {
33
- "pin": pin,
34
- "players": [player_name],
35
- "gameStarted": False,
36
- "turn": player_name,
37
- "currentAction": None,
38
- "currentChallenge": None,
39
- "pendingCardLoss": None,
40
- "votes": [],
41
- "permissions": {player_name: {"steal": True, "gain": True}}
42
- }
43
-
44
- return {"success": True, "message": "Game created successfully!"}
45
-
46
- @app.get("/api/test")
47
- async def test():
48
- return {"success": True}
49
-
50
- @app.get("/api/getGames")
51
- async def getGames():
52
- return {"success": True, "data": games}
53
-
54
- @app.get("/api/gameData")
55
- async def get_game_data(pin: str):
56
- game = games.get(pin)
57
- if not game:
58
- raise HTTPException(status_code=404, detail="Game not found.")
59
- return {"success": True, "game": game}
60
-
61
- @app.put("/api/gameData")
62
- async def update_game_data(request: Request):
63
- data = await request.json()
64
- pin = data.get("pin")
65
-
66
- if not pin or pin not in games:
67
- raise HTTPException(status_code=404, detail="Game not found.")
68
-
69
- games[pin].update(data)
70
- return {"success": True, "message": "Game updated successfully!"}
71
-
72
- @app.get("/api/getGameStatus")
73
- async def get_game_status(pin: str):
74
- game = games.get(pin)
75
- if not game:
76
- raise HTTPException(status_code=404, detail="Game not found.")
77
- return {"success": True, "game": game}
78
-
79
- @app.post("/api/handleAction")
80
- async def handle_action(request: Request):
81
- data = await request.json()
82
- pin = data.get("pin")
83
- player = data.get("player")
84
- action = data.get("action")
85
- target = data.get("target")
86
- response = data.get("response")
87
- challenge = data.get("challenge")
88
-
89
- if pin not in games:
90
- raise HTTPException(status_code=404, detail="Game not found.")
91
-
92
- game = games[pin]
93
-
94
- if action == 'getStatus':
95
- return {"success": True, "challenge": game.get("challenge", None)}
96
-
97
- if action == 'steal':
98
- if game["permissions"].get(player, {}).get("steal", True):
99
- game["challenge"] = {
100
- "action": 'steal',
101
- "challenger": player,
102
- "target": target,
103
- "challengeType": 'steal',
104
- "status": 'pending'
105
- }
106
- game["permissions"][player]["steal"] = False
107
- return {"success": True, "message": f"Steal initiated by {player} targeting {target}. Awaiting response from {target}."}
108
- else:
109
- return {"success": False, "message": "You can only steal once per turn."}
110
-
111
- if action == 'coup':
112
- player_data = next((p for p in game["players"] if p["name"] == player), None)
113
- if not player_data:
114
- return {"success": False, "message": "Player not found."}
115
- if player_data["coins"] < 7:
116
- return {"success": False, "message": "You don't have enough coins to coup another player."}
117
- player_data["coins"] -= 7
118
- game["challenge"] = {
119
- "action": 'coup',
120
- "challenger": player,
121
- "target": target,
122
- "challengeType": 'coup',
123
- "status": 'choose'
124
- }
125
- return {"success": True, "message": f"Coup initiated by {player} targeting {target}."}
126
-
127
- if action == 'assassin':
128
- # Assassin action: must be the player's turn.
129
- if game["turn"] != player:
130
- return {"success": False, "message": "Not your turn."}
131
- # Create an assassin challenge waiting for the target's decision.
132
- game["challenge"] = {
133
- "action": "assassin",
134
- "challenger": player, # the assassin
135
- "target": target, # the chosen target
136
- "challengeType": "assassin",
137
- "status": "pending",
138
- "phase": "target_decision" # awaiting target's decision: allow/challenge/contessa
139
- }
140
- return {"success": True, "message": f"Assassin action initiated by {player} targeting {target}. Awaiting target's response."}
141
-
142
- if action == 'challengeResponse':
143
- if not game.get("challenge"):
144
- return {"success": False, "message": "No challenge pending."}
145
-
146
- # --- Handle existing steal response ---
147
- if game["challenge"]["challengeType"] == "steal":
148
- challenger_player = next(p for p in game["players"] if p["name"] == game["challenge"]["challenger"])
149
- target_player = next(p for p in game["players"] if p["name"] == game["challenge"]["target"])
150
- if response == 'accept':
151
- coins_to_steal = min(target_player["coins"], 2)
152
- target_player["coins"] -= coins_to_steal
153
- challenger_player["coins"] += coins_to_steal
154
- game["challenge"] = None
155
- return {"success": True, "message": f"Steal accepted. {coins_to_steal} coins transferred from {target_player['name']} to {challenger_player['name']}."}
156
- elif response == 'challenge':
157
- if "Captain" in challenger_player["cards"]:
158
- coins_to_steal = min(target_player["coins"], 2)
159
- target_player["coins"] -= coins_to_steal
160
- challenger_player["coins"] += coins_to_steal
161
- game["challenge"]["status"] = 'choose'
162
- game["challenge"]["challenger"] = target_player['name']
163
- game["challenge"]["target"] = challenger_player['name']
164
- return {"success": True, "message": f"Challenge failed. {target_player['name']} loses {coins_to_steal} coins to {challenger_player['name']}."}
165
- else:
166
- game["challenge"]["status"] = 'choose'
167
- return {"success": True, "message": f"Challenge successful. {challenger_player['name']} must choose a card to lose.", "challenge": game["challenge"]}
168
-
169
- # --- Handle Ambassador response (existing) ---
170
- elif game["challenge"]["challengeType"] == "ambassador":
171
- if response == 'allow':
172
- if "responses" not in game["challenge"]:
173
- game["challenge"]["responses"] = {}
174
- game["challenge"]["responses"][player] = 'allow'
175
- total_opponents = len(game["players"]) - 1
176
- if len(game["challenge"]["responses"]) == total_opponents:
177
- ambassador_player = next(p for p in game["players"] if p["name"] == game["challenge"]["challenger"])
178
- ambassador_player["cards"] = generate_cards()
179
- game["challenge"] = None
180
- return {"success": True, "message": f"Ambassador action accepted. {ambassador_player['name']} swaps cards with the deck."}
181
- else:
182
- return {"success": True, "message": f"{player} allowed the Ambassador action. Awaiting other responses."}
183
- elif response == 'challenge':
184
- ambassador_player = next(p for p in game["players"] if p["name"] == game["challenge"]["challenger"])
185
- if "Ambassador" in ambassador_player["cards"]:
186
- game["challenge"]["status"] = "choose"
187
- game["challenge"]["challenger"] = player # challenger loses card
188
- game["challenge"]["target"] = ambassador_player["name"]
189
- ambassador_player["cards"] = generate_cards()
190
- game["challenge"] = None
191
- return {"success": True, "message": f"Challenge failed. {player} must lose a card, while {ambassador_player['name']} swaps cards with the deck."}
192
- else:
193
- game["challenge"]["status"] = "choose"
194
- return {"success": True, "message": "Challenge successful. Ambassador user must choose a card to lose.", "challenge": game["challenge"]}
195
-
196
- # --- Handle Assassin/Contessa responses ---
197
- elif game["challenge"]["challengeType"] == "assassin":
198
- # Phase 1: target's decision on assassination
199
- if game["challenge"].get("phase") == "target_decision":
200
- if response == "allow":
201
- # Target accepts assassination: must lose one card.
202
- game["challenge"]["status"] = "choose"
203
- # Set the losing player to the target.
204
- game["challenge"]["challenger"] = game["challenge"]["target"]
205
- return {"success": True, "message": f"{game['challenge']['target']} must now choose a card to lose."}
206
- elif response == "challenge":
207
- # Target challenges the assassin's claim.
208
- assassin_player = next(p for p in game["players"] if p["name"] == game["challenge"]["challenger"])
209
- if "Assassin" in assassin_player["cards"]:
210
- # Assassin is truthful: target loses both cards.
211
- target_player = next(p for p in game["players"] if p["name"] == game["challenge"]["target"])
212
- target_player["cards"] = [] # remove all cards (eliminated)
213
- game["challenge"] = None
214
- return {"success": True, "message": f"Challenge failed. {target_player['name']} loses both cards."}
215
- else:
216
- # Assassin is lying: assassin must lose one card.
217
- game["challenge"]["status"] = "choose"
218
- game["challenge"]["challenger"] = assassin_player["name"]
219
- return {"success": True, "message": f"Challenge successful. {assassin_player['name']} must choose a card to lose.", "challenge": game["challenge"]}
220
- elif response == "contessa":
221
- # Target opts to block with Contessa. Shift phase.
222
- game["challenge"]["phase"] = "assassin_contessa"
223
- return {"success": True, "message": f"{game['challenge']['challenger']} must now choose to challenge or accept the Contessa."}
224
- # Phase 2: assassin responding to contessa claim.
225
- elif game["challenge"].get("phase") == "assassin_contessa":
226
- if response == "accept":
227
- # Assassin accepts contessa block: target loses one card.
228
- game["challenge"]["status"] = "choose"
229
- game["challenge"]["challenger"] = game["challenge"]["target"]
230
- return {"success": True, "message": f"{game['challenge']['target']} must now choose a card to lose."}
231
- elif response == "challenge":
232
- # Assassin challenges contessa.
233
- target_player = next(p for p in game["players"] if p["name"] == game["challenge"]["target"])
234
- if "Contessa" in target_player["cards"]:
235
- # Contessa is truthful: assassin loses one card.
236
- game["challenge"]["status"] = "choose"
237
- # Losing player is the assassin.
238
- game["challenge"]["challenger"] = game["challenge"]["challenger"]
239
- return {"success": True, "message": f"Contessa challenge successful. {game['challenge']['challenger']} must choose a card to lose.", "challenge": game["challenge"]}
240
- else:
241
- # Contessa is bluffing: target loses both cards.
242
- target_player["cards"] = []
243
- game["challenge"] = None
244
- return {"success": True, "message": f"Contessa challenge failed. {target_player['name']} loses both cards."}
245
-
246
- # --- Handle Foreign Aid responses ---
247
- elif game["challenge"]["challengeType"] == "foreignAid":
248
- if player == game["challenge"]["challenger"]:
249
- return {"success": False, "message": "Challenger cannot respond to their own action."}
250
- game["challenge"]["responses"][player] = response
251
- if response == "block":
252
- game["challenge"]["status"] = "blocked"
253
- game["challenge"] = None
254
- return {"success": True, "message": f"Foreign Aid blocked by {player}."}
255
- else:
256
- total_opponents = len(game["players"]) - 1
257
- if len(game["challenge"]["responses"]) == total_opponents:
258
- challenger_player = next(p for p in game["players"] if p["name"] == game["challenge"]["challenger"])
259
- challenger_player["coins"] += 2
260
- game["challenge"] = None
261
- return {"success": True, "message": f"Foreign Aid accepted. {challenger_player['name']} gains 2 coins."}
262
- else:
263
- return {"success": True, "message": f"{player} allowed Foreign Aid. Awaiting other responses."}
264
-
265
- if action == 'ambassador':
266
- if game["turn"] != player:
267
- return {"success": False, "message": "Not your turn."}
268
- game["challenge"] = {
269
- "action": "ambassador",
270
- "challenger": player,
271
- "challengeType": "ambassador",
272
- "status": "pending",
273
- "responses": {}
274
- }
275
- return {"success": True, "message": f"Ambassador action initiated by {player}. Waiting for opponents to respond."}
276
-
277
- if action == 'choose':
278
- acting_player = next((p for p in game["players"] if p["name"] == game["challenge"]["challenger"]), None)
279
- if acting_player and target in acting_player["cards"]:
280
- acting_player["cards"].remove(target)
281
- game["challenge"] = None
282
- return {"success": True, "message": f"{acting_player['name']} loses the {target} card."}
283
- else:
284
- return {"success": False, "message": f"Card {target} not found in {acting_player['name']}'s hand."}
285
-
286
- if action == 'income':
287
- player_found = False
288
- for p in game["players"]:
289
- if p["name"] == player:
290
- player_found = True
291
- if not game["permissions"].get(player, {}).get("gain", True):
292
- return {"success": False, "message": "You can only earn money once per turn."}
293
- p["coins"] += 1
294
- game["permissions"][player]["gain"] = False
295
- return {"success": True, "message": f"You now have {p['coins']} coins."}
296
- if not player_found:
297
- raise HTTPException(status_code=404, detail="Player not found in the game.")
298
-
299
- if action == 'foreignAid':
300
- if game["turn"] != player:
301
- return {"success": False, "message": "Not your turn."}
302
- if not game["permissions"].get(player, {}).get("gain", True):
303
- return {"success": False, "message": "You can only earn money once per turn."}
304
- game["challenge"] = {
305
- "action": "foreignAid",
306
- "challenger": player,
307
- "challengeType": "foreignAid",
308
- "responses": {},
309
- "status": "pending"
310
- }
311
- game["permissions"][player]["gain"] = False
312
- return {"success": True, "message": f"Foreign Aid initiated by {player}. Waiting for opponents to respond."}
313
-
314
- if action == 'foreignAidResponse':
315
- if not game.get("challenge") or game["challenge"].get("challengeType") != "foreignAid":
316
- return {"success": False, "message": "No foreign aid action pending."}
317
- if player == game["challenge"]["challenger"]:
318
- return {"success": False, "message": "Challenger cannot respond to their own action."}
319
- game["challenge"]["responses"][player] = response
320
- if response == "block":
321
- game["challenge"]["status"] = "blocked"
322
- game["challenge"] = None
323
- return {"success": True, "message": f"Foreign Aid blocked by {player}."}
324
- else:
325
- total_opponents = len(game["players"]) - 1
326
- if len(game["challenge"]["responses"]) == total_opponents:
327
- challenger_player = next(p for p in game["players"] if p["name"] == game["challenge"]["challenger"])
328
- challenger_player["coins"] += 2
329
- game["challenge"] = None
330
- return {"success": True, "message": f"Foreign Aid accepted. {challenger_player['name']} gains 2 coins."}
331
- else:
332
- return {"success": True, "message": f"{player} allowed Foreign Aid. Awaiting other responses."}
333
-
334
- return {"success": True, "message": f"Action '{action}' processed for player {player}."}
335
-
336
- @app.post("/api/joinGame")
337
- async def join_game(request: Request):
338
- data = await request.json()
339
- pin = data.get("pin")
340
- player_name = data.get("playerName")
341
-
342
- game = games.get(pin)
343
- if not game:
344
- raise HTTPException(status_code=404, detail="Game not found.")
345
-
346
- # Prevent duplicate player names.
347
- if player_name in game["permissions"]:
348
- raise HTTPException(status_code=400, detail="Player name already taken.")
349
-
350
- game["players"].append(player_name)
351
- # Properly initialize the new player's permissions.
352
- game["permissions"][player_name] = {"steal": True, "gain": True}
353
-
354
- return {"success": True, "message": "Player joined successfully!"}
355
-
356
- @app.put("/api/startGame")
357
- async def start_game(request: Request):
358
- data = await request.json()
359
- pin = data.get("pin")
360
-
361
- game = games.get(pin)
362
- if not game:
363
- raise HTTPException(status_code=404, detail="Game not found.")
364
-
365
- if game["gameStarted"]:
366
- raise HTTPException(status_code=400, detail="Game has already started.")
367
-
368
- if len(game["players"]) == 0:
369
- raise HTTPException(status_code=400, detail="No players in the game.")
370
-
371
- # Initialize players with 2 coins and cards.
372
- game["players"] = [{"name": name, "coins": 2, "cards": generate_cards()} for name in game["players"]]
373
- # Reset permissions to a dictionary with proper keys for each player.
374
- game["permissions"] = {player["name"]: {"steal": True, "gain": True} for player in game["players"]}
375
- game["gameStarted"] = True
376
- game["turn"] = game["players"][0]["name"]
377
-
378
- return {"success": True, "message": "Game started successfully!"}
379
-
380
- def generate_cards():
381
- cards = ['Duke', 'Assassin', 'Captain', 'Ambassador', 'Contessa']
382
- shuffled = sorted(cards, key=lambda x: 0.5 - random.random())
383
- return [shuffled[0], shuffled[1]]
384
-
385
- if __name__ == "__main__":
386
- uvicorn.run(app, host="0.0.0.0", port=8000)