from fastapi import FastAPI, HTTPException from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles import uvicorn from game_logic import generate_dungeon app = FastAPI() # 掛載 static 資料夾,供前端靜態檔案存取 app.mount("/static", StaticFiles(directory="static"), name="static") @app.get("/", response_class=HTMLResponse) async def index(): # 讀取並回傳 index.html with open("static/index.html", "r", encoding="utf-8") as f: html_content = f.read() return HTMLResponse(content=html_content) @app.post("/api/new_game") async def new_game(): """ 新遊戲:初始化玩家狀態與隨機生成迷宮 """ game_state = { "level": 1, "exp": 0, "exp_next": 100, # 初始升級所需經驗 "skill_points": 0, "stats": {"physical": 10, "magic": 10, "defense": 10}, "dungeon": generate_dungeon() } # 此處可依需求寫入資料庫或檔案存檔 return game_state @app.post("/api/level_up") async def level_up(game_state: dict): """ 升級功能: - 檢查玩家經驗值是否足夠 - 升級後經驗扣除、等級提升、技能點 +1,並將下一次所需經驗乘以 2 """ if game_state["exp"] >= game_state["exp_next"]: game_state["exp"] -= game_state["exp_next"] game_state["level"] += 1 game_state["skill_points"] += 1 game_state["exp_next"] *= 2 return game_state else: raise HTTPException(status_code=400, detail="經驗值不足,無法升級") # 本區塊僅供本地端測試使用,部署時 HuggingFace Spaces 會自動啟動 app 物件 if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000)