Separate command queue

This commit is contained in:
Anton Vakhrushev 2019-09-13 20:59:12 +03:00
parent 09ec46dd82
commit 5acf1694ee
2 changed files with 25 additions and 11 deletions

View File

@ -1,10 +1,25 @@
class App::CommandQueue
def initialize
@data = [] of {Int32, Command}
end
def push(ts : Int32, cmd : Command)
@data.push({ts, cmd})
@data.sort! do |x|
-x[0]
end
end
def pop(ts : Int32) : Command | Nil
if @data.size == 0
return nil
end
last_ts = @data[-1][0]
if last_ts <= ts
last_item = @data.pop
return last_item[1]
else
nil
end
end
end

View File

@ -1,3 +1,5 @@
require "./queue"
class Resources
def initialize
@wood = 0
@ -146,7 +148,7 @@ class World
def initialize
@resources = Resources.new
@map = Map.new
@queue = Array(Command).new
@queue = App::CommandQueue.new
end
def resources
@ -162,21 +164,18 @@ class World
return false
end
printf "push command %d\n", command.ts
@queue.push(command)
@queue.sort! do |c|
-c.ts
end
@queue.push(command.ts, command)
true
end
def run(ts : Int32)
while @queue.size != 0
c = @queue.pop
printf "pop command %d\n", c.ts
if c.ts > ts
loop do
cmd = @queue.pop(ts)
if cmd.nil?
break
end
c.run(self)
printf "pop command %d\n", cmd.ts
cmd.run(self)
end
printf "Wood: %d\n", @resources.wood
end
@ -186,4 +185,4 @@ w = World.new
w.map.print
w.push(BuildMillCommand.new(0))
w.push(BuildForesterHouseCommand.new(0))
w.run(100)
w.run(20)