Microsoft Small Basic

Program Listing: FHC281
' Traffic Jam Simulator with Cellular-Automaton
' Version 0.1
' Copyright © 2018 Nonki Takahashi. The MIT License.
'
title = "Traffic Jam Simulator 0.1"
GraphicsWindow.Title = title + " | t = 0"
Not = "True=False;False=True;"
color = "1=Blue;2=Black;3=Gray;4=YellowGreen;5=Violet;"
size = 18
delay = 100
gw = 598
gh = 428
GraphicsWindow.Width = gw
GraphicsWindow.Height = gh
x0 = 30
y0 = gh - 20
x1 = gw - 50
y1 = 40 + size * 2.5
GraphicsWindow.PenWidth = 2
GraphicsWindow.PenColor = "Gray"
GraphicsWindow.BrushColor = "Gray"
GraphicsWindow.DrawText(x0 - 22, y1 - 20, "Flow")
GraphicsWindow.DrawText(x1, y0, "Dencity")
For dencity = 0 To 1 Step 0.1
Convert()
GraphicsWindow.DrawLine(x, y0, x, y1)
GraphicsWindow.DrawText(x - 22, y0, dencity)
EndFor
For flow = 0 To 1 Step 0.1
Convert()
GraphicsWindow.DrawLine(x0, y, x1, y)
GraphicsWindow.DrawText(x0 - 22, y, flow)
EndFor
Init()
GraphicsWindow.BrushColor = "Black"
btn = Controls.AddButton("Start", 10, 10)
Controls.ButtonClicked = OnButtonClicked
While "True"
If buttonClicked Then
While Not[empty]
t = t + 1
GraphicsWindow.Title = title + " | t = " + t
Move()
Draw()
Program.Delay(delay)
EndWhile
dencity = nCar / n
flow = nCar / t
Plot()
Init()
'buttonClicked = "False"
Else
Program.Delay(delay)
EndIf
EndWhile

Sub Convert
x = x0 + dencity * (x1 - x0)
y = y0 + flow * (y1 - y0)
EndSub

Sub Draw
If t = 0 Then
x = 10
y = 40
GraphicsWindow.PenColor = "Black"
GraphicsWindow.PenWidth = 2
For d = 1 To n
GraphicsWindow.DrawRectangle(x, y, size, size)
x = x + size
EndFor
EndIf
x = 10
For d = 1 To n
GraphicsWindow.BrushColor = "White"
GraphicsWindow.FillRectangle(x + 1, y + 1, size - 2, size - 2)
If road[d] <> "" Then
GraphicsWindow.BrushColor = color[car[road[d]]]
s = (size - 4) / 4
GraphicsWindow.FillRectangle(x + 2, y + 2, size - 4, size - 4)
GraphicsWindow.BrushColor = "Yellow"
GraphicsWindow.FillEllipse(x + size - 2 - s, y + 2, s, s)
GraphicsWindow.FillEllipse(x + size - 2 - s, y + size - 2 - s, s, s)
If break[d] Then
GraphicsWindow.BrushColor = "Red"
Else
GraphicsWindow.BrushColor = "Black"
EndIf
GraphicsWindow.FillEllipse(x + 2, y + 2, s, s)
GraphicsWindow.FillEllipse(x + 2, y + size - 2 - s, s, s)
EndIf
x = x + size
EndFor
EndSub

Sub Init
t = 0
road = ""
n = 30
nCar = 0
empty = "True"
For d = 1 To n
If Math.GetRandomNumber(2) = 1 Then
empty = "False"
nCar = nCar + 1
car[nCar] = Math.GetRandomNumber(Array.GetItemCount(color))
road[d] = nCar
break[d] = "True"
EndIf
EndFor
Draw()
EndSub

Sub Move
temp = ""
break = ""
empty = "True"
For d = 1 To n - 1
If road[d] <> "" Then
empty = "False"
If road[d + 1] <> "" Then
temp[d] = road[d]
break[d] = "True"
Else
temp[d + 1] = road[d]
EndIf
EndIf
EndFor
road = temp
EndSub

Sub OnButtonClicked
buttonClicked = "True"
EndSub

Sub Plot
' param dencity
' param flow
Convert()
GraphicsWindow.BrushColor = "Red"
GraphicsWindow.FillEllipse(x - 2, y - 2, 4, 4)
EndSub