File size: 5,768 Bytes
26d2e1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, Request, HTTPException
import uvicorn

app = FastAPI()

games = {}

@app.post("/api/createGame")
async def create_game(request: Request):
    data = await request.json()
    pin = data.get("pin")
    player_name = data.get("playerName")

    if not pin or not player_name:
        raise HTTPException(status_code=400, detail="PIN and player name are required.")

    if pin in games:
        raise HTTPException(status_code=400, detail="Game already exists.")

    games[pin] = {
        "pin": pin,
        "players": [player_name],
        "gameStarted": False,
        "turn": player_name,
        "currentAction": None,
        "currentChallenge": None,
        "pendingCardLoss": None,
        "votes": []
    }

    return {"success": True, "message": "Game created successfully!"}

@app.get("/api/gameData")
async def get_game_data(pin: str):
    game = games.get(pin)
    if not game:
        raise HTTPException(status_code=404, detail="Game not found.")
    return {"success": True, "game": game}

@app.put("/api/gameData")
async def update_game_data(request: Request):
    data = await request.json()
    pin = data.get("pin")

    if not pin or pin not in games:
        raise HTTPException(status_code=404, detail="Game not found.")

    games[pin].update(data)
    return {"success": True, "message": "Game updated successfully!"}

@app.post("/api/getGameStatus")
async def get_game_status(pin: str):
    game = games.get(pin)
    if not game:
        raise HTTPException(status_code=404, detail="Game not found.")
    return {"success": True, "game": game}

@app.post("/api/handleAction")
async def handle_action(request: Request):
    data = await request.json()
    pin = data.get("pin")
    player = data.get("player")
    action = data.get("action")
    target = data.get("target")
    response = data.get("response")
    challenge = data.get("challenge")

    if pin not in games:
        raise HTTPException(status_code=404, detail="Game not found.")

    game = games[pin]

    if action == 'getStatus':
        return {"success": True, "challenge": game.get("challenge", None)}

    if action == 'steal':
        game["challenge"] = {
            "action": 'steal',
            "challenger": player,
            "target": target,
            "challengeType": 'steal',
            "status": 'pending'
        }
        return {"success": True, "message": f"Steal initiated by {player} targeting {target}. Awaiting response from {target}."}

    if action == 'challengeResponse':
        if not game.get("challenge"):
            return {"success": False, "message": "No challenge pending."}

        challenger = next(p for p in game["players"] if p["name"] == game["challenge"]["challenger"])
        target_player = next(p for p in game["players"] if p["name"] == game["challenge"]["target"])

        if response == 'accept':
            coins_to_steal = min(target_player["coins"], 2)
            target_player["coins"] -= coins_to_steal
            challenger["coins"] += coins_to_steal
            game["challenge"] = None
            return {"success": True, "message": f"Steal accepted. {coins_to_steal} coins transferred from {target_player['name']} to {challenger['name']}."}
        elif response == 'challenge':
            if "Captain" in challenger["cards"]:
                coins_to_steal = min(target_player["coins"], 2)
                target_player["coins"] -= coins_to_steal
                challenger["coins"] += coins_to_steal
                game["challenge"] = None
                return {"success": True, "message": f"Challenge failed. {target_player['name']} loses {coins_to_steal} coins to {challenger['name']}."}
            else:
                game["challenge"]["status"] = 'choose'
                return {"success": True, "message": f"Challenge successful. {challenger['name']} must choose a card to lose.", "challenge": game["challenge"]}

    if action == 'choose':
        challenger = next(p for p in game["players"] if p["name"] == game["challenge"]["challenger"])
        if target in challenger["cards"]:
            challenger["cards"].remove(target)
            game["challenge"] = None
            return {"success": True, "message": f"{challenger['name']} loses the {target} card."}
        else:
            return {"success": False, "message": f"Card {target} not found in {challenger['name']}'s hand."}

    return {"success": True, "message": f"Action '{action}' processed for player {player}."}

@app.post("/api/joinGame")
async def join_game(request: Request):
    data = await request.json()
    pin = data.get("pin")
    player_name = data.get("playerName")

    game = games.get(pin)
    if not game:
        raise HTTPException(status_code=404, detail="Game not found.")

    game["players"].append(player_name)
    return {"success": True, "message": "Player joined successfully!"}

@app.put("/api/startGame")
async def start_game(request: Request):
    data = await request.json()
    pin = data.get("pin")

    game = games.get(pin)
    if not game:
        raise HTTPException(status_code=404, detail="Game not found.")

    if not game["players"]:
        raise HTTPException(status_code=400, detail="No players in the game.")

    game["players"] = [{"name": name, "coins": 2, "cards": generate_cards()} for name in game["players"]]
    game["gameStarted"] = True
    game["turn"] = game["players"][0]["name"]
    
    return {"success": True, "message": "Game started successfully!"}

def generate_cards():
    cards = ['Duke', 'Assassin', 'Captain', 'Ambassador', 'Contessa']
    shuffled = sorted(cards, key=lambda x: 0.5 - random.random())
    return [shuffled[0], shuffled[1]]

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)