-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame_of_life.py
71 lines (53 loc) · 2.08 KB
/
game_of_life.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import copy
import random
from threading import Lock
from copy import deepcopy
from typing import List
class SingletonMeta(type):
_instances = {}
_lock: Lock = Lock()
def __call__(cls, *args, **kwargs):
with cls._lock:
if cls not in cls._instances or args or kwargs:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
class GameOfLife(metaclass=SingletonMeta):
world: list[list[int]]
def counter(self):
self.count += 1
def __init__(self, width=20, height=20, count=0):
self.count = count
self.__width = width
self.__height = height
self.world = self.generate_universe()
self.old_world = self.world
def form_new_generation(self):
self.counter()
universe = self.world
new_world = [[0 for _ in range(self.__width)] for _ in range(self.__height)]
self.old_world = copy.deepcopy(self.world)
for i in range(len(universe)):
for j in range(len(universe[0])):
if universe[i][j]:
if self.__get_near(universe, [i, j]) not in (2, 3):
new_world[i][j] = 0
continue
new_world[i][j] = 1
continue
if self.__get_near(universe, [i, j]) == 3:
new_world[i][j] = 1
continue
new_world[i][j] = 0
self.world = new_world
def generate_universe(self):
return [[random.randint(0, 1) for _ in range(self.__width)] for _ in range(self.__height)]
@staticmethod
def __get_near(universe, pos, system=None):
if system is None:
system = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1))
count = 0
for i in system:
if universe[(pos[0] + i[0]) % len(universe)][(pos[1] + i[1]) % len(universe[0])]:
count += 1
return count