Esempio n. 1
0
    def createOwn(self):  #user decided to create their own story
        tkinter.messagebox.showinfo(
            "Create Own!", "You have chosen to create your own story!")
        self.infoText1.grid_remove()  #this is to remove the information text
        # remove the buttons
        self.madLibsButton.grid_remove()
        self.createOwnButton.grid_remove()

        #create story object
        self.story = Story()

        # The default text for the window
        content = StringVar()
        self.storyBox = Entry(self, width=40,
                              textvariable=content)  #adding it to the box
        self.storyBox.bind('<FocusIn>', self.on_entry_click)
        content.set("Story here")
        self.storyBox.config(fg='grey')
        self.storyBox.grid()

        self.readButton = Button(self,
                                 text="Read aloud",
                                 command=self.callRead)
        self.readButton.grid()

        self.saveLabel = Label(self,
                               text="Enter a filename to save your story")
        self.saveLabel.grid()
        self.saveFileName = Entry(self, width=35)
        self.saveFileName.grid()
        self.saveButton = Button(self,
                                 text="Save Story",
                                 command=self.saveStory)
        self.saveButton.grid()
Esempio n. 2
0
def json_story_post(scrumteam, jira_connection):
    # Body
    body = '''
    {
        "jql": "filter=AWO-%s-Sprint-Story",
                    "startAt": 0,
                "maxResults" : 1000
    }
    ''' % scrumteam

    jira_connection = JiraConnection()

    jira_connection.\
            setUserAndPass(userpsw).\
            setHeader().\
            setBody(body)

    try:
        x = jira_connection.sendRequest()
    except Exception:
        raise

    story = Story(json.loads(x.decode()))

    return story.get_story()
Esempio n. 3
0
    def run_once(self):

        self.session_1.restart_session()
        self.session_2.restart_session()

        story = Story()

        while self.session_1.is_connected() and self.session_2.is_connected():
            sleep(0.2)

            message_list_1 = self.session_1.get_local_messages()
            message_list_2 = self.session_2.get_local_messages()

            self.transfer_session_info_to_session(message_list_1, self.session_2)
            self.transfer_session_info_to_session(message_list_2, self.session_1)
            self.transfer_session_info_to_story(self.session_1.identifier, message_list_1, story)
            self.transfer_session_info_to_story(self.session_2.identifier, message_list_2, story)

            self.session_1.read_messages()
            self.session_2.read_messages()

            self.session_1.update_status()
            self.session_2.update_status()

        story.save_as_txt(self.save_folder)
Esempio n. 4
0
def findMode(monitor):
    """Controls the flow of finding articles and updating the database"""
    while(True):
        print "Enter key words to search for separated by a comma:"
        keyWords = raw_input()
        if (keyWords == ""):
            continue
        keyWords = [w.strip() for w in keyWords.split(",")]
        print "Searching for articles related to those keywords..."
               
        for source in SOURCES:
            links = monitor.scrapeURL(source, keyWords) 
            print("Found %d article(s) on %s\n" % (len(links), source))
            for link in links:
                title = link.string
                url = link.get("href")
                story = Story(title, url, keyWords, source)
                doc = story.getDocument()  

                # Insert document into database
                monitor.addToDatabase(doc)

                # Print results to console
                print "ARTICLE TITLE: %s" % title
                print "URL: %s" % url
        break
Esempio n. 5
0
def main():
    plot = Story()
    st = plot.get_start()
    while True:
        printer(st)
        if plot.checkpoint == plot.end:
            break
        st = plot.select_checkpoint()
Esempio n. 6
0
def readInStories(inputFilenames):
    stories = []
    for fileName in inputFilenames:
        with open(fileName, 'r', encoding="UTF-8") as jsonFile:
            data = json.load(jsonFile)
            stories.append(Story(data))
    return stories
Esempio n. 7
0
def upload():
    if request.method == "POST":
        # Grab POST data from submitted form
        input_title = request.form.get("title")
        input_file = request.files["file"]
        # Get specific user based on uid stored in session
        user = UserList.getUserByID(session["uid"])

        # Handle file upload
        isValidFile = True
        message = "Upload successful"
        filename = input_file.filename
        # Checks for valid file name / format
        if not isValidFileType(filename):
            isValidFile = False
            message = "Invalid file type"
        if isValidFile:
            # Get the directory of this current User.py script
            currPath = os.path.dirname(__file__)
            relativePath = "/userdata" + user.getDirectory()
            projectPath = currPath + relativePath + filename
            input_file.save(projectPath)
        else:
            # If invalid, return now, providing an error message
            return redirect(url_for("feed", message=message))

        # Otherwise, continue to make a new story
        newStory = Story(projectPath, input_title)
        user.addStory(newStory)
        return redirect(url_for("feed", message=message))
    else:
        # Else method is GET - display login form
        return render_template("login.html",
                               message="Must be logged in to upload.")
Esempio n. 8
0
    def __init__(self,
                 name,
                 password,
                 directory,
                 imageURL="/static/img/default_profile.jpg"):
        # Username
        self.__name = name
        # Directory of data stored
        self.__directory = directory
        # Profile picture URL
        self.__imageURL = imageURL

        storiesList = []
        # Get the directory of this current User.py script
        currPath = os.path.dirname(__file__)
        relativePath = "userdata" + directory
        fullPath = os.path.join(currPath, relativePath)
        filesList = os.listdir(fullPath)
        for file in filesList:
            projectPath = os.path.join(fullPath, file)
            # Use the file name (sans the file ext) as the caption
            caption = file.split(".")[0]
            storiesList.append(Story(projectPath, caption))
        # Stories List
        self.__storiesList = storiesList

        # userID
        self.__userID = User.userID
        # Increment static UID by 1
        User.userID += 1
        password = password.encode("utf-8")
        hashed_password = hashlib.sha256(password)
        self.__password = hashed_password
Esempio n. 9
0
    def get_story():
        if len(stories) <= 0:
            import_stories()
        #  chooses story randomly
        index = random.randrange(len(stories))
        new_story = Story(stories[index])
        #  removes this story from list so that it won't be repeated
        del stories[index]

        return new_story
Esempio n. 10
0
 def __init__(self):
     """Game Instance responsible For all non visual work"""
     
     # Keep track of how long we have been playing.
     self.gameTime = None
     self.frameTimer = QTimer()
     
     # Manage Character
     self.character = None
     
     # Manage Game Progression
     self.story = Story(self.FRAME_RATE)
     
     # Manage World
     self.places = Places()
Esempio n. 11
0
 def __init__(self):
     """Game Instance responsible For all non visual work"""
     
     # Keep track of how long we have been playing.
     self.gameTime = None
     self.frameTimer = QTimer()
     
     # Manage Character
     self.character = None
     
     # Manage Game Progression
     self.story = Story(self.FRAME_RATE)
     
     # Manage World
     self.places = Places()
     
     # Store player's name
     self.playerName = ""
     
     # Store scores from previous play
     self.scoreList = []
     self.topTen = True
Esempio n. 12
0
class Game(QObject):
    """Container to hold one new or loaded game instance"""
    FRAME_RATE = 25 # Frame rate in frames per second.
    
    def __init__(self):
        """Game Instance responsible For all non visual work"""
        
        # Keep track of how long we have been playing.
        self.gameTime = None
        self.frameTimer = QTimer()
        
        # Manage Character
        self.character = None
        
        # Manage Game Progression
        self.story = Story(self.FRAME_RATE)
        
        # Manage World
        self.places = Places()

    def new(self):
        """Load new game from file"""
        debug("newgame...loading clues")
        self.story.loadClues()
        debug("newgame...loading charcter")
        self.character = Character((0,0), "Character", "Character")
        debug("newgame...loading places")
        self.places.loadLoc()
        debug("end of load")
        self.places.addLoc(self.character)
        self.story.currClue = self.story._clueList.pop()
        #self.frameTimer = QTimer() # Create Frame Timer
        self.gameTime = QTime()
        self.launch()
        
        
    def load(self,filename):
        """Load existing game from file"""
        
        debug("loadgame...read data from saved file")
        debug("loadgame...loading clues")
        self.story.loadClues()
        
        savedData = open(filename)    
        nextLine = savedData.readline()
        # Parsing saved file
        while (nextLine):
            line = nextLine.split()
            if (len(line) == 4 and self.loadIsValid(line)):
                x = int(line[0])
                y = int(line[1])
                numClues = int(line[2])+1
                self.story._clueList =  self.story._clueList[:numClues]
                self.story.score = int(line[3])
                debug("x: " + `x` + " y: " + `y` + " numCLue: " + `len(self.story._clueList)` + \
                      " score is: " + `int(line[3])`)
            nextLine = savedData.readline()       
        savedData.close()
        self.story.currClue = self.story._clueList.pop()
        
        debug("loadgame...loading initial character and places")
        self.character = Character((x,y), "Character", "Character")
        self.places.loadLoc()
        
        debug("end of load")
        self.places.addLoc(self.character)
        # FIXME if QTime and QTimer should be stored in certain way
        self.gameTime = QTime()
        #self.frameTimer = QTimer() # Create Frame Timer
        self.launch()
    
    def loadIsValid(self,obj):
        """Check that the input from saved file is valid"""         
        posx = obj[0]
        posy = obj[1]
        numClue = obj[2]
        score = obj[3]
        try:
            int(posx) and int(posy) and int(numClue) and int(score)
        except:
            debug("Invalid position input in save file")
            return False
        return True
    
    def save(self, filename):
        """Save to file"""
        fname = open(filename, "w")
        score = `self.story.score`
        numClues = `len(self.story._clueList)`
        charX, charY = self.character.getCenter()
        toWriteList = '\t' + `charX` + '\t' + `charY` + '\t' + \
                        numClues + '\t' + score
        fname.write(toWriteList)     
        fname.close()
    
    def endGame(self):
        """Make things tidy for another game instance"""
        # Signal that we have won the game and should
        None
    
    def launch(self):
        """Start sending signals to the game using Timers"""
        self.gameTime.start()
        self.frameTimer.start(ONE_SECOND/self.FRAME_RATE)
        self.frameTimer.timeout.connect(self.story.frameTime)
        
    def keyPress(self, event):
        key = event.key()
        self.character.keyPress(key)
        
    def keyRelease(self, event):
        key = event.key()
        self.character.keyRelease(key)
Esempio n. 13
0
from Person import Person
from Story import Story
from Car import Car
from School import School
from Choice import Choice
import time

if __name__ == '__main__':
    story = Story()
    story.introduce()
    story.wait(3)
    story.Begining()
    story.wait(3)
    choice = Choice()
    choice.choice1()
    story.wait(3)
    story.Transmission()
    story.wait(3)
    story.interview()
    story.wait(3)
    story.Fightingyears()
    story.wait(3)
    story.endline()
    choice.choice2()
Esempio n. 14
0
#_*_encoding:utf-8_*_

__author__ = 'lizhanguo'

from Person import Person
from Car import Car
from School import School
from Story import Story
from Choice import Choice
import gl
import time

#主程序开始
if __name__ == '__main__':
    #初始化各个类
    story = Story()
    John = Person('John',22,'M','China','None','None','Basketball')
    Liz = Person('Liz',22,'F','China','None','None','Dance')
    Peter = Person('Peter',28,'M','USA','Manager','30000','Golf')
    car = Car('法拉利')
    choice = Choice()
    school = School()

    #主角介绍
    story.intro()
    story.wait(5)
    #故事开始
    story.begin()
    #工作选择
    choice.choice1()
    story.wait(5)
Esempio n. 15
0
 def addStory(self, storyName, author, firstEntry):
     Story.makeStory(storyName, author, entry)
Esempio n. 16
0
def test_storyfile_json():
    jfile = open("jira_story.json")

    story = Story(json.loads(jfile.read()))

    return story.get_story()
Esempio n. 17
0
from player import Player
from Enemy import *
from inventory import *
from npc import *
from fight import Fight
from Story import Story

p = Player("asd")
s = Story(p)
print(s.greeting())
s.chap1()
"""
f = Fight(p, anidict["Rat"])
p.app_weapons(weaponsdict["copper sword"])
p.equip_weapon(p.weapons["copper sword"])
p.app_armor(armordict["cloth armor"])
p.equip_armor(p.armor["cloth armor"])

print(f.fight_c())
print(p.experience)

for name in vendorsdict:
    print(name, vendorsdict[name].inventory)

for w in weaponsdict:
    print(vars(weaponsdict[w]))

for hi in healthitems: 
    print(vars(healthitems[hi]))

for a in armordict:
Esempio n. 18
0
    def loadStories(self):
        storyNum = 0
        for st in self.gamedata.stories.story:
            storyNum += 1
            currStory = Story(storyNum, st.name.cdata, st.startRoom.cdata,
                              st.description.cdata)

            for room in st.room:
                currRoom = Room(room.name.cdata, room.description.cdata,
                                room.art.cdata, room.interactables.cdata)
                currStory.addRoom(currRoom)

            for item in st.item:
                currItem = Item(item.name.cdata, item.description.cdata,
                                item.sellable.cdata, item.value.cdata)
                currStory.addItem(currItem)

            for interactable in st.interactable:
                currInteractable = Interactable(
                    interactable.name.cdata, interactable.description.cdata,
                    interactable.requiredEffects.cdata.split(','))
                #this is fine, we can just check for req effect name in player's effect list
                for action in interactable.action:
                    currAction = Action(
                        action.name.cdata, action.description.cdata,
                        action.failDescription.cdata, action.item.cdata,
                        action.requiredEffects.cdata,
                        action.givenEffects.cdata, action.removedEffects.cdata,
                        action.requiredItems.cdata, action.givenItems.cdata,
                        action.removedItems.cdata, action.newDesc.cdata,
                        action.newItems.cdata, action.newArt.cdata,
                        action.newInteractables.cdata)

                    currInteractable.addAction(currAction)
                currStory.addInteractable(currInteractable)

            for effect in st.effect:
                try:
                    effectName = effect.name.cdata
                    if effect.isRoomChange.cdata == "True" and effect.isRoomChange[
                            'roomname'] == '':
                        raise invalidSetup(Exception)
                    currEffect = Effect(effect.name.cdata,
                                        effect.description.cdata,
                                        effect.isRoomChange.cdata,
                                        effect.isRoomChange['roomname'])
                except AttributeError:
                    currEffect = Effect(effect.name.cdata,
                                        effect.description.cdata)
                except invalidSetup:
                    print('Warning: InvalidEffect - EFFECT[' + effectName +
                          '] STORY[' + currStory.name + '] ROOMCHANGE INGORED')
                    currEffect = Effect(effect.name.cdata,
                                        effect.description.cdata)
                currStory.addEffect(currEffect)

            player = Player(st.player.name.cdata, st.player.description.cdata,
                            st.player.effects.cdata, st.player.items.cdata,
                            st.player.art.cdata)
            currStory.setPlayer(player)

            self.stories.append(currStory)
Esempio n. 19
0
class Game(QObject):
    """Container to hold one new or loaded game instance"""
    FRAME_RATE = 25 # Frame rate in frames per second.
    
    def __init__(self):
        """Game Instance responsible For all non visual work"""
        
        # Keep track of how long we have been playing.
        self.gameTime = None
        self.frameTimer = QTimer()
        
        # Manage Character
        self.character = None
        
        # Manage Game Progression
        self.story = Story(self.FRAME_RATE)
        
        # Manage World
        self.places = Places()
        
        # Store player's name
        self.playerName = ""
        
        # Store scores from previous play
        self.scoreList = []
        self.topTen = True
        
    def new(self):
        """Load new game from file"""
        debug("newgame...loading clues")
        self.story.loadClues()
        debug("newgame...loading charcter")
        self.character = Character((0,0), "Character", "Character")
        debug("newgame...loading places")
        self.places.loadLoc()
        debug("end of load")
        self.places.addLoc(self.character)
        self.story.currClue = self.story._clueList.pop()
        #self.frameTimer = QTimer() # Create Frame Timer
        self.gameTime = QTime()
        self.launch()
        
    def load(self,filename):
        """Load existing game from file"""
        
        debug("loadgame...read data from saved file")
        debug("loadgame...loading clues")
        self.story.loadClues()
        
        savedData = open(filename)    
        nextLine = savedData.readline()
        # Parsing saved file
        while (nextLine):
            line = nextLine.split()
            if (len(line) == 5 and self.loadIsValid(line)):
                x = int(line[0])
                y = int(line[1])
                numClues = int(line[2])+1
                self.story._clueList =  self.story._clueList[:numClues]
                self.story.score = int(line[3])
                self.playerName = line[4]
            nextLine = savedData.readline()       
        savedData.close()
        self.story.currClue = self.story._clueList.pop()
        
        debug("loadgame...loading initial character and places")
        self.character = Character((x,y), "Character", "Character")
        self.places.loadLoc()
        
        debug("end of load")
        self.places.addLoc(self.character)
        # FIXME if QTime and QTimer should be stored in certain way
        self.gameTime = QTime()
        #self.frameTimer = QTimer() # Create Frame Timer
        self.launch()
      
    def loadIsValid(self,obj):
        """Check that the input from saved file is valid"""         
        posx = obj[0]
        posy = obj[1]
        numClue = obj[2]
        score = obj[3]
        try:
            int(posx) and int(posy) and int(numClue) and int(score)
        except:
            debug("Invalid position input in save file")
            return False
        return True
    
    def loadScores(self, filename = "saves/player.score"):
        """load the 10 highest score from file"""
        scoreData = open(filename)    
        nextLine = scoreData.readline()
        # Parsing saved file
        while (nextLine):
            prevScore = nextLine.strip().split(";")
            if (len(prevScore) == 2):
                loadedName = prevScore[0]
                loadedScore = int(prevScore[1])
                self.scoreList.append((loadedName, loadedScore))
            nextLine = scoreData.readline()       
        scoreData.close()
        self.addCurrScoreToList()
    
    def addCurrScoreToList(self):
        """save player's score into top 10 list if the player make it"""
        listLen = len(self.scoreList)
        lowestScore = 0
        
        if (listLen > 0):
            lowestScore = self.scoreList[-1][1]
        if (self.story.score <= lowestScore and listLen > 9):
            debug("player's score is not high enough to write to file")
            self.topTen = False
            return
        elif listLen < 10:
            debug("Player score append to scoreList")
            self.scoreList.append((self.playerName, self.story.score))
        else:
            debug("Pop the bad score, and add in player score to file")
            self.scoreList.pop()
            self.scoreList.append((self.playerName, self.story.score))
        # sorted previous player by score
        self.scoreList = sorted(self.scoreList, \
                                key = itemgetter(1), reverse = True) 
        
    def writeScoreToFile(self, filename = "saves/player.score"):
        """Save the 10 highest score to file.."""
        text = ""
        if (len(self.scoreList)<=10):
            scoreFile = open(filename, "w")
            while (self.scoreList):
                scores = self.scoreList.pop()
                text = text + scores[0] + ";" + `scores[1]` + "\n"
            scoreFile.write(text)
            scoreFile.close()
        else:
            print "Error: Too many scores to be stored in scoreList"
            return    
        
    def save(self, filename):
        """Save to file"""
        fname = open(filename, "w")
        score = `self.story.score`
        numClues = `len(self.story._clueList)`
        charX, charY = self.character.getCenter()
        name = self.playerName
        toWriteList = '\t' + `charX` + '\t' + `charY` + '\t' \
                       + numClues + '\t'+ score + '\t'+ name
        fname.write(toWriteList)     
        fname.close()
            
    def endGame(self):
        """Make things tidy for another game instance"""
        # Signal that we have won the game and should
        None
    
    def launch(self):
        """Start sending signals to the game using Timers"""
        self.gameTime.start()
        self.frameTimer.start(ONE_SECOND/self.FRAME_RATE)
        self.frameTimer.timeout.connect(self.story.frameTime)
        
    def keyPress(self, event):
        """Recieve events from keyboard, pass to update character movement"""
        key = event.key()
        self.character.keyPress(key)
        
    def keyRelease(self, event):
        """Recieve events from keyboard, pass to update character movement"""
        key = event.key()
        self.character.keyRelease(key)
Esempio n. 20
0
class GUI(Frame):
    def __init__(self, master):
        super().__init__(master)
        self.grid()
        self.__master = master
        #First window information
        self.readMyStoryLabel = Label(self,
                                      text="readMyStory",
                                      font=("Courier", 30))
        # self.readMyStoryLabel.grid(row=0, column=2)
        self.readMyStoryLabel.grid()

        img = PhotoImage(Image.open("bookEmoji.png"))
        panel = Label(self, image=img)
        self.panel.grid()

        self.infoText1 = Label(
            self,
            text="You have the option of creating your own story or \n "
            "filling in a MadLibs that will then be read out for you \n"
            "at the end! You will even get the option to \n"
            "save your wonderful story!",
            font=("Courier", 12))
        self.infoText1.grid()
        # self.infoText1.grid(row=1, column=2)
        # buttons
        self.createOwnButton = Button(
            self, text="Create Own!",
            command=self.createOwn)  #.pack(side=LEFT)
        self.createOwnButton.grid()
        # self.createOwnButton.grid(row=2, column=2)
        self.madLibsButton = Button(self,
                                    text="MadLibs!",
                                    command=self.madLibs)  #.pack(side=RIGHT)
        self.madLibsButton.grid()
        # self.madLibsButton.grid(row=2, column=2)

    def createOwn(self):  #user decided to create their own story
        tkinter.messagebox.showinfo(
            "Create Own!", "You have chosen to create your own story!")
        self.infoText1.grid_remove()  #this is to remove the information text
        # remove the buttons
        self.madLibsButton.grid_remove()
        self.createOwnButton.grid_remove()

        #create story object
        self.story = Story()

        # The default text for the window
        content = StringVar()
        self.storyBox = Entry(self, width=40,
                              textvariable=content)  #adding it to the box
        self.storyBox.bind('<FocusIn>', self.on_entry_click)
        content.set("Story here")
        self.storyBox.config(fg='grey')
        self.storyBox.grid()

        self.readButton = Button(self,
                                 text="Read aloud",
                                 command=self.callRead)
        self.readButton.grid()

        self.saveLabel = Label(self,
                               text="Enter a filename to save your story")
        self.saveLabel.grid()
        self.saveFileName = Entry(self, width=35)
        self.saveFileName.grid()
        self.saveButton = Button(self,
                                 text="Save Story",
                                 command=self.saveStory)
        self.saveButton.grid()

    def on_entry_click(self, event):  #will clear the default text
        if self.storyBox.get() == "Story here":
            self.storyBox.delete(0, "end")  # delete all the text in the entry
            self.storyBox.insert(0, '')  # Insert blank for user input
            self.storyBox.config(fg='black')

    # def on_focusout(self):

    def madLibs(self):  #user wanted to do the mad libs version
        tkinter.messagebox.showinfo("MadLibs!",
                                    "You have chosen to do a MadLib Story!")
        # clear the main and start
        self.infoText1.grid_remove()  # this is to remove the information text
        # remove the buttons
        self.madLibsButton.grid_remove()
        self.createOwnButton.grid_remove()

        #create the MadLib object
        self.mlObject = MadLib()
        listofStories = self.mlObject.getListOfStories()

        self.selectStoryText = Label(self, text="Please select a story below")
        self.madLibsStoryList = Listbox(
            self.__master)  #passing in the window to add it
        for item in listofStories:  #iterate to add
            self.madLibsStoryList.insert(END, item)

        self.madLibsStoryList.grid()
        self.selectStoryButton = Button(self,
                                        text="Select",
                                        command=self.setSelected)
        self.selectStoryButton.grid()

    def callRead(self):
        if self.storyBox.get(
        ) != "":  #will only call on it if the box is filled out
            if self.storyBox.get(
            ) != "Story here":  #will only read it if it's not default text
                self.story.read(self.storyBox.get())  #will read the text
        else:
            msg = "Please enter some text to be read!"
            # self.story.read(msg)  # will read the text to tell the user to enter text
            tkinter.messagebox.showinfo("Nothing to Read!", msg)

    def saveStory(self):
        if self.storyBox.get(
        ) != "":  #will only call on it if the box is filled out
            #get the text from the save box
            if self.saveFileName.get() != "":
                #check if the end of the file is a .txt, if not add it
                print("old filename " + self.saveFileName.get())  #debugg
                self.fileName = self.saveFileName.get()
                if ".txt" not in self.fileName:
                    self.fileName += ".txt"  #append it at the end
                self.story.save(self.storyBox.get(), self.fileName)
            else:
                tkinter.messagebox.showinfo("No filename!",
                                            "Please enter a filename!")

        else:
            msg = "Please write a story to be saved!"
            # self.story.read(msg)  # will read the text to tell the user to enter text
            tkinter.messagebox.showinfo("Nothing to Save!", msg)

    def setSelected(self):
        selected = self.madLibsStoryList.get(ACTIVE)
        print(selected)
        #call on the next action command from here
        self.showStory(selected)
        return selected

    def showStory(self,
                  selectedStory):  #this will grab the text from the sotyr
        storyFile = open("Stories/" + selectedStory.rstrip(),
                         "r")  #go into the folder to get the stories

        #remove the items from previous window
        self.madLibsStoryList.grid_remove()
        self.selectStoryButton.grid_remove()

        story = ""  #starts off blank
        for line in storyFile:
            story += line
        storyFile.close()  #close the file after done reading from it
        self.madLibLabel = Label(
            self,
            text=
            "Replace all of the words with _someWord_ and hear your story by clicking the Read button",
            wraplength=250)
        self.madLibLabel.grid()

        self.storyTextBox = Text(self, width=50, height=10)
        self.storyTextBox.config(background="beige")
        self.storyTextBox.grid()
        self.storyTextBox.insert(END, story)  # adding the liens to the file

        #buttons to read & save
        self.readButton2 = Button(self,
                                  text="Read aloud",
                                  command=self.callReadMadLib)
        self.readButton2.grid()

        self.saveLabel2 = Label(self,
                                text="Enter a filename to save your story")
        self.saveLabel2.grid()
        self.saveFileName2 = Entry(self, width=20)
        self.saveFileName2.grid()
        self.saveButton2 = Button(self,
                                  text="Save File!",
                                  command=self.saveStory)
        self.saveButton2.grid()

    def callReadMadLib(self):
        if self.storyTextBox.get(
                "0.0",
                END) != "":  #will only call on it if the box is filled out
            if self.storyTextBox.get(
                    "0.0", END
            ) != "Story here":  #will only read it if it's not default text
                self.mlObject.read(self.storyTextBox.get(
                    "0.0", END))  #will read the text
        else:
            msg = "Please enter some text to be read!"
            tkinter.messagebox.showinfo("Nothing to Read!", msg)
Esempio n. 21
0
    def transfer_session_info_to_story(identifier, message_list, story_obj: Story):

        for message in message_list:
            story_obj.push_message(identifier, message)