Advertisement
_eremec_

Untitled

Feb 15th, 2017
513
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1. import random
  2. from collections import Counter
  3. from copy import deepcopy
  4.  
  5.  
  6. EMPTY_CELL = ' '
  7. ALIVE_CELL = 'O'
  8.  
  9. def get_cell(field, y, x):
  10.     return field[y % len(field)][x % len(field[y % len(field)])]
  11.  
  12. def count_neighbors(field, coords):
  13.     y, x = coords      
  14.     return Counter([get_cell(field, j, i) == ALIVE_CELL
  15.                     for j in range(y - 1, y + 2)
  16.                     for i in range(x - 1, x + 2)
  17.                     if i != x or j != y])[True]
  18.  
  19. def create_new_field(field_width, field_height):  
  20.     return [[EMPTY_CELL for x in range(field_width)]
  21.              for y in range(field_height)]
  22.     return field
  23.  
  24. def create_random_field(field_width, field_height):  
  25.     random_field = create_new_field(field_width, field_height)
  26.     for y in range(field_height):
  27.         for x in range(field_width):
  28.             random_field[y][x] = random.choice([ALIVE_CELL, EMPTY_CELL])
  29.     return random_field
  30.  
  31. def field2str(arr):
  32.     return '\n'.join(' '.join(line) for line in arr)
  33.  
  34. def update_cell(field, coords):
  35.     if count_neighbors(field, coords) == 3:
  36.         return 'O'
  37.     elif (count_neighbors(field, coords) < 2
  38.           or count_neighbors(field, coords) > 3):
  39.         return ' '
  40.     elif count_neighbors(field, coords) == 2:
  41.         return field[coords[0]][coords[1]]
  42.  
  43. def generate_new_generation(field):
  44.     new_generation = deepcopy(field)
  45.     for y in range(len(field)):
  46.         for x in range(len(field[y])):
  47.             new_generation[y][x] = update_cell(field, (y, x))
  48.     return new_generation
  49.  
  50. def game_of_life():
  51.     field = create_random_field(66, 35)
  52.     while True:
  53.         print(field2str(field))
  54.         field = generate_new_generation(field)
  55.    
  56. def main():
  57.     game_of_life()  
  58.  
  59. if __name__ == '__main__':
  60.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement