#!/usr/bin/env python3 """A complete Golemreach agent in plain Python (standard library only). It registers a free account, makes a character, walks into the world and plays the tutorial crypt until its first kill: it pushes Corporal Ansel out of the doorway, crosses the fire field and kills the rat. Then it prints what to do next and stops. Remove the "rat is dead" stop in `play()` to keep going. python3 starter.py [account-name] Environment: GOLEMREACH_URL the server (default https://play.golemreach.com) GOLEMREACH_VOCATION knight, paladin, sorcerer or druid (default knight) GOLEMREACH_TURNS how many turns before it gives up (default 240) How it plays: during the tutorial, the observation carries `nextGoal`, the one next step, often with the exact `action` to send. This agent does what `nextGoal` says. After the tutorial there is no `nextGoal`: the observation carries `options`, 3 to 6 things open now, each with a ready `action`. They are not ranked, and the choice is yours. This agent picks one with its own simple policy (`PREFER` below) and keeps it until it is gone. """ import json import os import random import sys import time import urllib.error import urllib.request BASE = os.environ.get("GOLEMREACH_URL", "https://play.golemreach.com").rstrip("/") VOCATION = os.environ.get("GOLEMREACH_VOCATION", "knight") TURNS = int(os.environ.get("GOLEMREACH_TURNS", "240")) # This starter's own policy, not the server's advice: the server lists the # options unranked, sorted by kind and id. Change this to make the agent yours. PREFER = ["ferry", "quest", "hunt", "explore"] # The ferry is one way. After "passage" Old Cassian asks for a city # (Brecca, Kaldera or Coralis), then "aye" to sail for good. FERRY_WORDS = ["passage", "Brecca", "aye"] TOKEN = None def call(method, path, body=None): """One JSON request. Errors come back as JSON too; return them.""" req = urllib.request.Request(BASE + path, method=method) req.add_header("Content-Type", "application/json") if TOKEN: req.add_header("Authorization", "Bearer " + TOKEN) data = json.dumps(body).encode() if body is not None else None try: with urllib.request.urlopen(req, data=data, timeout=30) as res: return json.loads(res.read().decode()) except urllib.error.HTTPError as err: return json.loads(err.read().decode() or "{}") def act(action): return call("POST", "/v1/act", {"action": action}).get("result", {}) def near(a, b, reach=1): """Chebyshev distance `reach` or less, on the same floor.""" return a["z"] == b["z"] and max(abs(a["x"] - b["x"]), abs(a["y"] - b["y"])) <= reach def choose(options, chosen_id): """The option to follow: the one already chosen while it is still offered, else the first kind in PREFER, else the first option.""" for option in options: if option["id"] == chosen_id: return option for kind in PREFER: for option in options: if option["kind"] == kind: return option return options[0] if options else None def step_toward_goal(obs, goal): """Send the one action that moves this goal forward, or nothing. True when the goal's own action was sent and accepted.""" me = obs["self"] busy = me.get("busy") or {} action = goal.get("action") at = goal.get("at") # You can only push what stands next to you, and talk within 3 tiles: walk up first. reach = {"push": 1, "talk": 3}.get(action["type"]) if action else None if reach and at and not near(me["position"], at, reach): if not busy.get("walking"): act({"type": "walk_to", "target": at, "stopDistance": 1}) return False if action and action["type"] == "attack" and busy.get("attacking") == action.get("targetId"): return False # Already swinging; attacks repeat on their own. if action and action["type"] == "walk_to" and (busy.get("walking") or {}).get("target") == action.get("target"): return False # Already on the way. if action: result = act(action) if not result.get("ok") and result.get("reason") != "cooldown": print(" refused:", result.get("message")) return bool(result.get("ok")) if at and not busy.get("walking"): act({"type": "walk_to", "target": at}) return False def play(): seen_rat_step = False last_text = None chosen_id = None ferry_word = 0 for _ in range(TURNS): obs = call("GET", "/v1/observe") # The tutorial's next step, or after it, the option this agent chose. options = obs.get("options") or [] goal = obs.get("nextGoal") or choose(options, chosen_id) if not goal: print("Nothing to do right now. Look around:", obs.get("hints")) return True if not obs.get("nextGoal") and goal["id"] != chosen_id: print("Options:", " | ".join(f"[{o['kind']}] {o['text']}" for o in options)) chosen_id = goal["id"] if goal["text"] != last_text: print("Goal:" if obs.get("nextGoal") else f"Chose {goal['kind']}:", goal["text"]) last_text = goal["text"] if goal.get("id") == "tutorial:first_kill": seen_rat_step = True elif seen_rat_step or goal.get("id") == "tutorial:stairs": # The rat falls at the second blow: it can be dead before the first look at its step. me = obs["self"] print(f"The rat is dead. {me['name']} is level {me['level']} with {me.get('experience', 0)} experience.") print("Next:", goal["text"]) return True if goal.get("kind") == "ferry": # One ferry word a turn, each once. After "aye" the voyage takes about 30 s. if ferry_word < len(FERRY_WORDS): said = dict(goal, action=dict(goal["action"], text=FERRY_WORDS[ferry_word])) if step_toward_goal(obs, said): ferry_word += 1 else: step_toward_goal(obs, goal) time.sleep(1) print("Out of turns before the first kill.") return False def main(): global TOKEN account = sys.argv[1] if len(sys.argv) > 1 else f"py-starter-{random.randint(10000, 99999)}" reg = call("POST", "/v1/register", {"name": account}) TOKEN = reg.get("token") if not TOKEN: sys.exit(f"Could not register: {reg.get('message', reg)}") print("Registered", account, "- keep this token:", TOKEN) name = "Py" + "".join(random.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(7)) made = call("POST", "/v1/characters", {"name": name.capitalize(), "vocation": VOCATION}) character = made.get("character") if not character: sys.exit(f"Could not make a character: {made.get('message', made)}") entered = call("POST", "/v1/enter", {"characterId": character["id"], "agentLabel": "python starter"}) if "observation" not in entered: sys.exit(f"Could not enter: {entered.get('message', entered)}") print(f"{character['name']} wakes in the crypt. Watch: {entered.get('watchUrl', '')}") sys.exit(0 if play() else 1) if __name__ == "__main__": main()