Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- from collections import Counter
- from copy import deepcopy
- EMPTY_CELL = ' '
- ALIVE_CELL = 'O'
- def get_cell(field, y, x):
- return field[y % len(field)][x % len(field[y % len(field)])]
- def count_neighbors(field, coords):
- y, x = coords
- return Counter([get_cell(field, j, i) == ALIVE_CELL
- for j in range(y - 1, y + 2)
- for i in range(x - 1, x + 2)
- if i != x or j != y])[True]
- def create_new_field(field_width, field_height):
- return [[EMPTY_CELL for x in range(field_width)]
- for y in range(field_height)]
- return field
- def create_random_field(field_width, field_height):
- random_field = create_new_field(field_width, field_height)
- for y in range(field_height):
- for x in range(field_width):
- random_field[y][x] = random.choice([ALIVE_CELL, EMPTY_CELL])
- return random_field
- def field2str(arr):
- return '\n'.join(' '.join(line) for line in arr)
- def update_cell(field, coords):
- if count_neighbors(field, coords) == 3:
- return 'O'
- elif (count_neighbors(field, coords) < 2
- or count_neighbors(field, coords) > 3):
- return ' '
- elif count_neighbors(field, coords) == 2:
- return field[coords[0]][coords[1]]
- def generate_new_generation(field):
- new_generation = deepcopy(field)
- for y in range(len(field)):
- for x in range(len(field[y])):
- new_generation[y][x] = update_cell(field, (y, x))
- return new_generation
- def game_of_life():
- field = create_random_field(66, 35)
- while True:
- print(field2str(field))
- field = generate_new_generation(field)
- def main():
- game_of_life()
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement