OMWebBook
Evaluate Cell
Eval All
Game of Life
1 Introduction
function firstGeneration input Integer M[:,:]; input Integer I[:,2]; output Integer G[size(M,1), size(M,1)] = M; algorithm for i in 1:size(I,1) loop G[I[i,1], I[i,2]] := 1; end for; end firstGeneration;
function nextGeneration input Integer M[:,:]; output Integer G[size(M,1), size(M,1)]; protected Integer iW, iE, jN, jS, borderSum; parameter Integer n = size(M,1); algorithm for i in 1:n loop for j in 1:n loop iW := mod(i-2+n, n) + 1; iE := mod(i+n, n) + 1; jN := mod(j+n, n) + 1; jS := mod(j-2+n, n) + 1; borderSum := M[iW,j] + M[iE,j] + M[iW,jS] + M[i,jS] + M[iE,jS] + M[iW,jN] + M[i,jN] + M[iE,jN]; if borderSum == 3 then G[i,j] := 1; elseif borderSum == 2 then G[i,j] := M[i,j]; else G[i,j] := 0; end if; end for; end for; end nextGeneration;
2 Game of Life
model GameOfLife parameter Integer n = 10; parameter Integer initialAlive[:,2] = {{2,2},{2,1},{1,2},{3,3},{3,2}}; discrete Integer lifeHistory[n,n](start=zeros(n,n)); Boolean init = initial(); equation when {init, sample(0.1,0.1)} then if edge(init) then lifeHistory = firstGeneration(pre(lifeHistory), initialAlive); else lifeHistory = nextGeneration(pre(lifeHistory)); end if; end when; end GameOfLife;
2.1 Animation of GameOfLife (to be done)
2.2 Simulation of GameOfLife
simulate( GameOfLife )
plot(lifeHistory[1,1])
2.3 Test of GameOfLife
model test1 GameOfLife g(initialAlive = {{1,1},{2,2},{3,3},{4,4},{5,5},{6,6},{7,7},{8,8},{9,9},{10,10}, {1,10},{2,9},{3,8},{4,7},{5,6},{6,5},{7,4},{8,3},{9,2},{10,1}}); end test1;
2.4 Simulation of test1
simulate( test1 )
plot({g.lifeHistory[1,1],g.initialAlive[5,1]})