Declarative routing and data serialization for the embedded HTTP server
Adding a REST API to your game makes it possible for other programs to inspect and manipulate the current game state while the game is running.
Declare a route with
route "/string" # {...}to match an exact stringUse
route "/resource(/:id(.:format))" # {...}to match optional substrings and capture paramsYou can nest additional routes to namespace them within the parent scope:
route'/entities'doroute'/players'doroute'/:id'# '/entities/players/:id'endend
Call
action -> { ... }within a route to handle requests, returning a response.- If an action returns an Integer, it will be used as the http status code with an empty response
- If an action returns a String, it will be sent as HTML text
- Any other kind of object will be serialized to JSON
A simple API with a few different routes
classGame < Draco::WorldincludeDraco::APIroute'/foo'doroute'/success'{action->{200}}route'/error'{action->{500}}route'/string'{action->{"<strong>OK</strong>"}}route'/:id'doaction->doworld.entities[params.id.to_i].firstendendendendCheck the examples/ directory for a complete demo containing several more examples you can learn from.
If you don't already have a game project, run smaug new to create one.
$ smaug add draco
$ smaug add draco-api# app/main.rbrequire'smaug.rb'deftickargsargs.state.world ||= HelloWorld.newargs.state.world.tick(args)endNext, create a World and include Draco::API.
# app/worlds/hello_world.rbclassHelloWorld < Draco::WorldincludeDraco::APIroute'/hello'{action->{'Hello'}}endStart the game with smaug run, and navigate to http://localhost:9001/hello to see the result.
This package contains code originally derived from the following projects under the MIT license: