each new index.html request now initiates a new game instance

This commit is contained in:
Richard Harrington 2013-08-20 13:25:51 -04:00
parent d7d27ca9f0
commit e02dd126c0
2 changed files with 37 additions and 21 deletions

View File

@ -23,10 +23,11 @@
// when the queue is running low.
var queue = new Queue();
var gameId;
var isFetching = false;
function fetch(callback) {
$.getJSON('worlds/' + bufferLength, function(data) {
$.getJSON('worlds/' + gameId + '/' + bufferLength, function(data) {
queue.enqueueArray(data);
if (callback) callback();
});
@ -41,7 +42,11 @@
}
}
fetch(constructorCallback);
$.getJSON('init', function(data) {
gameId = data['id'];
fetch(constructorCallback);
});
return {
dropMulti: dropMulti,
enqueueArray: queue.enqueueArray.bind(queue),

View File

@ -8,33 +8,44 @@
[robotwar.world :as world]
[robotwar.browser :as browser]))
(defn take-drop-send
"takes a collection agent and a number n,
returns a collection of the first n items and
drops those items from the agent's state.
TODO: find a built-in way to do this.
There must be one."
[a n]
(let [coll @a]
(send a (constantly (drop n coll)))
(take n coll)))
; TODO: have this source-code-picking be done in requests from the UI
; in the browser, not hard-coded here.
(def progs
(repeat 3 (:moving-to-spot source-programs/programs)))
(def world
(world/init-world progs))
(defn combined-worlds []
(world/build-combined-worlds world))
(def worlds (agent (browser/worlds-for-browser (combined-worlds))))
(defn add-game
"a function to update the games store agent state.
It keeps a running store of games, which is added
to upon request from a browser, who is then
assigned an id number"
[{:keys [next-id games]}]
{:next-id (inc next-id)
:games (merge games {next-id (-> progs
(world/init-world)
(world/build-combined-worlds)
(browser/worlds-for-browser))})})
(defn take-drop-send
"takes the games store agent, a game id, and a number n,
and returns a collection of the first n items from that game,
then drops those items from the game in the agent's state."
[a id n]
(let [coll (get-in @a [:games id])]
(send a #(assoc-in % [:games id] (drop n coll)))
(take n coll)))
(def games-agent (agent {:next-id 0
:games {}}))
(defroutes app-routes
(GET "/programs" [] (response/response source-programs/programs))
(GET "/worlds/:n" [n] (response/response
(take-drop-send worlds (Integer/parseInt n))))
(GET "/init" [] (let [next-id (:next-id @games-agent)]
(send games-agent add-game)
(response/response {:id next-id})))
(GET "/worlds/:id/:n" [id n] (response/response (take-drop-send
games-agent
(Integer/parseInt id)
(Integer/parseInt n))))
(route/files "/")
(route/not-found "Not Found"))