Next-Dining-The-Video-Game/engine.py

63 lines
2.7 KiB
Python

import json
import sys
from openai import OpenAI
from termcolor import cprint
client = OpenAI(api_key="12345", base_url="http://boss-baby:8080/v1/")
c = json.load(open(sys.argv[1]))
print(c["description"])
c["player"]["name"] = input("Enter your name: ")
while c["player"]["health"] > 0 and c["player"][c["win"]["property"]] < c["win"]["value"]:
act = input("Enter go or do: ")
if act == "go":
while True:
c["player"]["location"] = input("Choose location from " + str(c["locations"].keys()) + ": ")
if c["player"]["location"] in c["locations"].keys():
break
print("Invalid location. Try again.")
act = "Enter the " + c["player"]["location"]
else:
while True:
act = input("Enter your action (limit 30 chars): ")
if len(act) <= 30:
break
print("Action is", len(act), "chars long. Try again.")
prompt = c["prompt"] + "\n"
prompt += "I am not allowed to use an item that is not in my inventory. Actions that harm me will cause me to lose health points.\n"
prompt += "I am at the " + c["player"]["location"] + " which is " + c["locations"][c["player"]["location"]] + "\n"
prompt += "Player status:\n" + json.dumps(c["player"]) + "\n"
prompt += "NPC statuses:\n" + json.dumps({k: v for k, v in c["npc"].items() if v["location"] == c["player"]["location"]}) + "\n"
prompt += "Player action: " + act + "\n"
prompt += "Please write one single paragraph about what happens due to this action referring to me, the player, in second person. Remember, do not write more than one paragraph! Then, return the player status and NPC statuses updated to reflect changes due to this action. Make sure to meticulously update the states of both the player and the NPCs!"
cprint(prompt, "green")
stream = client.chat.completions.create(messages=[{"role": "user", "content": prompt}], model="", stream=True)
updated = ""
for chunk in stream:
text = chunk.choices[0].delta.content or ""
if updated == "":
if "\n" in text:
print(text[:text.index("\n")], end="")
updated += text[text.index("\n"):]
print(text, end="")
else:
updated += text
cprint(updated, "red")
lines = list(filter(lambda i: "{" in i, updated.split("\n")))
newp = json.loads(lines[0])
newp["location"] = c["player"]["location"]
c["player"] = newp
for k, v in json.loads(lines[1]).items():
c["npc"][k] = v
print(c["player"])
if c["player"][c["win"]["property"]] >= c["win"]["value"]:
print("Congratulations! You won the game!")
else:
print("Oops! You ran out of health!")