Separate command queue
This commit is contained in:
parent
09ec46dd82
commit
5acf1694ee
15
src/queue.cr
15
src/queue.cr
@ -1,10 +1,25 @@
|
|||||||
class App::CommandQueue
|
class App::CommandQueue
|
||||||
def initialize
|
def initialize
|
||||||
|
@data = [] of {Int32, Command}
|
||||||
end
|
end
|
||||||
|
|
||||||
def push(ts : Int32, cmd : Command)
|
def push(ts : Int32, cmd : Command)
|
||||||
|
@data.push({ts, cmd})
|
||||||
|
@data.sort! do |x|
|
||||||
|
-x[0]
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def pop(ts : Int32) : Command | Nil
|
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
|
||||||
end
|
end
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
|
require "./queue"
|
||||||
|
|
||||||
class Resources
|
class Resources
|
||||||
def initialize
|
def initialize
|
||||||
@wood = 0
|
@wood = 0
|
||||||
@ -146,7 +148,7 @@ class World
|
|||||||
def initialize
|
def initialize
|
||||||
@resources = Resources.new
|
@resources = Resources.new
|
||||||
@map = Map.new
|
@map = Map.new
|
||||||
@queue = Array(Command).new
|
@queue = App::CommandQueue.new
|
||||||
end
|
end
|
||||||
|
|
||||||
def resources
|
def resources
|
||||||
@ -162,21 +164,18 @@ class World
|
|||||||
return false
|
return false
|
||||||
end
|
end
|
||||||
printf "push command %d\n", command.ts
|
printf "push command %d\n", command.ts
|
||||||
@queue.push(command)
|
@queue.push(command.ts, command)
|
||||||
@queue.sort! do |c|
|
|
||||||
-c.ts
|
|
||||||
end
|
|
||||||
true
|
true
|
||||||
end
|
end
|
||||||
|
|
||||||
def run(ts : Int32)
|
def run(ts : Int32)
|
||||||
while @queue.size != 0
|
loop do
|
||||||
c = @queue.pop
|
cmd = @queue.pop(ts)
|
||||||
printf "pop command %d\n", c.ts
|
if cmd.nil?
|
||||||
if c.ts > ts
|
|
||||||
break
|
break
|
||||||
end
|
end
|
||||||
c.run(self)
|
printf "pop command %d\n", cmd.ts
|
||||||
|
cmd.run(self)
|
||||||
end
|
end
|
||||||
printf "Wood: %d\n", @resources.wood
|
printf "Wood: %d\n", @resources.wood
|
||||||
end
|
end
|
||||||
@ -186,4 +185,4 @@ w = World.new
|
|||||||
w.map.print
|
w.map.print
|
||||||
w.push(BuildMillCommand.new(0))
|
w.push(BuildMillCommand.new(0))
|
||||||
w.push(BuildForesterHouseCommand.new(0))
|
w.push(BuildForesterHouseCommand.new(0))
|
||||||
w.run(100)
|
w.run(20)
|
||||||
|
Loading…
Reference in New Issue
Block a user