Thank you for our answers! Refactored code:
import random
import time
import os
from collections import Counter
class LifeGame:
def __init__(self):
self.width = 60
self.height = 10
self.death_level = 0 # more - worse
self.birth_level = 10 # less - better
self.start_spawn = 1 # how many lifes will be spawn on start
self.matrix = []
self.iteration = 0
row_counter = 0
for y in range(self.height):
self.matrix.append([])
for x in range(self.width):
self.matrix[row_counter].append(" ")
row_counter += 1
def print(self):
life_cells = 0
empty_cells = 0
print("---" * self.width)
for row in self.matrix:
print(f"| {' '.join(row)} |")
print("---" * self.width)
cnt = Counter()
for row in self.matrix:
cnt.update(row)
life_cells = cnt['*']
empty_cells = cnt[' ']
if empty_cells != 0:
print(round((life_cells/100), 2)*(100/((self.width*self.height)/100)), "% of life")
else:
print("100 % of life")
print(lg.iteration)
def spawn_life(self):
rand_coords = []
counter = 0
for i in range(lg.start_spawn):
rand_coords.append([])
rand_coords[counter].append(random.randint(0, self.width-1))
rand_coords[counter].append(random.randint(0, self.height-1))
counter += 1
for i in range(len(rand_coords)):
self.matrix[rand_coords[i][1]][rand_coords[i][0]] = "*"
return rand_coords
def get_available_coords(self, x, y):
available_coords = [[x-1, y], [x+1, y], [x, y+1], [x, y-1]]
coords = []
for i in range(len(available_coords)):
if available_coords[i][0] <= self.width-1 and available_coords[i][0] >= 0\
and available_coords[i][1] <= self.height-1 and available_coords[i][1] >= 0\
and self.matrix[available_coords[i][1]][available_coords[i][0]] == " ":
coords.append([available_coords[i][0], available_coords[i][1]])
return coords
def add_life_to_matrix(self, coords):
coords = sum(coords, [])
for x, y in coords:
chance = random.randint(0, lg.birth_level)
if chance == 1:
self.matrix[y][x] = '*'
def del_life(self):
for i in range(lg.death_level):
del_x = random.randint(0, lg.width-1)
del_y = random.randint(0, lg.height-1)
self.matrix[del_y][del_x] = " "
lg = LifeGame()
lg.spawn_life()
while True:
coords = []
for y in range(lg.height):
for x in range(lg.width):
if lg.matrix[y][x] == "*":
coords.append(lg.get_available_coords(x, y))
lg.del_life()
lg.add_life_to_matrix(coords)
lg.iteration += 1
lg.print()
time.sleep(0.01)
os.system('cls')