This program builds a tree of possible decisions and outcomes up to 2 steps deep starting from 'start'. It shows how choices lead to new states.
def possible_actions(state):
if state == 'start':
return ['go left', 'go right']
elif state == 'left room':
return ['open door', 'look around']
elif state == 'right room':
return ['climb ladder', 'search drawer']
else:
return []
def apply_action(state, action):
if state == 'start' and action == 'go left':
return 'left room'
if state == 'start' and action == 'go right':
return 'right room'
if state == 'left room' and action == 'open door':
return 'secret chamber'
if state == 'left room' and action == 'look around':
return 'left room'
if state == 'right room' and action == 'climb ladder':
return 'attic'
if state == 'right room' and action == 'search drawer':
return 'found key'
return state
def build_tree(node, depth):
if depth == 0:
return
for action in possible_actions(node['current_state']):
new_state = apply_action(node['current_state'], action)
child_node = {'current_state': new_state, 'action': action, 'children': []}
node['children'].append(child_node)
build_tree(child_node, depth - 1)
tree = {'current_state': 'start', 'children': []}
build_tree(tree, 2)
import json
print(json.dumps(tree, indent=2))