Two guys meet
If two guys meet, there is standard verbiage, but some uncertainty in how long they need to greet and respond. We can simulate this as an introductory example.
We call the needed modules and define some types and data:
using Simulate, Printf
struct Guy
name
end
abstract type Encounter end
struct Meet <: Encounter
someone
end
struct Greet <: Encounter
num
from
end
struct Response <: Encounter
num
from
end
comm = ("Nice to meet you!", "How are you?", "Have a nice day!", "bye bye")
We implement the behavior of the "guys" as step!
-functions of a state machine.
say(name, n) = @printf("%5.2f s, %s: %s\n", tau(), name, comm[n])
function step!(me::Guy, ฯ::Meet)
event!(๐ถ, SF(step!, ฯ.someone, Greet(1, me)), after, 2*rand())
say(me.name, 1)
end
function step!(me::Guy, ฯ::Greet)
if ฯ.num < 3
event!(๐ถ, SF(step!, ฯ.from, Response(ฯ.num, me)), after, 2*rand())
say(me.name, ฯ.num)
else
say(me.name, 4)
end
end
function step!(me::Guy, ฯ::Response)
event!(๐ถ, SF(step!, ฯ.from, Greet(ฯ.num+1, me)), after, 2*rand())
say(me.name, ฯ.num+1)
end
Then we define some "guys" and a starting event and tell the clock ๐ถ
to run
for twenty "seconds":
foo = Guy("Foo")
bar = Guy("Bar")
event!(๐ถ, SF(step!, foo, Meet(bar)), at, 10*rand())
run!(๐ถ, 20)
If we source this code, it will run a simulation:
julia> include("docs/examples/greeting.jl")
7.30 s, Foo: Nice to meet you!
8.00 s, Bar: Nice to meet you!
9.15 s, Foo: How are you?
10.31 s, Bar: How are you?
11.55 s, Foo: Have a nice day!
12.79 s, Bar: bye bye
Finished: 6 events, simulation time: 20.0
Then we reset
the clock ๐ถ
for further simulations.
julia> reset!(๐ถ)
clock reset to tโ=0, sampling rate ฮt=0.