Elevator Simulator Revisited

I have suggested before that writing and debugging a little simulator offers considerable insight into how computer programs give meaning to calculations. After sketching a few methods at the whiteboard recently, I completed the code to discover a small version took 100 lines. wiki

Here elevator E takes person P to work W.

Recorded Jun 27, 2017

My code has considerable limitations.

My whiteboard version passed a hash of parameters through the queue with each event. This avoids state in globals so that there could be many elevators and riders.

I chose to busy-wait for passengers to get on and off the elevator. More intertwined logic could save cycles and expose interesting collaborations.

# http://wiki.c2.com/?LittleSimulator # usage: ruby sim.rb # S I M U L A T O R @clock = 0 @queue = [] def advance @event = @queue.shift @clock = @event[:time] send @event[:action] end def delay sec, action @queue << {time: @clock+sec, action: action} @queue = @queue.sort_by {|event| event[:time]} end # E L E V A T O R @floor = 1 @going = +1 delay 1, 'move' def move @floor += @going if (1..30).include? @floor+@going delay 2, 'move' else @going = -@going delay 5, 'move' end end # P A S S E N G E R @at = 2 @want = 5 delay 1, 'wait' def going @want <=> @at end def wait if @floor == @at and going == @going delay 1, 'ride' else delay 1, 'wait' end end def ride @at = @floor if @at == @want delay 60, 'work' else delay 1, 'ride' end end def work @want = 1+rand(30) if @at == @want delay 60, 'work' else delay 1, 'wait' end end # A N I M A T I O N delay 0, 'frame' def frame puts @clear ||= `clear` draw 'E', @floor draw 'P', @at draw "W", @want puts @clock delay 1, 'frame' sleep 0.1 end def draw ch, pos puts "#{' '*pos}#{ch}" end # M A I N while @clock < 1000.0 advance end

I had the simulator running for a few dozen cycles before I thought to add the character-based animation. I added the rider's going-logic after I saw the P board the E going the wrong way. It was chance that ruby's <=> operator answered the same numeric code as the elevator.

I was wishing I had the rather exotic animation system I built in Smalltalk many years ago. It was meant as a backend to simulators or other data feeds.

I have delighted myself coding this application in the strangely continuous rule systems of Cocoa Worlds.