PYTHON   5

GameOfLife4.py

Guest on 6th June 2021 05:05:31 PM

  1. # Game Of Life 2
  2.  
  3. # This prompts for and reads an input file for the initial
  4. # configuration. Eventually, it will get the file from a text
  5. # box in the graphics window
  6.  
  7. from GameBoard4 import Board
  8. from LifeDisplay import LifeDisplay, Button
  9. import time
  10.  
  11. def main():
  12.     print("Welcome to the Game of Life.")
  13.  
  14.     #   Create game window
  15.     initStrings = getInputFile()
  16.  
  17.     win = LifeDisplay(150, 100)
  18.  
  19.     currBoard = Board(initStrings, win)
  20.     gens = currBoard.generations()
  21.     win.updateGeneration(gens)
  22.     prevBoard = Board()
  23.  
  24.  
  25.     while gens < 250 and not stopped(win):
  26.         if currBoard.empty():
  27.             print("Game ended. Empty board reached after",
  28.                   gens, "generations.")
  29.             return
  30.  
  31.         nextBoard = Board(currBoard)
  32.         gens = nextBoard.generations()
  33.         win.updateGeneration(gens)
  34.         if nextBoard == prevBoard:
  35.             print("Game ended. Repetition after",
  36.                   gens, "generations")
  37.             return
  38.         else:
  39.             time.sleep(0.125)
  40.             prevBoard, currBoard = currBoard, nextBoard
  41.  
  42.     print("Game forcibly stopped after", currBoard.generations(),
  43.           "generations")
  44.     print("End of test ....")
  45.     return
  46.  
  47. def stopped(win):
  48.     mouse = win.checkMouse()
  49.     if mouse is not None and \
  50.         win.stopButton().clicked(mouse):
  51.             return True
  52.     else:
  53.         return False
  54.  
  55. def getInputFile():
  56.     fileName = input("Enter file name to initialize:- ")
  57.     inputFile = open(fileName, 'r')
  58.     lines = inputFile.readlines()
  59.     numberOfLines = len(lines)
  60.  
  61.     for i in range(numberOfLines):
  62.         #   Strip trailing newline character
  63.         lines[i] = lines[i][:-1]
  64.     return lines
  65.  
  66.  
  67.  
  68. if __name__ == '__main__':
  69.     main()

Raw Paste


Login or Register to edit or fork this paste. It's free.