Microsoft Small Basic

Program Listing: XMC184
' 1-D Cellular Automaton
' Version 0.0.1
' Copyright © 2020 Nonki Takahashi. The MIT License.

title = "1-D Cellular Automaton"
random = "False"
wait = 500 ' ms
GraphicsWindow.Title = title
cellSize = 4
cols = 100
rows = 100
Init()
rule = -1
While "True"
If random Then
rule = Math.GetRandomNumber(256) - 1
Else
rule = rule + 1
If 255 < rule Then
rule = 0
EndIf
EndIf
GraphicsWindow.Title = title + " | rule = " + rule
Clear()
Gen0()
DrawCells()
For row = 1 To rows - 1
CalcNextCells()
cell = next
DrawCells()
EndFor
Program.Delay(wait)
EndWhile

Sub CalcNextCells
' param cell[] - current generation
' param row - for next generation
' return next[] - next generation
next = ""
For col = 0 To cols - 1
c3 = 0
If cell[col - 1] Then
c3 = c3 + 4
EndIf
If cell[col] Then
c3 = c3 + 2
EndIf
If cell[col + 1] Then
c3 = c3 + 1
EndIf
If ruleset[rule][c3] = 1 Then
next[col] = "True"
EndIf
EndFor
EndSub

Sub Clear
GraphicsWindow.BrushColor = "White"
GraphicsWindow.FillRectangle(0, 0, gw, gh)
EndSub

Sub DrawCells
' param row - generation to draw (0 origin)
' param cell[] - current generation
index = Array.GetAllIndices(cell)
n = Array.GetItemCount(cell)
GraphicsWindow.BrushColor = "Black"
For i = 1 To n
col = index[i]
x = col * cellSize
y = row * cellSize
GraphicsWindow.FillRectangle(x, y, cellSize, cellSize)
EndFor
EndSub

Sub DrawGrid
' param gw, gh - window size [px]
' param cellSize - cell size [px]
GraphicsWindow.PenWidth = 0
GraphicsWindow.BrushColor = "LightGray"
For x = 0 To gw Step cellSize
line = Shapes.AddRectangle(1, gh)
Shapes.Move(line, x 0)
EndFor
For y = 0 To gh Step cellSize
line = Shapes.AddRectangle(gw, 1)
Shapes.Move(line, 0, y)
EndFor
EndSub

Sub Init
gw = cols * cellSize
gh = rows * cellSize
GraphicsWindow.Width = gw
GraphicsWindow.Height = gh
DrawGrid()
' initialize ruleset
For i = 0 To 255
n = i
p = ""
For d = 7 To 0 Step -1
p[d] = Math.Remainder(n, 2)
n = Math.Floor(n / 2)
EndFor
ruleset[i] = p
EndFor
EndSub

Sub Gen0
' initialize generation 0 for top line
row = 0
cell = ""
If random Then
For col = 0 To cols - 1
If Math.GetRandomNumber(2) - 1 = 1 Then
cell[col] = "True"
EndIf
EndFor
Else
col = Math.Round(cols / 2)
cell[col] = "True"
EndIf
EndSub