-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread.py
More file actions
executable file
·81 lines (67 loc) · 2.32 KB
/
thread.py
File metadata and controls
executable file
·81 lines (67 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/python3
"""
Story generator based on JSON chapter files.
See README.md for file format.
(c) 2016 Finn Rose Ellis. Licensed under the MIT License.
See LICENSE.txt for license details.
"""
import random
import json
import sys
import character
# Grab the filename from the command line and open it.
if len(sys.argv) == 2:
chapterfile = sys.argv[1]
else:
print("Please pass exactly one argument: a chapter filename.")
sys.exit(1)
with open(chapterfile) as f:
chapter = json.loads(f.read())
# Reorder the scene list randomly.
random.shuffle(chapter["scenes"])
# Generate character objects.
characters = []
for c in chapter.get("characters", []):
characters.append(character.Character(c["name"], c["pronouns"]))
# Replace integer globals with the appropriate character.
if "globals" not in chapter:
chapter["globals"] = {}
for k,v in chapter["globals"].items():
try:
chapter["globals"][k] = characters[v]
except TypeError:
# Value wasn't an integer, ignore it.
pass
# Generate and print the story.
if chapter["introduction"]:
print(chapter["introduction"].format(**chapter["globals"]))
for story in chapter["story"]:
# Replace integer variables with the corresponding characters.
for k,v in story.items():
try:
story[k] = characters[v]
except TypeError:
# Value wasn't an integer, ignore it.
pass
# Add globals to the available story variables.
story.update(chapter["globals"])
rejects = []
found_scene = False
while chapter["scenes"] and not found_scene:
# Look for a scene whose variables match the next story piece.
try:
scene = chapter["scenes"].pop()
print(scene.format(**story))
# If the print worked, we had the right variables available.
found_scene = True
break
except KeyError:
# Didn't have the right variables, set it aside and keep looking.
rejects.append(scene)
# Put the rejected scenes for this story piece back.
chapter["scenes"].extend(rejects)
if not found_scene:
print("Couldn't find an appropriate scene for story with these keys:", ", ".join(story.keys()))
sys.exit(2)
if chapter["conclusion"]:
print(chapter["conclusion"].format(**chapter["globals"]))