1# Game of Life - Example for illustrative purposes only.
2# In honor of John Conway
3
4import smartpy as sp
5
6
7@sp.module
8def main():
9 def board(size):
10 b = {}
11 for i in range(0, size):
12 b[i] = {}
13 for j in range(0, size):
14 b[i][j] = 0
15 return b
16
17 class Game_of_life(sp.Contract):
18 def __init__(self, size):
19 self.private.size = size
20 self.private.zero = board(size)
21 self.data.board = {}
22
23 @sp.entrypoint
24 def reset(self):
25 self.data.board = self.private.zero
26
27 @sp.entrypoint
28 def glider(self):
29 self.data.board = self.private.zero
30 x = self.private.size / 3
31 self.data.board[x][x] = 1
32 self.data.board[x + 1][x + 1] = 1
33 self.data.board[x + 2][x - 1] = 1
34 self.data.board[x + 2][x] = 1
35 self.data.board[x + 2][x + 1] = 1
36
37 @sp.entrypoint
38 def bar(self):
39 self.data.board = self.private.zero
40 x = self.private.size / 2
41 for k in range(0, self.private.size):
42 self.data.board[x][k] = 1
43
44 @sp.entrypoint
45 def run(self):
46 next = self.private.zero
47 for i in range(0, self.private.size):
48 for j in range(0, self.private.size):
49 sum = 0
50 for k in range(-1, 2):
51 if 0 <= i + k and i + k < self.private.size:
52 for l in range(-1, 2):
53 if 0 <= j + l and j + l < self.private.size:
54 if k != 0 or l != 0:
55 sum += self.data.board[i + k][j + l]
56 if self.data.board[i][j] == 0:
57 if sum == 3:
58 next[i][j] = 1
59 else:
60 if 2 <= sum and sum <= 3:
61 next[i][j] = 1
62 self.data.board = next
63
64
65if "main" in __name__:
66
67 @sp.add_test()
68 def test():
69 scenario = sp.test_scenario("GameOfLife", main)
70 c1 = main.Game_of_life(10)
71 scenario.h1("Game of life")
72
73 scenario += c1
74
75 scenario.h2("Zero")
76 c1.reset()
77
78 scenario.h2("Glider")
79 c1.glider()
80 for i in range(0, 20):
81 c1.run()
82
83 scenario.h2("Horizontal Bar")
84 c1.bar()
85 for i in range(0, 18):
86 c1.run()