Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import sys
- import glob
- import time
- STORYFILE = "Story"
- class StoryManager():
- def __init__(self, story):
- self.story = story
- self.currentChapter = 0
- self.endMessage = "The End"
- self.ended = False #Flag to check whether story has ended
- def getChapter(self):
- if self.currentChapter < len(self.story):
- return self.story[self.currentChapter]
- else:
- self.ended = True
- return self.endMessage
- def nextChapter(self):
- self.currentChapter += 1
- if self.currentChapter <= len(self.story):
- return self.story[self.currentChapter - 1]
- else:
- self.ended = True
- return self.endMessage
- def pollChoices(self, choices):
- chosen = ""
- while True:
- chosen = input("Will you " + (" or ".join([choice[0] for choice in choices])) + " : ").lower()
- for choice in choices:
- if chosen == choice[0]:
- print(choice[1])
- return choice[1]
- def goThroughStoryLinearly(self):
- while not self.ended:
- next = self.nextChapter()
- delayedPrint(next[1], 50)
- self.pollChoices(next[2])
- def goThroughStory(self):
- while not self.ended:
- next = self.getChapter()
- delayedPrint(next[1], 100)
- self.currentChapter = self.pollChoices(next[2])
- def delayedPrint(message, delay = 0):
- for char in message:
- print(char, end = "")
- sys.stdout.flush()
- time.sleep(delay / 1000)
- def parseChapter(chapter):
- """Should fix"""
- try:
- choices = chapter[1][chapter[1].index("[") : chapter[1].index("]") + 1]
- return eval(choices), choices
- except Exception as e:
- print("Invalid choices in file", str(chapter[0]), ":", str(e))
- def parseStory(story):
- chapters = []
- for item in story.items():
- choices = parseChapter(item)
- if choices:
- chapters.append((item[0], item[1].replace(choices[1], ""), choices[0]))
- return chapters
- def startup():
- if not os.path.exists(STORYFILE):
- raise IOExeption("Story files missing")
- def loadStoryFiles(fileExtension = ".txt"):
- story = {}
- for file in glob.glob(STORYFILE + "/*.txt"):
- f = open(file)
- chapter = file.replace("\\", "").replace(STORYFILE, "").replace(fileExtension, "")
- try:
- chapter = int(chapter)
- except ValueError:
- print("Non-numerical chapter name ignored")
- continue
- story[chapter] = f.read()
- f.close()
- return story
- def main():
- startup()
- sm = StoryManager(parseStory(loadStoryFiles()))
- sm.goThroughStory()
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement