Certainly! Below is a simple Python runtime that:
- Parses a
.storia story file conforming to the format and grammar described earlier (with indentation-based blocks).
- Runs a command-line interactive session to play through the story, showing scene text and presenting choices.
- Supports conditions only in a very minimal way (you can easily extend it).
- Handles basic navigation by scenes and choices.
How this runtime works
- Parses the
.storia file into an internal data structure: Story -> Scenes -> Choices.
- Starts at the
start scene defined in the @story block (or the first scene if not specified).
- Shows the scene text, presents the choices.
- Prompts the player to select a choice.
- Moves to the next scene as directed by the choice's
goto.
- Ends when a scene has no choices.
Limitations:
- No variable support or expression evaluation for conditions (but stubs are present).
- No complex metadata processed except
start.
- Only basic minimal parsing with strict indentation (4 spaces).
- No multiline quoted strings — just indented lines after keys like
text:.
Python Code
import sys
from typing import Dict, List, Optional
# ------------------------
# Data Classes for Story
# ------------------------
class Choice:
def __init__(self, label: str, goto: str, condition: Optional[str] = None):
self.label = label
self.goto = goto
self.condition = condition # Currently unused
def __repr__(self):
return f"Choice(label={self.label!r}, goto={self.goto!r}, condition={self.condition!r})"
class Scene:
def __init__(self, id_: str):
self.id = id_
self.title: Optional[str] = None
self.text: str = ""
self.choices: List[Choice] = []
self.condition: Optional[str] = None # Currently unused
self.tags: List[str] = []
def __repr__(self):
return f"Scene(id={self.id!r}, title={self.title!r}, choices={self.choices})"
class Story:
def __init__(self):
self.metadata: Dict[str, str] = {}
self.scenes: Dict[str, Scene] = {}
def get_start_scene_id(self) -> Optional[str]:
return self.metadata.get("start")
# ------------------------
# Parsing Utilities
# ------------------------
def count_indent(line: str) -> int:
return len(line) - len(line.lstrip(' '))
def strip_comment(line: str) -> str:
if '#' in line:
return line[:line.index('#')]
return line
def parse_scalar(line: str) -> str:
s = line.strip()
if s.startswith('"') and s.endswith('"'):
return s[1:-1]
return s
def parse_tags(line: str) -> List[str]:
val = parse_scalar(line)
parts = [part.strip() for part in val.split(',')]
return [p for p in parts if p]
# ------------------------
# Storia File Parser
# ------------------------
class StoriaParser:
def __init__(self, lines: List[str]):
self.lines = lines
self.pos = 0
self.story = Story()
def peek(self) -> Optional[str]:
if self.pos < len(self.lines):
return self.lines[self.pos]
return None
def next(self) -> Optional[str]:
if self.pos < len(self.lines):
line = self.lines[self.pos]
self.pos += 1
return line
return None
def expect_prefix(self, prefix: str) -> Optional[str]:
line = self.peek()
if line and line.strip().startswith(prefix):
return self.next()
return None
def skip_empty_and_comments(self):
while True:
line = self.peek()
if line is None:
return
if line.strip() == '' or line.strip().startswith('#'):
self.next()
else:
return
def parse(self) -> Story:
# Parse entire file
while self.pos < len(self.lines):
self.skip_empty_and_comments()
line = self.peek()
if line is None:
break
line_strip = line.strip()
if line_strip.startswith("@story:"):
self.parse_story_block()
elif line_strip.startswith("@scene"):
self.parse_scene_block()
else:
# Ignore unknown lines or comments
self.next()
return self.story
def parse_story_block(self):
# consume @story:
self.next()
# parse indented key: value pairs
while True:
line = self.peek()
if line is None or line.strip() == '' or line.strip().startswith('@'):
break
if line.strip().startswith('#'):
self.next()
continue
indent = count_indent(line)
if indent == 0:
break
key, val = self.parse_key_value_line()
if key:
self.story.metadata[key] = val
def parse_key_value_line(self):
line = self.next()
line_no_comment = strip_comment(line)
if ':' not in line_no_comment:
return None, None
k, v = line_no_comment.split(':', 1)
return k.strip(), v.strip()
def parse_scene_block(self):
header = self.next() # e.g. '@scene intro:'
header_strip = header.strip()
# Extract scene id
_, rest = header_strip.split(' ', 1)
scene_id = rest.rstrip(':').strip()
scene = Scene(scene_id)
# Parse scene body: indented fields
while True:
line = self.peek()
if line is None:
break
if line.strip() == '' or line.strip().startswith('#'):
self.next()
continue
indent = count_indent(line)
if indent == 0:
# new block starts
break
# parse a field
key_line = self.next()
key_line_clean = strip_comment(key_line).rstrip('\n')
if ':' not in key_line_clean:
# malformed line, ignore
continue
key, val = key_line_clean.split(':', 1)
key = key.strip()
val = val.lstrip()
if key == "title":
scene.title = parse_scalar(val)
elif key == "tags":
scene.tags = parse_tags(val)
elif key == "condition":
scene.condition = val
elif key == "text":
# parse multiline text block
scene.text = self.parse_multiline_block()
elif key == "choices":
scene.choices = self.parse_choices_block()
else:
# unknown key, ignore or extend
pass
self.story.scenes[scene_id] = scene
def parse_multiline_block(self) -> str:
# All subsequent indented lines aggregated until indent slips back
lines = []
base_indent = None
while True:
line = self.peek()
if line is None:
break
if line.strip() == '' or line.strip().startswith('#'):
self.next()
lines.append('')
continue
indent = count_indent(line)
if base_indent is None:
base_indent = indent
if indent < base_indent:
break
text_line = line[base_indent:]
lines.append(text_line.rstrip('\n'))
self.next()
return "\n".join(lines).strip()
def parse_choices_block(self) -> List[Choice]:
choices = []
while True:
line = self.peek()
if line is None:
break
if line.strip() == '' or line.strip().startswith('#'):
self.next()
continue
indent = count_indent(line)
if indent == 0:
# outdent means block end
break
stripped = line.lstrip()
if not stripped.startswith('-'):
# Not a choice entry, stop
break
# Consume the dash line
dash_line = self.next()
# parse choice kv pairs under dash (must be more indented than dash line)
dash_indent = count_indent(dash_line)
choice_fields = {}
while True:
next_line = self.peek()
if next_line is None:
break
next_indent = count_indent(next_line)
if next_indent <= dash_indent:
break
key_line = self.next()
key_line_clean = strip_comment(key_line).rstrip('\n')
if ':' not in key_line_clean:
continue
k, v = key_line_clean.split(':', 1)
k = k.strip()
v = v.strip()
choice_fields[k] = v
# Validate required keys
label = choice_fields.get("label")
goto = choice_fields.get("goto")
condition = choice_fields.get("condition")
if label is None or goto is None:
print("Warning: choice missing 'label' or 'goto', skipping")
continue
c = Choice(parse_scalar(label), goto, condition)
choices.append(c)
return choices
# ------------------------
# Runtime Engine
# ------------------------
class StoriaRuntime:
def __init__(self, story: Story):
self.story = story
self.current_scene_id = story.get_start_scene_id()
if self.current_scene_id is None:
# fallback: any scene (first in dict)
if len(story.scenes) > 0:
self.current_scene_id = next(iter(story.scenes))
else:
raise ValueError("No start scene defined and no scenes found.")
# Placeholder for variables, inventory, flags (for conditions etc)
self.variables = {}
def evaluate_condition(self, condition: Optional[str]) -> bool:
# TODO: implement actual expression parsing and evaluation
# For now, always true or None
if condition is None:
return True
# VERY simple simulation: support "var == true" only
cond = condition.strip()
if "==" in cond:
var, val = [s.strip() for s in cond.split("==", 1)]
var_val = self.variables.get(var)
val_bool = val.lower() == 'true'
return (var_val is True) == val_bool
return True
def play(self):
while True:
scene = self.story.scenes.get(self.current_scene_id)
if scene is None:
print(f"Scene '{self.current_scene_id}' not found!")
break
if not self.evaluate_condition(scene.condition):
print(f"Scene '{self.current_scene_id}' condition failed, cannot enter.")
break
# Display Scene
print("\n" + ("=" * 40))
if scene.title:
print(f"{scene.title}\n{'-' * len(scene.title)}")
print(scene.text)
print()
# Filter choices by condition
available_choices = [c for c in scene.choices if self.evaluate_condition(c.condition)]
if not available_choices:
print("<< The End >>")
return # no choices = end of story
# Show choices
for i, choice in enumerate(available_choices, start=1):
print(f"{i}) {choice.label}")
# Prompt player
selected = None
while selected is None:
try:
user_input = input("Choose an option (number): ").strip()
if user_input == '':
continue
choice_num = int(user_input)
if 1 <= choice_num <= len(available_choices):
selected = available_choices[choice_num - 1]
else:
print("Invalid choice number.")
except ValueError:
print("Please enter a valid number.")
# Go to next scene
self.current_scene_id = selected.goto
# ------------------------
# Main entry point
# ------------------------
def main(filename):
try:
with open(filename, encoding='utf-8') as f:
lines = f.readlines()
except Exception as e:
print(f"Failed to read file '{filename}': {e}")
return
parser = StoriaParser(lines)
story = parser.parse()
print(f"Loaded story: {story.metadata.get('title', '(unknown title)')} by {story.metadata.get('author', 'unknown')}")
runtime = StoriaRuntime(story)
runtime.play()
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python run_storia.py <storyfile.storia>")
sys.exit(1)
main(sys.argv[1])
How to use this runtime:
- Save the above code to a file, e.g.,
run_storia.py.
- Prepare a Storia story file, e.g.
sample.storia with content like:
@story:
title: Demo Adventure
author: ChatGPT
start: intro
@scene intro:
title: "At the Crossroads"
text:
You are standing at a crossroads. Paths lead north and east.
choices:
- label: "Go north"
goto: north_path
- label: "Go east"
goto: east_path
@scene north_path:
text:
The northern path leads you into a dark forest. It feels eerie.
choices:
- label: "Return to crossroads"
goto: intro
@scene east_path:
text:
The eastern path brings you to a sunny glade full of flowers.
choices:
- label: "Pick a flower"
goto: flower_scene
- label: "Return to crossroads"
goto: intro
@scene flower_scene:
text:
You pick a beautiful flower and feel happy.
# No choices means end of story.
- Run from command line:
python run_storia.py sample.storia
- The program will display scene text and prompt you to choose.
Extending the Runtime
- Condition evaluation: Integrate a proper expression parser or evaluator for variables.
- Variable assignment: Add the ability to assign variables on entering scenes or by choices.
- Inventory and branches: Extend choice metadata to modify variables.
- Saving/loading game state.
- GUI frontend or web interface.
If you want, I can help with those extensions or create a sample story to test!