Microsoft Small Basic

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

title = "1-D Cellular Automaton"
random = "False"
wait = 500 ' ms
cellSize = 4
cols = 100
rows = 100
yOffset = 34
Init()

Sub CA
Shapes.SetText(shTitle, title + " | rule = " + rule)
Clear()
Gen0()
DrawCells()
For row = 1 To rows - 1
CalcNextCells()
cell = next
DrawCells()
EndFor
EndSub

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, yOffset, gw, gh)
EndSub

Sub DrawCells
' param row - generation to draw (0 origin)
' param cell[] - current generation
GraphicsWindow.BrushColor = "Black"
For col = 0 To cols - 1
If rows - 1 < row Then
col = cols - 1 ' exit For to avoid over run
ElseIf cell[col] Then
x = col * cellSize
y = row * cellSize
GraphicsWindow.FillRectangle(x, y + yOffset, cellSize, cellSize)
EndIf
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, yOffset)
EndFor
For y = 0 To gh Step cellSize
line = Shapes.AddRectangle(gw, 1)
Shapes.Move(line, 0, y + yOffset)
EndFor
EndSub

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

Sub Init
gw = cols * cellSize
gh = rows * cellSize
GraphicsWindow.BrushColor = "Black"
GraphicsWindow.FontName = "Arial"
shTitle = Shapes.AddText(title)
Shapes.Move(shTitle, 10, 8)
GraphicsWindow.DrawText(250, 8, "rule")
tbox = Controls.AddTextBox(280, 4)
Controls.SetSize(tbox, 40, yOffset - 14)
Controls.SetTextBoxText(tbox, 0)
btn = Controls.AddButton("Draw", gw - 60, 2)
Controls.SetSize(btn, 50, yOffset - 4)
DrawGrid()
' initialize ruleset
For i = 0 To 255
n = i
p = ""
For d = 0 To 7
p[d] = Math.Remainder(n, 2)
n = Math.Floor(n / 2)
EndFor
ruleset[i] = p
EndFor
Controls.ButtonClicked = OnButtonClicked
EndSub

Sub OnButtonClicked
rule = Controls.GetTextBoxText(tbox)
_rule = rule + 1
If 255 < _rule Then
_rule = 0
EndIf
Controls.SetTextBoxText(tbox, _rule)
CA()
EndSub