Beispiel #1
0
 def change_world_size(self):
     """Creates new world with user input for rows and columns."""
     rows = get_integer(input("rows: "))
     columns = get_integer(input("columns: "))
     newWorld = World(rows, columns)
     self.rows = rows
     self.columns = columns
     self.world = newWorld
     self.world.populate_cells(self.percentAlive)
     self.world.get_living_cells()
     for cell in self.world.cellList:
         cell.assign_neighbors()
     print(self.world)
     return self.world
Beispiel #2
0
 def sim(self, parameter):
     """Simulates throught generations of the current world"""
     if self.world == None:
         print("You haven't made a world yet\n")
     elif self.world.count_living() == 0:
         print('All your cells are dead, please populate your world\n')
     else:
         if parameter!= None:
             generations = parameter
         else:
             generations = get_integer("How many generations do you want to move forward? ")
         counter = 0
         self.world.state = 'alive'
         while int(generations) > counter and self.world.count_living() > 0:
             self.world.next_cell_status()
             self.world.create_next_world()
             counter += 1
             #
             # Remove the time sleep when running speed test
             #
             time.sleep(self.speed)
             print(self.world)
         if self.world.count_living() == 0:
             print('Your cells all died at generation ', self.world.generation)
         elif self.world.state == 'stale':
             print('Your world will not change in its current state\n')
         elif self.world.state == 'blinker':
             print('All you have left is blinkers')
Beispiel #3
0
 def get_rows(self):
     """
     Gets amount of rows in new world from user.
     :return: rows
     """
     rows = toolbox.get_integer("How many rows do you want in your world? ")
     return rows
Beispiel #4
0
 def get_generations(self):
     """
     gets a number of generations from the user
     :return: number of generations
     """
     generations = toolbox.get_integer("How many generations do you want to advance? ")
     return int(generations)
Beispiel #5
0
 def skip_back(self, generations):
     if generations > len(self.world.previousGenerations):
         print("Error: could not go back that far in previous generations.")
         while generations > len(
                 self.world.previousGenerations) and generations >= 0:
             generations = (get_integer(
                 f"Enter a number less than {len(self.world.previousGenerations)}. "
             )) + 1
     genCount = self.world.genNumber
     newGenCount = genCount - generations
     generations += 1
     selected = self.world.previousGenerations[-generations]
     textGeneration = selected.split('\n')[1:]
     rows = len(textGeneration)
     columns = len(textGeneration[0])
     fullText = ''
     for _ in textGeneration:
         fullText += _
     # makes it a new world to display
     world = World(rows, columns)
     for cell in world.cellList:
         index = world.cellList.index(cell)
         correspondingText = fullText[index]
         if correspondingText == World.aliveASCII:
             cell.living = True
         else:
             cell.living = False
     self.world = world
     for cell in self.world.cellList:
         cell.assign_neighbors()
     self.world.get_living_cells()
     self.world.genNumber = newGenCount
     print(world)
Beispiel #6
0
 def get_columns(self):
     """
     gets amount of columns in new world from user
     :return: columns
     """
     columns = toolbox.get_integer(
         "How many columns do you want in your world? ")
     return columns
Beispiel #7
0
    def change_world_size(self, size=None):
        """
        Create a new world with the given size.

        :param size: [optional] list containing the number of rows and columns
        :return: None
        """
        if size == None:
            rows = get_integer('How many rows should the new world have?')
            columns = get_integer('How many columns should the new world have?')
        else:
            rows = size[0]
            columns = size[1]
        self.generation = self.generationType(rows, columns, self.geometry, self.rules)
        self.generation.assign_neighbors()
        self.generation.populate_cells(self.initialPercentAlive)
        self.message = 'world size changed'
        self.generationCount = 1
        self.timeLine = []
        print(self)
Beispiel #8
0
    def rule_change(self, newRules=None):
        """
        Change the rules for the simulation.
        :param newRules: string with two integers separated by a space:
                         integer1: number of neighbors where a cell continues living
                         integer2: number of neighbors where a dead cell comes alive

                         The default rules are: '23 3'
        :return:
        """
        if newRules is None:
            self.help('rules.txt')
            remainAlive = get_integer('Cells remaing alive with this many neighbors:')
            generate =  get_integer('Cells become alive with this many neighbors :')
        else:
            remainAlive = newRules[0]
            generate = newRules[1]
        remainAlive = [int(number) for number in str(remainAlive)]
        generate = [int(number) for number in str(generate)]
        self.rules = [remainAlive, generate]
        self.generation.rules = self.rules
        self.message = 'The rules have changed'
        print(self)
Beispiel #9
0
 def change_population_rate(self, percentAlive=None):
     """
     Create a new world with the given percent of cells alive.
     :param percentAlive: [optiona] Number of living cells out of total cells.
     :return: None
     """
     if percentAlive == None:
         percentAlive = get_integer('What percent should be alive?')
     self.generation = self.generationType(self.generation.rows, self.generation.columns, self.geometry, self.rules)
     self.generation.assign_neighbors()
     self.generation.populate_cells(percentAlive)
     self.initialPercentAlive = percentAlive
     self.message = 'world population changed'
     self.generationCount = 1
     self.timeLine = []
     print(self)
Beispiel #10
0
 def skip(self, parameter):
     """Skips a number of generations of the current world"""
     if self.world == None:
         print("You haven't made a world yet")
     elif self.world.count_living() == 0:
         print('All your cells are dead, please populate your world')
     else:
         if parameter != None:
             generations = parameter
         else:
             generations = get_integer("How many generations do you want to skip? ")
         counter = 0
         while int(generations) > counter and self.world.count_living() > 0:
             self.world.next_cell_status()
             self.world.create_next_world()
             counter += 1
         if self.world.count_living() == 0:
             print('Your cells all died at generation ', self.world.generation)
Beispiel #11
0
 def skip_backwards(self, generations=None):
     """
     Loop through the number of generations specified without displaying the
     intermediate generations.
     :param generations: [optional] number of generations to skip
     :return: None
     """
     if generations == None:
         generations = get_integer('How many generations?')
     if generations > len(self.timeLine):
         generations = len(self.timeLine)
     if generations:
         for _ in range(generations):
             self.generation.set_generation(self.timeLine.pop())
             self.generationCount -= 1
         self.message = f'skipped backwards {generations} generations'
     else:
         self.message = 'No previous generations exist.'
     print(self)
Beispiel #12
0
 def get_geometry(self):
     """
     Changes the type of world from a world with boundaries or a wrap around world
     :return:
     """
     print("""
     1) Normal World
     2) Torus World (no corners, world wraps around)
     """)
     geometry = toolbox.get_integer("What type of world would you like to have?")
     if geometry == 1:
         self.__worldType = World
     else:
         self.__worldType = World_Torus
     sleep(1)
     print("...creating new world...")
     sleep(2)
     print(self.__world)
     self.show_status()
Beispiel #13
0
 def back_x_generations(self, generations):
     """Reads and displays former generations saved in world.previousGenerations. Displays each former generation."""
     #
     # so it doesn’t count current generation (added to previousGenerations during world.next_generation())
     #
     generations += 1
     previousGenerations = self.world.previousGenerations
     if generations > len(previousGenerations):
         print("Error: could not go back that far in previous generations.")
         while generations > len(previousGenerations) and generations >= 0:
             generations = (get_integer(
                 f"Enter a number less than {len(previousGenerations)}. ")
                            ) + 1
     newGenList = previousGenerations[0:-(generations)]
     #
     # list of selected generation to end of previousGenerations
     #
     goBack = previousGenerations[-generations:]
     goBack.reverse()
     goBack.remove(goBack[0])
     for generation in goBack:
         textGeneration = generation.split('\n')[1:]
         rows = len(textGeneration)
         columns = len(textGeneration[0])
         fullText = ''
         for _ in textGeneration:
             fullText += _
         world = World(rows, columns)
         for cell in world.cellList:
             index = world.cellList.index(cell)
             correspondingText = fullText[index]
             if correspondingText == World.aliveASCII:
                 cell.living = True
             else:
                 cell.living = False
         print(world)
     self.world = world
     for cell in self.world.cellList:
         cell.assign_neighbors()
     self.world.get_living_cells()
     self.world.previousGenerations = newGenList
     self.world.genNumber = len(newGenList) + 1
Beispiel #14
0
 def skip_forward(self, generations=None):
     """
     Loop through the number of generations specified without displaying the
     intermediate generations.
     :param generations: [optional] number of generations to skip
     :return: None
     """
     if generations == None:
         generations = get_integer('How many generations?')
     stable = False
     current = 0
     while (current < generations) and not stable:
         self.timeLine.append(self.generation.get_generation())
         self.generation = self.generation.next_generation()
         current += 1
         stable = self.is_stable()
     self.message = f'skipped forward {current} '
     if stable:
         self.message += '[stable position reached]'
     self.generationCount += current
     print(self)
Beispiel #15
0
 def skip_advance(self, parameter):
     """
     Run generations but only show the last one
     :param parameter:
     :return: none
     """
     lifeTime = toolbox.get_integer(
         'How many generations would you like to go through? ')
     life = 1
     while life <= lifeTime:
         if life == lifeTime:
             self.__currentWorld.next_generation()
             string = f'››››››››››››››››››››››››››››››››››››››››\n'
             string += f'{self.__currentWorld}\n'
             string += f'{self.status_bar(life)}\n'
             string += f'‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹\n'
             print(string)
             life += 1
         else:
             self.__currentWorld.next_generation()
             life += 1
Beispiel #16
0
 def advance(self, parameter):
     """
     Ask user how many times they would like to run though generations
    :param parameter:
     :return: none
     """
     lifeTime = toolbox.get_integer(
         'How many generations would you like to go through? ')
     life = 1
     again = True
     while life <= lifeTime:
         if again == True:
             self.__currentWorld.next_generation()
             string = f'››››››››››››››››››››››››››››››››››››››››\n'
             string += f'{self.__currentWorld}\n'
             string += f'{self.status_bar(life)}\n'
             string += f'‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹\n'
             print(string)
             again = self.__currentWorld.rerun()
             sleep(self.__delay)
             life += 1
         else:
             break
     print('Simulation Ended')
Beispiel #17
0
    def play(self):
        """Main Event Loop. Calls former simulation methods for user to play Life."""
        mainMenu = """[h]elp [n]ext [p]revious [e]dit world [o]pen [s]ave [q]uit"""
        self.display_status_bar()
        print(mainMenu)
        command = ''
        try:
            command = self.get_command('Enter command: ')
        except:
            #
            #if command == '', next code
            #
            if self.world.steady_state() == True:
                print("""
========================================================================================================================
World is currently in a steady state.
========================================================================================================================
""")
                self.enterCommand = "p"
            self.enter(self.enterCommand)
        try:
            #
            #selects action based on command from Main Menu
            #placed in try/except due to an error with the 'q' method.
            #
            if command[0][0] == 'h':
                print("""=======================================""")
                myPath = './'
                filename = os.path.join(myPath, 'Help.txt')
                myFile = open(filename, 'r')
                text = myFile.read()
                myFile.close()
                print(text)
                print("""=======================================""")
                print(self.world)
                self.play()
            elif command[0][0] == 'n':
                if self.world.steady_state() == True:
                    #
                    #prohibits player from progressing forwards with Progress Forwards Menu.
                    #
                    print("""
========================================================================================================================                 
World is in a steady state.
========================================================================================================================
""")
                    self.play()
                else:
                    #
                    #if not prohibited...
                    #
                    self.enterCommand = 'n'
                    command = self.get_command_forward('Enter command: ')
                    if len(command) == 0:
                        command = 'n'
                    if command[0][0] == 'n':
                        self.multiple_generations(1)
                        self.play()
                    elif command[0][0] == 'm':
                        if len(command) == 1:
                            generations = get_integer(
                                input("How many generations? "))
                        else:
                            generations = command[1]
                        self.multiple_generations(generations)
                        self.play()
                    elif command[0][0] == 's':
                        if len(command) == 1:
                            generations = get_integer(
                                input(
                                    "How many generations do you want to skip? "
                                ))
                        else:
                            generations = command[1]
                        self.skip_x_generations(generations)
                        self.play()
            elif command[0][0] == 'p':
                #
                #Determines action based on Progress Backwards Menu
                #
                self.enterCommand = 'p'
                command = self.get_command_back('Enter command: ')
                if command[0][0] == 'p':
                    self.back_x_generations(1)
                    self.play()
                elif command[0][0] == 'b':
                    if len(command) == 1:
                        generations = get_integer(
                            input("How many generations? "))
                    else:
                        generations = command[1]
                    self.back_x_generations(generations)
                    self.play()
                elif command[0][0] == 's':
                    if len(command) == 1:
                        generations = get_integer(
                            input(
                                "How many generations do you want to skip? "))
                    else:
                        generations = command[1]
                    self.skip_back(generations)
                    self.play()
                elif command[0][0] == 'r':
                    self.reset_timeline()
                    self.enterCommand = 'n'
                    self.play()
            elif command[0][0] == 'e':
                #
                #Determines action based on Edit World Menu
                #
                command = self.get_command_edit_world('Enter command: ')
                if command[0][0] == 's':
                    if len(command) == 1:
                        newSpeed = get_positive_number(input("New speed: "))
                    else:
                        newSpeed = command[1:]
                    self.change_speed(newSpeed)
                    self.play()
                elif command[0][0] == 'p':
                    if len(command) == 1:
                        newRate = get_integer(input("New rate: "))
                    else:
                        newRate = command[1]
                    self.change_population_rate(newRate)
                    self.play()
                elif command[0][0] == 'w':
                    self.change_world_size()
                    self.play()
                elif command[0][0] == 't':
                    self.toggle_geometry()
                    self.play()
                elif command[0][0] == 'r':
                    toLetLive = []
                    anotherNum = True
                    while anotherNum != False and len(toLetLive) <= 8:
                        num = get_integer(
                            "Enter a number of neighbors that cells can live with: "
                        )
                        if num > 8 or num < 0:
                            anotherNum = True
                        else:
                            toLetLive.append(num)
                            anotherNum = yes_or_no("Enter another number? ")
                    toMakeAlive = -1
                    while toMakeAlive < 0 or toMakeAlive > 8:
                        toMakeAlive = get_integer(
                            "With what number of neighbors should cells become alive? "
                        )
                    self.change_rules(toLetLive, toMakeAlive)
                    self.play()
            elif command[0][0] == 'o':
                self.open()
                self.play()
            elif command[0][0] == 's':
                self.save()
                self.play()
            elif command[0][0] == 'q':
                print(
                    """========================================================================================================================"""
                )
                print('End of Life Simulation. Thanks for playing!')
                print(
                    """========================================================================================================================"""
                )
                pass
        except:
            pass