Certainly! Below is the full integrated, updated Python script for the InkScript parser and interactive runtime. It includes all fixes:
- Proper parsing of choices with conditions.
- Special handling of
Else choice condition.
- Grouping of choices by condition and presenting only the first matching group.
- The example story includes the missing
hesitate and end nodes so all jumps are valid.
Save this as e.g. inkscript_runtime.py and run with Python 3.6+.
import re
import ast
import operator
from typing import List, Dict, Optional, Any, Union
from collections import OrderedDict
# --- Data classes representing the story structure ---
class VariableAssignment:
def __init__(self, var_name: str, expression: str):
self.var_name = var_name
self.expression = expression
def __repr__(self):
return f"VariableAssignment({self.var_name} = {self.expression})"
class Jump:
def __init__(self, target_node: str):
self.target_node = target_node
def __repr__(self):
return f"Jump(-> {self.target_node})"
class Choice:
def __init__(self, text: str, jump: Optional[Jump] = None, condition: Optional[str] = None):
self.text = text
self.jump = jump
self.condition = condition # Normalized, e.g. "ELSE" or expression
def __repr__(self):
return f"Choice(text={self.text!r}, condition={self.condition!r}, jump={self.jump})"
class ConditionalBlock:
def __init__(self, condition: Optional[str]):
self.condition = condition # None for else
self.lines: List[Union[str, 'ConditionalBlock', Choice, VariableAssignment, Jump]] = []
def __repr__(self):
return f"ConditionalBlock(condition={self.condition!r}, lines={self.lines})"
class Node:
def __init__(self, name: str):
self.name = name
self.content: List[Union[str, Choice, ConditionalBlock, VariableAssignment, Jump]] = []
def __repr__(self):
return f"Node(name={self.name!r}, content={self.content})"
class Metadata:
def __init__(self):
self.title: Optional[str] = None
self.author: Optional[str] = None
self.vars: Dict[str, Any] = {}
def __repr__(self):
return f"Metadata(title={self.title!r}, author={self.author!r}, vars={self.vars})"
class InkScriptStory:
def __init__(self):
self.metadata = Metadata()
self.nodes: Dict[str, Node] = {}
def __repr__(self):
return f"InkScriptStory(metadata={self.metadata}, nodes={list(self.nodes.keys())})"
# --- Lexer helpers ---
def count_leading_spaces(s: str) -> int:
return len(s) - len(s.lstrip(' '))
# --- InkScript Parser Implementation ---
class InkScriptParser:
METADATA_KEY_PATTERN = re.compile(r'^@(\w+):\s*(.*)$')
VAR_INIT_PATTERN = re.compile(r'^(\w+)\s*=\s*(.+)$')
NODE_HEADER_PATTERN = re.compile(r'^::(\w+)$')
CHOICE_LINE_PATTERN = re.compile(r'^\*\s*(\((.+)\))?\s*(.*)$')
VARIABLE_ASSIGN_PATTERN = re.compile(r'^=\s*(\w+)\s*=\s*(.+)$')
JUMP_LINE_PATTERN = re.compile(r'^->\s*(\w+)$')
CONDITIONAL_PATTERN = re.compile(r'^\*\s*\((If|Else)(.*)\)$', re.IGNORECASE)
def __init__(self, lines: List[str]):
self.lines = lines
self.story = InkScriptStory()
self.current_line = 0
self.max_line = len(lines)
self.current_node: Optional[Node] = None
def parse(self) -> InkScriptStory:
self._parse_metadata_and_nodes()
return self.story
def _parse_metadata_and_nodes(self):
while self.current_line < self.max_line:
line = self.lines[self.current_line].strip()
if not line or line.startswith('#'):
self.current_line += 1
continue
if line.startswith('@'):
self._parse_metadata_line(line)
self.current_line += 1
continue
node_match = self.NODE_HEADER_PATTERN.match(line)
if node_match:
node_name = node_match.group(1)
if node_name in self.story.nodes:
self._error(f"Duplicate node name: {node_name}")
self.current_node = Node(node_name)
self.story.nodes[node_name] = self.current_node
self.current_line += 1
self._parse_node_content()
continue
self._error(f"Unexpected line outside node or metadata: {line}")
def _parse_metadata_line(self, line: str):
if line.startswith('@vars:'):
self.current_line += 1
while self.current_line < self.max_line:
var_line = self.lines[self.current_line]
if not var_line.strip() or var_line.strip().startswith('#'):
self.current_line += 1
continue
indent = count_leading_spaces(var_line)
if indent == 0:
break
var_line = var_line.strip()
m = self.VAR_INIT_PATTERN.match(var_line)
if not m:
self._error(f"Invalid variable initialization in metadata: {var_line}")
var_name, var_value = m.group(1), m.group(2)
parsed_value = self._parse_value(var_value)
self.story.metadata.vars[var_name] = parsed_value
self.current_line += 1
self.current_line -= 1
else:
m = self.METADATA_KEY_PATTERN.match(line)
if m:
key, val = m.group(1).lower(), m.group(2)
if key == 'title':
self.story.metadata.title = val
elif key == 'author':
self.story.metadata.author = val
else:
# Unknown metadata key ignored
pass
def _parse_value(self, val: str) -> Any:
val = val.strip()
if val.lower() in ['true', 'false']:
return val.lower() == 'true'
try:
iv = int(val)
return iv
except Exception:
pass
try:
fv = float(val)
return fv
except Exception:
pass
if val.startswith('[') and val.endswith(']'):
inner = val[1:-1].strip()
if not inner:
return []
parts = [p.strip() for p in inner.split(',')]
return parts
return val
def _parse_node_content(self):
assert self.current_node is not None
while self.current_line < self.max_line:
line_raw = self.lines[self.current_line]
line = line_raw.rstrip('\n')
if line.strip() == '':
self.current_line += 1
continue
if self.NODE_HEADER_PATTERN.match(line.strip()):
break
if line.strip().startswith('#'):
self.current_line += 1
continue
stripped = line.lstrip()
indent = count_leading_spaces(line)
if stripped.startswith('*'):
self._parse_choice_or_conditional(indent)
elif stripped.startswith('='):
self._parse_variable_assignment(indent)
elif stripped.startswith('->'):
self._parse_jump(indent)
else:
self.current_node.content.append(stripped)
self.current_line += 1
def _parse_choice_or_conditional(self, base_indent: int):
line = self.lines[self.current_line]
stripped = line.lstrip()
# Check conditional narrative block (if/else)
cond_block_match = self.CONDITIONAL_PATTERN.match(stripped)
if cond_block_match:
cond_type = cond_block_match.group(1).lower()
cond_expr_raw = cond_block_match.group(2).strip()
condition = None if cond_type == 'else' else cond_expr_raw
cond_block = ConditionalBlock(condition)
self.current_line += 1
cond_block.lines = self._parse_indented_block(base_indent + 2)
self.current_node.content.append(cond_block)
return
# Otherwise parse choice line
choice_match = self.CHOICE_LINE_PATTERN.match(stripped)
if not choice_match:
self._error(f"Malformed choice line: {stripped}")
condition = choice_match.group(2)
if condition is not None:
condition = condition.strip()
if condition.lower() == 'else':
condition = 'ELSE'
text = choice_match.group(3).strip()
choices: List[Choice] = []
self.current_line += 1
while self.current_line < self.max_line:
next_line = self.lines[self.current_line]
indent = count_leading_spaces(next_line)
stripped_next = next_line.lstrip()
if indent <= base_indent:
break
elif stripped_next.startswith('+'):
choice_text = stripped_next[1:].strip()
choice_jump = None
self.current_line += 1
if self.current_line < self.max_line:
jump_line = self.lines[self.current_line]
jump_indent = count_leading_spaces(jump_line)
stripped_jump = jump_line.lstrip()
if jump_indent > indent and stripped_jump.startswith('->'):
m_jump = self.JUMP_LINE_PATTERN.match(stripped_jump)
if m_jump:
choice_jump = Jump(m_jump.group(1))
self.current_line += 1
else:
self._error(f"Invalid jump line: {stripped_jump}")
choices.append(Choice(choice_text, choice_jump, condition))
else:
break
self.current_node.content.extend(choices)
def _parse_variable_assignment(self, base_indent: int):
line = self.lines[self.current_line].lstrip()
m = self.VARIABLE_ASSIGN_PATTERN.match(line)
if not m:
self._error(f"Malformed variable assignment: {line}")
var_name, expr = m.group(1), m.group(2)
assignment = VariableAssignment(var_name, expr)
self.current_node.content.append(assignment)
self.current_line += 1
def _parse_jump(self, base_indent: int):
line = self.lines[self.current_line].lstrip()
m = self.JUMP_LINE_PATTERN.match(line)
if not m:
self._error(f"Malformed jump line: {line}")
jump = Jump(m.group(1))
self.current_node.content.append(jump)
self.current_line += 1
def _parse_indented_block(self, expected_indent: int) -> List[Union[str, Choice, ConditionalBlock, VariableAssignment, Jump]]:
block_content = []
while self.current_line < self.max_line:
line = self.lines[self.current_line]
indent = count_leading_spaces(line)
if indent < expected_indent or not line.strip():
break
stripped = line.lstrip()
if stripped.startswith('#'):
self.current_line += 1
continue
if stripped.startswith('*'):
old_content = self.current_node.content
self.current_node.content = block_content
self._parse_choice_or_conditional(expected_indent)
self.current_node.content = old_content
elif stripped.startswith('='):
old_content = self.current_node.content
self.current_node.content = block_content
self._parse_variable_assignment(expected_indent)
self.current_node.content = old_content
elif stripped.startswith('->'):
old_content = self.current_node.content
self.current_node.content = block_content
self._parse_jump(expected_indent)
self.current_node.content = old_content
else:
block_content.append(stripped)
self.current_line += 1
return block_content
def _error(self, msg: str):
raise ValueError(f"Parse error at line {self.current_line + 1}: {msg}")
def parse_inkscript(text: str) -> InkScriptStory:
lines = text.splitlines()
parser = InkScriptParser(lines)
story = parser.parse()
return story
# --------------------------------------
# Expression Evaluator: Safe and Basic
# --------------------------------------
class ExpressionEvaluator:
ALLOWED_NODES = {
ast.Expression,
ast.BinOp,
ast.UnaryOp,
ast.Num,
ast.Name,
ast.Load,
ast.Compare,
ast.BoolOp,
ast.And,
ast.Or,
ast.Not,
ast.Eq,
ast.NotEq,
ast.Lt,
ast.LtE,
ast.Gt,
ast.GtE,
ast.Str,
ast.Constant,
}
ALLOWED_BINOPS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.Mod: operator.mod,
}
ALLOWED_UNARYOPS = {
ast.USub: operator.neg,
ast.UAdd: operator.pos,
ast.Not: operator.not_,
}
ALLOWED_CMPOP = {
ast.Eq: operator.eq,
ast.NotEq: operator.ne,
ast.Lt: operator.lt,
ast.LtE: operator.le,
ast.Gt: operator.gt,
ast.GtE: operator.ge,
}
def __init__(self, variables: Dict[str, Any]):
self.variables = variables
def eval(self, expr: str) -> Any:
try:
tree = ast.parse(expr, mode='eval')
except SyntaxError as e:
raise ValueError(f"Syntax error in expression '{expr}': {e}")
return self._eval_node(tree.body)
def _eval_node(self, node):
nodetype = type(node)
if nodetype not in self.ALLOWED_NODES:
raise ValueError(f"Unsupported expression: {nodetype}")
if isinstance(node, ast.Expression):
return self._eval_node(node.body)
elif isinstance(node, ast.Constant):
return node.value
elif isinstance(node, ast.Num):
return node.n
elif isinstance(node, ast.Str):
return node.s
elif isinstance(node, ast.Name):
if node.id in self.variables:
return self.variables[node.id]
else:
return False # Undefined vars treated as False
elif isinstance(node, ast.BinOp):
left = self._eval_node(node.left)
right = self._eval_node(node.right)
op_type = type(node.op)
if op_type in self.ALLOWED_BINOPS:
return self.ALLOWED_BINOPS[op_type](left, right)
raise ValueError(f"Unsupported binary operator: {op_type}")
elif isinstance(node, ast.UnaryOp):
operand = self._eval_node(node.operand)
op_type = type(node.op)
if op_type in self.ALLOWED_UNARYOPS:
return self.ALLOWED_UNARYOPS[op_type](operand)
raise ValueError(f"Unsupported unary operator: {op_type}")
elif isinstance(node, ast.Compare):
left = self._eval_node(node.left)
for op, comparator in zip(node.ops, node.comparators):
right = self._eval_node(comparator)
op_type = type(op)
if op_type not in self.ALLOWED_CMPOP:
raise ValueError(f"Unsupported comparison operator: {op_type}")
if not self.ALLOWED_CMPOP[op_type](left, right):
return False
left = right
return True
elif isinstance(node, ast.BoolOp):
op_type = type(node.op)
if op_type is ast.And:
return all(self._eval_node(v) for v in node.values)
elif op_type is ast.Or:
return any(self._eval_node(v) for v in node.values)
else:
raise ValueError(f"Unsupported boolean operator: {op_type}")
else:
raise ValueError(f"Unsupported AST node: {nodetype}")
# --------------------------------------
# InkScript Runtime Engine
# --------------------------------------
class InkScriptRuntime:
VARIABLE_PATTERN = re.compile(r'\{([^}]+)\}')
def __init__(self, story: InkScriptStory):
self.story = story
self.variables: Dict[str, Any] = {}
for k, v in story.metadata.vars.items():
self.variables[k] = v
self.current_node: Optional[Node] = None
self.evaluator = ExpressionEvaluator(self.variables)
def run(self, start_node: str = 'start'):
if start_node not in self.story.nodes:
raise ValueError(f"Start node '{start_node}' not found.")
self.current_node = self.story.nodes[start_node]
print(f"=== {self.story.metadata.title or 'Untitled Story'} ===")
if self.story.metadata.author:
print(f"by {self.story.metadata.author}")
print()
while self.current_node:
self._run_node(self.current_node)
def _run_node(self, node: Node):
self.current_node = node
lines_to_display = []
choices: List[Choice] = []
def collect_content(content):
for item in content:
if isinstance(item, str):
interpolated = self._interpolate_text(item)
lines_to_display.append(interpolated)
elif isinstance(item, VariableAssignment):
value = self._eval_expression(item.expression)
self.variables[item.var_name] = value
self.evaluator.variables = self.variables
elif isinstance(item, Jump):
self.current_node = self.story.nodes.get(item.target_node)
if not self.current_node:
raise ValueError(f"Jump to unknown node: {item.target_node}")
return 'jump'
elif isinstance(item, Choice):
choices.append(item)
elif isinstance(item, ConditionalBlock):
cond = item.condition
cond_result = False
if cond is None:
cond_result = True
else:
cond_result = self._eval_condition(cond)
if cond_result:
ret = collect_content(item.lines)
if ret == 'jump':
return 'jump'
else:
raise ValueError(f"Unknown content type: {item}")
ret = collect_content(node.content)
if ret == 'jump':
return
for line in lines_to_display:
print(line)
print()
if choices:
# Group choices by their condition to support if-else chains
groups = OrderedDict()
for choice in choices:
key = choice.condition or "NONE"
groups.setdefault(key, []).append(choice)
chosen_group = None
# Evaluate groups except ELSE first
for cond in groups.keys():
if cond == 'ELSE':
continue
if cond == 'NONE': # No condition means always show
chosen_group = groups[cond]
break
if self._eval_condition(cond):
chosen_group = groups[cond]
break
# If no other groups matched, try ELSE
if not chosen_group and 'ELSE' in groups:
chosen_group = groups['ELSE']
if chosen_group:
self._present_choices_and_handle(chosen_group)
else:
self.current_node = None
print("=== The End ===")
else:
self.current_node = None
print("=== The End ===")
def _eval_condition(self, expr: str) -> bool:
try:
return bool(self._eval_expression(expr))
except Exception as e:
print(f"[Warning] Failed to evaluate condition '{expr}': {e}")
return False
def _eval_expression(self, expr: str) -> Any:
return self.evaluator.eval(expr)
def _interpolate_text(self, text: str) -> str:
def replace_var(match):
varname = match.group(1).strip()
val = self.variables.get(varname, f"{{{varname}}}")
return str(val)
text = text.replace('{{', '{').replace('}}', '}')
return self.VARIABLE_PATTERN.sub(replace_var, text)
def _present_choices_and_handle(self, choices: List[Choice]):
print("Choices:")
for i, choice in enumerate(choices, 1):
print(f" {i}. {choice.text}")
selection = None
while selection is None:
input_line = input("Select choice number: ").strip()
if input_line.isdigit():
idx = int(input_line)
if 1 <= idx <= len(choices):
selection = idx - 1
else:
print("Invalid choice number, try again.")
else:
print("Please enter a number.")
chosen = choices[selection]
if chosen.jump is None:
self.current_node = None
print("=== The End ===")
return
next_node = self.story.nodes.get(chosen.jump.target_node)
if next_node is None:
print(f"[Error] Node not found: {chosen.jump.target_node}")
self.current_node = None
else:
self.current_node = next_node
print()
# --------------------------------------
# Entry point and example InkScript
# --------------------------------------
if __name__ == "__main__":
example_text = """
@title: The Haunted Mansion
@author: John Q. Writer
@vars:
sanity = 100
has_key = false
::start
You stand before the creaking gates of the mansion. Sanity: {sanity}
* (sanity > 50)
+ Enter the mansion bravely.
-> inside_mansion
* (Else)
+ Hesitate and reconsider.
-> hesitate
::inside_mansion
The door slams shut behind you. [You have the key?: {has_key}]
* (has_key == false)
+ Search the dusty foyer.
= has_key = true
-> foyer
* (has_key == true)
+ Proceed to the stairs.
-> stairs
::foyer
The key glints under a broken vase.
* Continue upstairs.
-> stairs
::stairs
You ascend cautiously...
::hesitate
You stand frozen in place, uncertain whether to enter the mansion or retreat.
* Summon your courage and enter.
-> inside_mansion
* Turn back and leave the grounds.
-> end
::end
Thank you for playing.
"""
story = parse_inkscript(example_text)
runtime = InkScriptRuntime(story)
runtime.run('start')
How to run:
- Save the script to a file, e.g.
inkscript_runtime.py.
- Run with Python 3 (3.6+):
python inkscript_runtime.py
What should happen:
=== The Haunted Mansion ===
by John Q. Writer
You stand before the creaking gates of the mansion. Sanity: 100
Choices:
1. Enter the mansion bravely.
2. Hesitate and reconsider.
Select choice number:
- Enter
1 or 2 to continue playing the story with choices and variable states.
If you'd like further improvements or explanation, just ask!