# Patrick Coleman # Comp Sys Res - 6th period - 2007-08 # Sugarscape - simulation require 'environment.rb' require 'agent.rb' require 'display.rb' require 'tk' #False while the window is running $q = false #True while the simulation is running $p = true #Time step $step = 0 #A copy of the environment $env #An array storing the population size at various time steps $population=Array.new #Number of time steps which the population array stores $popLength = 5000 #The largest number of agents which has been reached $maxPop = 0 #Carrying capacity of the environment $K = 1500 #Array of the different sugar quantities of agents in one time step $wealths = [0] #The total amount of sugar posessed by the entire population $totalW = 0 #increments the time step def runSim #Resets variables every time step $wealths = [0] $totalW = 0 #Cycles through array of agents $env.agents.each do |a| if a.dead #Deletes the agent from the array if it has died $env.agents.delete(a) else #Adds data to wealth variables w = a.wealth $totalW += w if w > 0 $wealths << w if w > 0 #Calls the act method of each agent a.act end end #Sorts the wealth array $wealths.sort! #Keeps population at a minimum of one $env.addAgent if $env.agents.length < 1 =begin #Adds agents to environment according to a logistic function dPdt = $env.agents.length*1.0*(1.0-$env.agents.length/$K) 10.times {$env.addAgent if rand($K/4.0) < dPdt} =end 13.times {$env.addAgent if rand($K) < $env.agents.length} #Appends current population size to the population array $population<<$env.agents.length $maxPop = $env.agents.length if $env.agents.length > $maxPop $population.shift if $population.length > $popLength #Increments the time step $step += 1 end #Plays or pauses the simulation depending on the state #and refreshes the play/pause button def play $p = !$p if $p $pBtn.configure(:text=>"Pause",'underline'=>0) else $pBtn.configure(:text=>" Play ",'underline'=>1) end end #Returns true if simulation is running def play? $p end #Runs the simulation, updates the display, and then pauses the simulation def step #Sets the refresh rate to one so the display is updated temp = $refresh $refresh = 1 #Runs simulation runSim #Updates the display updateDisp #Pauses simulation and updates play/pause button $p = false $pBtn.configure(:text=>" Play ",'underline'=>1) #Resets the refresh rate $refresh = temp end #Returns time step def getStep $step end #Sets quit variable to true def quit $q = true end #Returns true if the program has been quit def quit? $q end #Returns the array of population sizes def getPop $population end #Returns the maximum time steps which can be stored for population sizes def popLength $popLength end #Returns the largest population size which has been reached def maxPop $maxPop end #Returns the array of wealths def getWealths $wealths end #Returns the total wealth def getTotalW $totalW end