Spaces:
Build error
Build error
Download app.py from thirdgroup/GameStory: direct link, hf CLI and curl.
- Browser
- Download file 3.75 kB
-
https://huggingface.co/spaces/thirdgroup/GameStory/resolve/main/app.py
- Command line
-
hf download hf://spaces/thirdgroup/GameStory/app.py
-
curl -L -o app.py https://huggingface.co/spaces/thirdgroup/GameStory/resolve/main/app.py
3.75 kB
| #重要不要刪掉,這是正確的(最終版) | |
| import openai | |
| import gradio as gr | |
| # 設定 OpenAI API 金鑰 | |
| openai.api_key = "" | |
| # 初始故事設定 | |
| story_intro = """歡迎來到【冒險之旅】,冒險準備開始囉!\n你是一個失業的人,被種種生活壓力壓得喘不過氣的你,站在頂樓邊緣,不顧眾人勸說,跳了下去。\n再次醒來,你發現自己躺在森林裡,決定前往神秘森林冒險。卻在森林遠處聽到小孩子的求救聲...\n(小提醒:輸入關鍵字「結束」遊戲就會被迫停止。)""" | |
| # 用於處理 OpenAI API 來生成故事 | |
| def generate_story(user_input, context): | |
| try: | |
| response = openai.chat.completions.create( | |
| model="gpt-3.5-turbo", | |
| messages=[ | |
| {"role": "system", "content": "你是一個遊戲生成器,根據玩家的輸入編寫冒險故事,創造冒險事件讓玩家體驗,且此故事的軸心是要宣導「生命的重要性」,但是不希望強制宣傳,所以不要太硬要加入到台詞裡。並給出開放性問題再次讓玩家輸入編寫(不要設計選擇題),一次劇情不要生成太多劇情,一句話劇情生成不要過多。"}, | |
| {"role": "user", "content": context }, | |
| {"role": "user", "content": user_input} | |
| ], | |
| max_tokens=350, | |
| temperature=0.7 | |
| ) | |
| return response.choices[0].message.content.strip() | |
| except Exception as e: | |
| return f"抱歉,發生錯誤:{e}" | |
| # 遊戲邏輯 | |
| def play_game(state): | |
| """初始化遊戲""" | |
| context = story_intro | |
| state = [(None, context)] # 聊天記錄以故事開頭初始化 | |
| return state, state # 返回初始故事的聊天記錄和狀態 | |
| def chat_with_game(user_input, state): | |
| """處理玩家輸入,生成遊戲故事""" | |
| if not user_input.strip(): | |
| return state, state, "" # 如果輸入為空,保持原狀且清空輸入框 | |
| context = "\n".join([msg[1] for msg in state if msg[1]]) # 提取上下文 | |
| next_story = generate_story(user_input, context) # 使用玩家輸入生成新故事 | |
| state.append((user_input, next_story)) # 更新聊天記錄 | |
| return state, state, "" # 清空輸入框 | |
| def play_game_pro(): | |
| current_story = story_intro # 開始時的劇情 | |
| print(current_story) | |
| while True: | |
| user_input = input("你想做什麼?(自由輸入行動或描述):") | |
| # 根據玩家輸入生成新的故事情節 | |
| next_story = generate_story(user_input, current_story) | |
| # 顯示故事情節 | |
| print(next_story) | |
| # 更新故事上下文以便生成新的內容 | |
| current_story = next_story | |
| # 如果故事中包含結束的提示,結束遊戲 | |
| if "結束" in next_story : | |
| print("故事到這裡就告一個段落了,希望透過此次冒險,讓你明白生命的寶貴,唯有活下去,人生才能繼續精彩冒險。\n遊戲結束,謝謝遊玩!") | |
| break | |
| # 建立 Gradio UI | |
| with gr.Blocks(title="冒險遊戲") as app: | |
| gr.Markdown("# 🏰 冒險遊戲") | |
| chatbox = gr.Chatbot(label="遊戲介面", height=400) | |
| input_box = gr.Textbox(label="輸入框", placeholder="輸入你的行動!", lines=1) | |
| state = gr.State([]) # 聊天記錄狀態 | |
| # 按鈕與功能綁定 | |
| start_button = gr.Button("開始遊戲") | |
| start_button.click(play_game, inputs=state, outputs=[chatbox, state]) | |
| input_box.submit( | |
| chat_with_game, | |
| inputs=[input_box, state], | |
| outputs=[chatbox, state, input_box] # 加入 input_box 作為輸出,讓它接收到空字串 | |
| ) | |
| # 啟動應用程式 | |
| if __name__ == "__main__": | |
| app.queue().launch(share=True) |