Skip to content

Commit 216ff65

Browse files
committed
Add training code samples
1 parent 479687f commit 216ff65

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

training/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Training
2+
3+
Traning code examples.
4+
It should not depend on external libraries.
5+
6+
* Python 3.7+ (but older versions should be fine)

training/game_of_life.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# -*- coding: utf-8 -*-
2+
# vi:si:et:sw=4:sts=4:ts=4
3+
4+
# https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
5+
6+
import random
7+
import time
8+
import sys
9+
10+
11+
def create_grid(n):
12+
grid = []
13+
for i in range(n):
14+
grid.append([bool(random.randint(0, 1)) for col in range(n)])
15+
16+
return grid
17+
18+
19+
def display(grid, generation):
20+
# clear screen
21+
print(chr(27) + "[2J")
22+
23+
state = ""
24+
for row in grid:
25+
for value in row:
26+
state += "⬛️" if value else "⬜️"
27+
28+
state += "\n"
29+
30+
state += "\nGeneration: {}".format(generation)
31+
print(state)
32+
33+
34+
def count_alive_neighbours(grid, row, column):
35+
order = len(grid)
36+
count = 0
37+
for x in (row - 1, row, row + 1):
38+
for y in (column - 1, column, column + 1):
39+
if x == row and y == column:
40+
continue
41+
42+
if x >= 0 and x < order and y >= 0 and y < order:
43+
count += 1 if grid[x][y] else 0
44+
45+
return count
46+
47+
48+
def calculate_next_generation(grid):
49+
next_gen_states = []
50+
for i, row in enumerate(grid):
51+
for j, value in enumerate(row):
52+
alive = count_alive_neighbours(grid, i, j)
53+
if value:
54+
if alive < 2 or alive > 3:
55+
next_gen_states.append((i, j, False))
56+
else:
57+
if alive == 3:
58+
next_gen_states.append((i, j, True))
59+
60+
return next_gen_states
61+
62+
63+
def create_generations(grid_size, generations, interval=0.2):
64+
grid = create_grid(grid_size)
65+
for i in range(generations):
66+
next_generation_states = calculate_next_generation(grid)
67+
68+
if not next_generation_states:
69+
break
70+
71+
for row, col, value in next_generation_states:
72+
grid[row][col] = value
73+
74+
display(grid, i)
75+
time.sleep(interval)
76+
77+
78+
if __name__ == "__main__":
79+
try:
80+
create_generations(grid_size=20, generations=1000)
81+
except KeyboardInterrupt:
82+
print("\nbye!")
83+
sys.exit(1)
84+
else:
85+
sys.exit(0)

0 commit comments

Comments
 (0)