Created
December 5, 2015 13:23
-
-
Save Jonarzz/66cc0875c67a86d4341f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import copy | |
import os | |
import random | |
N = 20 | |
M = 20 | |
ALIVE = '#' | |
DEAD = '.' | |
def cls(): | |
os.system('cls') | |
def print_matrix_with_cls(matrix): | |
cls() | |
for i, row in enumerate(matrix): | |
for j, cell in enumerate(row): | |
print(cell, end='') | |
print() | |
print() | |
def neighbors(matrix, row, col): | |
for i in row-1, row, row+1: | |
if i < 0 or i == len(matrix): | |
continue | |
for j in col-1, col, col+1: | |
if j < 0 or j == len(matrix[i]): | |
continue | |
if i == row and j == col: | |
continue | |
yield matrix[i][j] | |
def create_random_matrix(): | |
matrix = [] | |
for i in range(N): | |
matrix.append([]) | |
for _ in range(M): | |
if random.randint(0,1) == 0: | |
matrix[i].append(DEAD) | |
else: | |
matrix[i].append(ALIVE) | |
return matrix | |
matrix = create_random_matrix() | |
print_matrix_with_cls(matrix) | |
new_matrix = copy.deepcopy(matrix) | |
while True: | |
for i, row in enumerate(matrix): | |
for j, cell in enumerate(row): | |
num_of_neighbors = 0 | |
for neighbor in neighbors(matrix, i, j): | |
if neighbor == ALIVE: | |
num_of_neighbors += 1 | |
if cell == DEAD: | |
if num_of_neighbors == 3: | |
new_matrix[i][j] = ALIVE | |
else: | |
if num_of_neighbors != 2 and num_of_neighbors != 3: | |
new_matrix[i][j] = DEAD | |
matrix = copy.deepcopy(new_matrix) | |
print_matrix_with_cls(matrix) | |
time.sleep(0.1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment