Conway's Game of Life in python console


SUBMITTED BY: Guest

DATE: Feb. 10, 2016, 12:20 p.m.

FORMAT: Python 3

SIZE: 2.7 kB

HITS: 1358

  1. import random
  2. import time
  3. class life:
  4. def __init__(self, born, alive, mwidth, mheight):
  5. self.born = born
  6. self.alive = alive
  7. self.mwidth = mwidth
  8. self.mheight = mheight
  9. self.field = []
  10. self.initfield()
  11. def initfield(self):
  12. self.field = []
  13. for i in range(self.mheight):
  14. self.field.append([])
  15. for j in range(self.mwidth):
  16. deadoralive = random.randint(0, 1)
  17. if deadoralive == 0:
  18. self.field[i].append(' ')
  19. else:
  20. self.field[i].append('#')
  21. def draw(self):
  22. for i in range(3):
  23. print()
  24. for row in self.field:
  25. print(''.join(row))
  26. def nextgen(self):
  27. tempfield = []
  28. for i in range(self.mheight):
  29. tempfield.append([])
  30. for j in range(self.mwidth):
  31. tempfield[i].append(' ')
  32. for i in range(1, self.mheight - 1):
  33. for j in range(1, self.mwidth - 1):
  34. neighbours = 0
  35. if self.field[i][j + 1] == '#':
  36. neighbours = neighbours + 1
  37. if self.field[i][j - 1] == '#':
  38. neighbours = neighbours + 1
  39. if self.field[i + 1][j + 1] == '#':
  40. neighbours = neighbours + 1
  41. if self.field[i + 1][j - 1] == '#':
  42. neighbours = neighbours + 1
  43. if self.field[i - 1][j + 1] == '#':
  44. neighbours = neighbours + 1
  45. if self.field[i - 1][j - 1] == '#':
  46. neighbours = neighbours + 1
  47. if self.field[i + 1][j] == '#':
  48. neighbours = neighbours + 1
  49. if self.field[i - 1][j] == '#':
  50. neighbours = neighbours + 1
  51. if neighbours in self.born:
  52. tempfield[i][j] = '#'
  53. elif neighbours not in self.alive:
  54. tempfield[i][j] = ' '
  55. else:
  56. tempfield[i][j] = self.field[i][j]
  57. for i in range(self.mheight):
  58. for j in range(self.mwidth):
  59. if tempfield[i][j] != self.field[i][j]:
  60. self.field = tempfield
  61. return
  62. self.initfield()
  63. def main():
  64. conway_life = life([3], [3, 2], 60, 30)
  65. while True:
  66. conway_life.draw()
  67. conway_life.nextgen()
  68. time.sleep(0.3)
  69. if __name__ == "__main__":
  70. main()

comments powered by Disqus