Advertisement
xgeovanni

Text-based game engine

Apr 18th, 2013
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.03 KB | None | 0 0
  1. import os
  2. import sys
  3. import glob
  4. import time
  5.  
  6. STORYFILE = "Story"
  7.  
  8. class StoryManager():    
  9.     def __init__(self, story):
  10.         self.story = story
  11.         self.currentChapter = 0
  12.        
  13.         self.endMessage = "The End"
  14.         self.ended = False #Flag to check whether story has ended
  15.        
  16.     def getChapter(self):
  17.         if self.currentChapter < len(self.story):
  18.             return self.story[self.currentChapter]
  19.         else:
  20.             self.ended = True
  21.             return self.endMessage
  22.        
  23.     def nextChapter(self):
  24.         self.currentChapter += 1
  25.        
  26.         if self.currentChapter <= len(self.story):
  27.             return self.story[self.currentChapter - 1]
  28.         else:
  29.             self.ended = True
  30.             return self.endMessage
  31.        
  32.     def pollChoices(self, choices):
  33.        
  34.         chosen = ""
  35.        
  36.         while True:
  37.             chosen =  input("Will you " + (" or ".join([choice[0] for choice in choices])) + " : ").lower()
  38.            
  39.             for choice in choices:
  40.                 if chosen == choice[0]:
  41.                     print(choice[1])
  42.                     return choice[1]
  43.            
  44.        
  45.     def goThroughStoryLinearly(self):
  46.         while not self.ended:
  47.             next = self.nextChapter()
  48.             delayedPrint(next[1], 50)
  49.             self.pollChoices(next[2])
  50.            
  51.     def goThroughStory(self):        
  52.         while not self.ended:
  53.             next = self.getChapter()
  54.             delayedPrint(next[1], 100)
  55.             self.currentChapter = self.pollChoices(next[2])
  56.            
  57. def delayedPrint(message, delay = 0):
  58.     for char in message:
  59.         print(char, end = "")
  60.         sys.stdout.flush()
  61.         time.sleep(delay / 1000)
  62.  
  63. def parseChapter(chapter):
  64.     """Should fix"""
  65.    
  66.     try:
  67.         choices = chapter[1][chapter[1].index("[") : chapter[1].index("]") + 1]
  68.         return eval(choices), choices
  69.     except Exception as e:
  70.         print("Invalid choices in file", str(chapter[0]), ":", str(e))
  71.        
  72. def parseStory(story):
  73.     chapters = []
  74.    
  75.     for item in story.items():
  76.         choices = parseChapter(item)
  77.         if choices:
  78.             chapters.append((item[0], item[1].replace(choices[1], ""), choices[0]))
  79.        
  80.     return chapters
  81.    
  82. def startup():
  83.     if not os.path.exists(STORYFILE):
  84.         raise IOExeption("Story files missing")
  85.  
  86. def loadStoryFiles(fileExtension = ".txt"):
  87.     story = {}
  88.    
  89.     for file in glob.glob(STORYFILE + "/*.txt"):
  90.         f = open(file)
  91.         chapter = file.replace("\\", "").replace(STORYFILE, "").replace(fileExtension, "")
  92.        
  93.         try:
  94.             chapter = int(chapter)
  95.         except ValueError:
  96.             print("Non-numerical chapter name ignored")
  97.             continue
  98.        
  99.         story[chapter] = f.read()
  100.         f.close()
  101.        
  102.     return story
  103.  
  104. def main():
  105.     startup()
  106.     sm = StoryManager(parseStory(loadStoryFiles()))
  107.     sm.goThroughStory()
  108.  
  109. if __name__ == "__main__":
  110.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement