Add list of commands

This commit is contained in:
Anton Vakhrushev 2019-10-06 18:45:42 +03:00
parent 3669e31c66
commit 21b0f7733b
2 changed files with 38 additions and 10 deletions

View File

@ -1,19 +1,40 @@
class CLI::CommandRouter class CLI::CommandRouter
def initialize alias RouteHandler = Proc(Hash(String, String), Nil)
@mappings = [] of {Regex, Proc(Hash(String, String), Nil)}
struct Route
def initialize(@route : String, @pattern : Regex, @desc : String, @handler : RouteHandler)
end
getter route
getter pattern
getter desc
getter handler
end end
def add(route, &block : Hash(String, String) -> Nil) def initialize
@routes = [] of Route
end
def add(route, &block : RouteHandler)
pattern = route_to_regex(route) pattern = route_to_regex(route)
@mappings.push({pattern, block}) @routes.push(Route.new(route, pattern, "", block))
end
def add(route, desc, &block : RouteHandler)
pattern = route_to_regex(route)
@routes.push(Route.new(route, pattern, desc, block))
end end
def handle(command) def handle(command)
@mappings.each do |handler| @routes.each do |route|
handle_pattern(command, *handler) handle_pattern(command, route.pattern, route.handler)
end end
end end
def routes
@routes
end
private def handle_pattern(command, pattern, cb) private def handle_pattern(command, pattern, cb)
m = command.match(pattern) m = command.match(pattern)
return if m.nil? return if m.nil?

View File

@ -10,14 +10,21 @@ world = Game::World.new(ts)
router = CLI::CommandRouter.new router = CLI::CommandRouter.new
router.add "q" do |p| router.add "h", "Show all commands" do |p|
printf "Commands:\n"
router.routes.each do |r|
printf " %s - %s\n", r.route, r.desc
end
end
router.add "q", "Show command queue" do |p|
items = world.queue.top(5) items = world.queue.top(5)
items.each do |i| items.each do |i|
printf "%s, %s\n", Time.unix(i.ts).to_local.to_s, typeof(i.command) printf "%s, %s\n", Time.unix(i.ts).to_local.to_s, typeof(i.command)
end end
end end
router.add "harv {x} {y}" do |p| router.add "harv {x} {y}", "Build harvester at x,y" do |p|
x = p["x"].to_i32 x = p["x"].to_i32
y = p["y"].to_i32 y = p["y"].to_i32
point = Game::Point.new(x, y) point = Game::Point.new(x, y)
@ -25,14 +32,14 @@ router.add "harv {x} {y}" do |p|
printf "Build harvester at %d %d\n", x, y printf "Build harvester at %d %d\n", x, y
end end
router.add "rest {x} {y}" do |p| router.add "rest {x} {y}", "Build restorer at x,y" do |p|
x = p["x"].to_i32 x = p["x"].to_i32
y = p["y"].to_i32 y = p["y"].to_i32
point = Game::Point.new(x, y) point = Game::Point.new(x, y)
world.push(Game::BuildCrystalRestorerCommand.new(point)) world.push(Game::BuildCrystalRestorerCommand.new(point))
end end
router.add "terr {x} {y}" do |p| router.add "terr {x} {y}", "Build terraformator at x,y" do |p|
x = p["x"].to_i32 x = p["x"].to_i32
y = p["y"].to_i32 y = p["y"].to_i32
point = Game::Point.new(x, y) point = Game::Point.new(x, y)