Advertisement
Guest User

Untitled

a guest
Feb 25th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. """
  2. Game of Life in python.
  3. Handles worlds as 2x2 lists.
  4. Starts with a 128x64 randomly generated world.
  5. """
  6.  
  7. from random import random
  8. from time import sleep
  9.  
  10. # Returns the next iteration of a given world.
  11. def next_world(world):
  12. # Returns a cell's next value given
  13. # its state and its surroundings.
  14. def next_cell(surr, cell):
  15. return (surr == 3 or (cell and surr == 2))
  16. height = len(world)
  17. width = len(world[0])
  18. new_world = [[0]*width for i in range(height)]
  19.  
  20. for m in range(height):
  21. for n in range(width):
  22. # p_m, etc. are defined for wraparound purposes.
  23. p_m = (m-1) % height
  24. n_m = (m+1) % height
  25. p_n = (n-1) % width
  26. n_n = (n+1) % width # ^_^
  27. # print('m,n', m, n)
  28. # print('p_m', p_m)
  29. # print('n_m', n_m)
  30. # print('p_n', p_n)
  31. # print('n_n', n_n)
  32. surr = (world[p_m][p_n]
  33. +world[p_m][n]
  34. +world[p_m][n_n]
  35. +world[m][p_n]
  36. +world[m][n_n]
  37. +world[n_m][p_n]
  38. +world[n_m][n]
  39. +world[n_m][n_n]
  40. )
  41. cell = world[m][n]
  42. new_world[m][n] = next_cell(surr, cell)
  43.  
  44. return new_world
  45.  
  46. # Outputs a given world to the console.
  47. def out(world):
  48. height = len(world)
  49. width = len(world[0])
  50. new_world = ' ' + '-'*width
  51. for i in range(height):
  52. # Convert each boolean in the row to a character.
  53. str_row = ('\n|'
  54. +''.join([('\u2588' if val else ' ') for val in world[i]])
  55. +'|'
  56. )
  57. new_world += str_row
  58.  
  59. new_world += '\n ' + '-'*width
  60. print(new_world)
  61. # sleep(amount)
  62.  
  63. def worldgen(height,width):
  64. world = [[0]*width for i in range(height)]
  65. for m in range(height):
  66. for n in range(width):
  67. world[m][n] = random() < 0.5
  68.  
  69. return world
  70.  
  71.  
  72. # world = [[False]*9
  73. # ,[False]*4 + [True] + [False]*4
  74. # ,[False]*4 + [True] + [False]*4
  75. # ,[False]*4 + [True] + [False]*4
  76. # ,[False]*9]
  77.  
  78. world = worldgen(64,128)
  79.  
  80. out(world)
  81. while(True):
  82. world = next_world(world)
  83. out(world)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement