Add list of commands
This commit is contained in:
parent
3669e31c66
commit
21b0f7733b
@ -1,19 +1,40 @@
|
||||
class CLI::CommandRouter
|
||||
def initialize
|
||||
@mappings = [] of {Regex, Proc(Hash(String, String), Nil)}
|
||||
alias RouteHandler = 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
|
||||
|
||||
def add(route, &block : Hash(String, String) -> Nil)
|
||||
def initialize
|
||||
@routes = [] of Route
|
||||
end
|
||||
|
||||
def add(route, &block : RouteHandler)
|
||||
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
|
||||
|
||||
def handle(command)
|
||||
@mappings.each do |handler|
|
||||
handle_pattern(command, *handler)
|
||||
@routes.each do |route|
|
||||
handle_pattern(command, route.pattern, route.handler)
|
||||
end
|
||||
end
|
||||
|
||||
def routes
|
||||
@routes
|
||||
end
|
||||
|
||||
private def handle_pattern(command, pattern, cb)
|
||||
m = command.match(pattern)
|
||||
return if m.nil?
|
||||
|
@ -10,14 +10,21 @@ world = Game::World.new(ts)
|
||||
|
||||
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.each do |i|
|
||||
printf "%s, %s\n", Time.unix(i.ts).to_local.to_s, typeof(i.command)
|
||||
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
|
||||
y = p["y"].to_i32
|
||||
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
|
||||
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
|
||||
y = p["y"].to_i32
|
||||
point = Game::Point.new(x, y)
|
||||
world.push(Game::BuildCrystalRestorerCommand.new(point))
|
||||
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
|
||||
y = p["y"].to_i32
|
||||
point = Game::Point.new(x, y)
|
||||
|
Loading…
Reference in New Issue
Block a user