-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
251 lines (211 loc) · 8.51 KB
/
Copy pathapi.py
File metadata and controls
251 lines (211 loc) · 8.51 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
import asyncio
import random
from fastapi import FastAPI, Query, HTTPException
from fastapi.responses import PlainTextResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI(
title="Games MCP HTTP API",
version="1.0.0",
description="A simple API for coin flipping and dice rolling games",
docs_url="/docs",
redoc_url="/redoc"
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Configure this for production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# === UTILITY FUNCTIONS ===
def format_coin_result(result):
"""Format coin flip result with emoji."""
emoji = "🪙" if result == "HEADS" else "🔘"
return f"{emoji} {result}"
def format_dice_results(rolls):
"""Format dice roll results with emojis."""
dice_emoji = {1: "⚀", 2: "⚁", 3: "⚂", 4: "⚃", 5: "⚄", 6: "⚅"}
formatted = [f"{dice_emoji.get(roll, '🎲')} {roll}" for roll in rolls]
return formatted
async def flip_coin(flips: str = "1") -> str:
"""Flip a coin one or more times and return the results."""
try:
# Validate and convert flips parameter
if not flips.strip():
num_flips = 1
else:
num_flips = int(flips)
# Validate range
if num_flips < 1:
return "❌ Error: Number of flips must be at least 1"
if num_flips > 100:
return "❌ Error: Maximum 100 flips allowed"
# Perform coin flips
results = [random.choice(["HEADS", "TAILS"]) for _ in range(num_flips)]
# Count results
heads_count = results.count("HEADS")
tails_count = results.count("TAILS")
# Format output
if num_flips == 1:
return f"✅ Coin Flip Result: {format_coin_result(results[0])}"
else:
result_list = "\n".join([f" Flip {i+1}: {format_coin_result(r)}" for i, r in enumerate(results)])
return f"""✅ Coin Flip Results ({num_flips} flips):
{result_list}
📊 Summary:
- Heads: {heads_count} ({heads_count/num_flips*100:.1f}%)
- Tails: {tails_count} ({tails_count/num_flips*100:.1f}%)"""
except ValueError:
return f"❌ Error: Invalid number of flips: {flips}"
except Exception as e:
return f"❌ Error: {str(e)}"
async def roll_dice(dice: str = "1", sides: str = "6") -> str:
"""Roll one or more dice with a specified number of sides."""
try:
# Validate and convert parameters
num_dice = int(dice) if dice.strip() else 1
num_sides = int(sides) if sides.strip() else 6
# Validate ranges
if num_dice < 1:
return "❌ Error: Number of dice must be at least 1"
if num_dice > 100:
return "❌ Error: Maximum 100 dice allowed"
if num_sides < 2:
return "❌ Error: Number of sides must be at least 2"
if num_sides > 1000:
return "❌ Error: Maximum 1000 sides allowed"
# Roll dice
results = [random.randint(1, num_sides) for _ in range(num_dice)]
total = sum(results)
average = total / num_dice
# Format output
dice_type = f"d{num_sides}"
if num_dice == 1:
emoji = format_dice_results(results)[0] if num_sides == 6 else f"🎲 {results[0]}"
return f"✅ Dice Roll Result ({dice_type}): {emoji}"
else:
if num_sides == 6 and num_dice <= 10:
result_list = "\n".join([f" Die {i+1}: {format_dice_results([r])[0]}" for i, r in enumerate(results)])
else:
result_list = "\n".join([f" Die {i+1}: 🎲 {r}" for i, r in enumerate(results)])
return f"""✅ Dice Roll Results ({num_dice}{dice_type}):
{result_list}
📊 Summary:
- Total: {total}
- Average: {average:.2f}
- Minimum: {min(results)}
- Maximum: {max(results)}"""
except ValueError as e:
return f"❌ Error: Invalid parameters - dice: {dice}, sides: {sides}"
except Exception as e:
return f"❌ Error: {str(e)}"
async def roll_custom(expression: str = "") -> str:
"""Roll dice using standard notation like 2d6+5 or 3d20-2."""
try:
if not expression.strip():
return "❌ Error: Expression is required (e.g., '2d6+5', '3d20', '1d100-10')"
# Parse the expression
expr = expression.strip().lower().replace(" ", "")
# Extract components using simple parsing
modifier = 0
if '+' in expr:
parts = expr.split('+')
expr = parts[0]
modifier = int(parts[1])
elif '-' in expr and expr.count('-') == 1:
parts = expr.split('-')
expr = parts[0]
modifier = -int(parts[1])
# Parse dice notation (XdY)
if 'd' not in expr:
return "❌ Error: Invalid format. Use format like '2d6', '1d20+5', or '3d10-2'"
dice_parts = expr.split('d')
if len(dice_parts) != 2:
return "❌ Error: Invalid dice notation. Use format like '2d6'"
num_dice = int(dice_parts[0]) if dice_parts[0] else 1
num_sides = int(dice_parts[1])
# Validate ranges
if num_dice < 1 or num_dice > 100:
return "❌ Error: Number of dice must be between 1 and 100"
if num_sides < 2 or num_sides > 1000:
return "❌ Error: Number of sides must be between 2 and 1000"
# Roll dice
results = [random.randint(1, num_sides) for _ in range(num_dice)]
dice_total = sum(results)
final_total = dice_total + modifier
# Format output
dice_notation = f"{num_dice}d{num_sides}"
modifier_str = f" {'+' if modifier >= 0 else ''}{modifier}" if modifier != 0 else ""
if num_dice <= 10:
result_list = "\n".join([f" Die {i+1}: 🎲 {r}" for i, r in enumerate(results)])
detail_section = f"\n{result_list}\n\n"
else:
detail_section = "\n"
return f"""✅ Custom Roll Result ({dice_notation}{modifier_str}):
{detail_section}📊 Summary:
- Dice rolled: {dice_notation}
- Roll results sum: {dice_total}
- Modifier: {modifier:+d}
- Final total: {final_total}"""
except ValueError as e:
return f"❌ Error: Invalid expression format: {expression}"
except Exception as e:
return f"❌ Error: {str(e)}"
# === API ENDPOINTS ===
@app.get("/health", response_class=PlainTextResponse)
async def health() -> str:
return "ok"
@app.get("/flip-coin", response_class=PlainTextResponse)
async def http_flip_coin(flips: int = Query(1, ge=1, le=100)) -> str:
return await flip_coin(str(flips))
@app.get("/roll-dice", response_class=PlainTextResponse)
async def http_roll_dice(
dice: int = Query(1, ge=1, le=100),
sides: int = Query(6, ge=2, le=1000),
) -> str:
return await roll_dice(str(dice), str(sides))
@app.get("/roll-custom", response_class=PlainTextResponse)
async def http_roll_custom(expression: str = Query(..., description="e.g. 2d6+5")) -> str:
return await roll_custom(expression)
# JSON API endpoints for better integration
@app.get("/api/flip-coin")
async def api_flip_coin(flips: int = Query(1, ge=1, le=100)):
"""Flip coins and return JSON response"""
try:
result = await flip_coin(str(flips))
return JSONResponse(content={
"success": True,
"result": result,
"flips": flips
})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/roll-dice")
async def api_roll_dice(
dice: int = Query(1, ge=1, le=100),
sides: int = Query(6, ge=2, le=1000),
):
"""Roll dice and return JSON response"""
try:
result = await roll_dice(str(dice), str(sides))
return JSONResponse(content={
"success": True,
"result": result,
"dice": dice,
"sides": sides
})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/roll-custom")
async def api_roll_custom(expression: str = Query(..., description="e.g. 2d6+5")):
"""Roll custom dice expression and return JSON response"""
try:
result = await roll_custom(expression)
return JSONResponse(content={
"success": True,
"result": result,
"expression": expression
})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))