peer-kit / src / ardegazu / peer / games / host / neon_grid_sim.cljs
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
;; ported-from: src/games/host/neon-grid-sim.ts @ v1.3.0
;;   (itself: game1/client/src/game/game.ts host block L246–395 + config.ts
;;   GW/GH/DX/DY/WIN_SCORE + state.ts H/HostBike @ 4c5def7)
;; divergences from the browser: DOM/render/audio removed; setInterval →
;;   chained `next {step:"tick"}` descriptors; roster reads / score mutations →
;;   injected callbacks; the round counter lives here (was G.round).
;;
;; The host sim itself has NO randomness — the spawn ring is deterministic
;; trigonometry, so a whole round replays from the inputs alone. Pinned by
;; test/vectors/neon-grid-sim.json (five traces, including the canonical
;; head-on draw at tick 36 and the WIN_SCORE match-end flip).
(ns ardegazu.peer.games.host.neon-grid-sim
  (:require [ardegazu.peer.obj :as obj]
            [ardegazu.peer.games.host.sim :as sim]
            [shadow.cljs.modern :refer (defclass)]))

(def GW 128)
(def GH 96)
(def WIN-SCORE 5)
;; 0=up 1=right 2=down 3=left
(def DX #js [0 1 0 -1])
(def DY #js [-1 0 1 0])
;; st → first tick (the client countdown), and the interstitial delays.
(def COUNTDOWN-MS 3000)
(def OVER-ROUND-MS 3200)
(def OVER-MATCH-MS 2200)
(def MATCH-LOBBY-MS 6000) ; browser: lo at 8200 = 2200 (ma) + 6000

;; A Bike is #js {id x y dir pend alive leftGame color nx ny dying} — 11 slots,
;; so sequential sets (the eight-pair js-obj rule; internal, but by policy).
(defn- new-bike [id x y dir color]
  (obj/ordered "id" id "x" x "y" y "dir" dir "pend" #js []
               "alive" true "leftGame" false "color" color
               "nx" x "ny" y "dying" false))

(defclass NeonGridSim
  (constructor [this opts]
    (unchecked-set this "_roster" (unchecked-get opts "roster"))
    (unchecked-set this "_addScore" (unchecked-get opts "addScore"))
    (unchecked-set this "_resetScores" (unchecked-get opts "resetScores"))
    (unchecked-set this "_round" 0)
    (unchecked-set this "_tickMs" 80)
    (unchecked-set this "_tickN" 0)
    (unchecked-set this "_grid" (js/Uint8Array. (* GW GH)))
    (unchecked-set this "_bikes" #js [])
    (unchecked-set this "_seatOf" (js/Map.))
    (unchecked-set this "_running" false)
    (unchecked-set this "_champId" nil)
    (unchecked-set this "_lastScores" #js [])))

(let [proto (.-prototype NeonGridSim)
      getter (fn [name slot]
               (js/Object.defineProperty
                proto name
                #js {:get (fn [] (this-as self (unchecked-get self slot)))
                     :configurable true}))]
  (getter "running" "_running")
  (getter "round" "_round")
  (getter "tickMs" "_tickMs")
  (getter "tickN" "_tickN")
  ;; The authoritative grid (values are colorIdx+1; 0 = free). Live copy.
  (getter "grid" "_grid"))

(defn new-match
  "Reset the round counter for a fresh match (ports hostStartMatch's part)."
  [self]
  (unchecked-set self "_round" 0)
  ((unchecked-get self "_resetScores"))
  js/undefined)

(defn start-round
  "Start a round with the connected riders (ports hostStartRound).
   riders = [#js {:id :color} …]"
  [self riders]
  (if (zero? (.-length ^js riders))
    sim/NO-EMIT
    (let [round (inc (unchecked-get self "_round"))]
      (unchecked-set self "_round" round)
      (unchecked-set self "_tickMs" (js/Math.max 45 (- 80 (* (- round 1) 4))))
      (unchecked-set self "_tickN" 0)
      ;; spawn ring, everyone facing the center
      (let [starts #js []
            n (.-length ^js riders)
            cx (/ GW 2)
            cy (/ GH 2)]
        (dotimes [i n]
          (let [a (- (* (/ i n) js/Math.PI 2) (/ js/Math.PI 2))
                x (js/Math.round (+ cx (* (js/Math.cos a) (- (/ GW 2) 14))))
                y (js/Math.round (+ cy (* (js/Math.sin a) (- (/ GH 2) 12))))
                dx (- cx x)
                dy (- cy y)
                dir (if (> (js/Math.abs dx) (js/Math.abs dy))
                      (if (> dx 0) 1 3)
                      (if (> dy 0) 2 0))]
            (.push starts #js [x y dir])))
        (.fill ^js (unchecked-get self "_grid") 0)
        (unchecked-set self "_bikes" #js [])
        (unchecked-set self "_seatOf" (js/Map.))
        (let [grid (unchecked-get self "_grid")
              bikes (unchecked-get self "_bikes")
              seat-of (unchecked-get self "_seatOf")]
          (.forEach ^js riders
                    (fn [r i]
                      (let [s (aget starts i)
                            x (aget s 0) y (aget s 1) dir (aget s 2)
                            id (unchecked-get r "id")
                            color (unchecked-get r "color")]
                        (.push bikes (new-bike id x y dir color))
                        (.set ^js seat-of id i)
                        (aset grid (+ (* y GW) x) (inc color))))))
        (unchecked-set self "_running" true)
        (js-obj "frames"
                #js [(sim/frame (js-obj "t" "st" "round" round
                                        "tickMs" (unchecked-get self "_tickMs")
                                        "order" (.map ^js riders (fn [r] (unchecked-get r "id")))
                                        "starts" starts))]
                "next" (sim/next-step "tick" COUNTDOWN-MS))))))

(defn input
  "Queue a turn (ports hostInput; 180° reversals are rejected at tick time)."
  [self id d]
  (let [s (.get ^js (unchecked-get self "_seatOf") id)]
    (when-not (identical? s js/undefined)
      (let [b (aget (unchecked-get self "_bikes") s)]
        (when (and (some? b)
                   (not (identical? b js/undefined))
                   (unchecked-get b "alive")
                   (unchecked-get self "_running"))
          (let [pend (unchecked-get b "pend")]
            (when (< (.-length pend) 3) (.push pend (bit-and d 3))))))))
  js/undefined)

(defn peer-gone
  "A rider left mid-round — dies next tick (ports the onPeerGone mark)."
  [self id]
  (when (unchecked-get self "_running")
    (let [s (.get ^js (unchecked-get self "_seatOf") id)]
      (when-not (identical? s js/undefined)
        (let [b (aget (unchecked-get self "_bikes") s)]
          (when (and (some? b) (not (identical? b js/undefined)) (unchecked-get b "alive"))
            (unchecked-set b "leftGame" true))))))
  js/undefined)

(defn- tick [self]
  (if-not (unchecked-get self "_running")
    sim/NO-EMIT
    (let [bikes (unchecked-get self "_bikes")
          grid (unchecked-get self "_grid")
          seat-of (unchecked-get self "_seatOf")
          alive (.filter ^js bikes (fn [b] (unchecked-get b "alive")))]
      ;; turns
      (.forEach alive
                (fn [b]
                  (unchecked-set b "dying" false)
                  (let [pend (unchecked-get b "pend")]
                    (loop []
                      (when (pos? (.-length pend))
                        (let [d (.shift pend)
                              dir (unchecked-get b "dir")]
                          (if (and (not (identical? d dir))
                                   (not (identical? d (mod (+ dir 2) 4))))
                            (unchecked-set b "dir" d)
                            (recur))))))
                  (unchecked-set b "nx" (+ (unchecked-get b "x") (aget DX (unchecked-get b "dir"))))
                  (unchecked-set b "ny" (+ (unchecked-get b "y") (aget DY (unchecked-get b "dir"))))))
      ;; deaths: walls, trails, and same-cell head-on collisions
      (let [claim (js/Map.)]
        (.forEach alive
                  (fn [b]
                    (let [nx (unchecked-get b "nx") ny (unchecked-get b "ny")]
                      (unchecked-set b "dying"
                                     (boolean
                                      (or (unchecked-get b "leftGame")
                                          (< nx 0) (< ny 0) (>= nx GW) (>= ny GH)
                                          (not (identical? 0 (aget grid (+ (* ny GW) nx)))))))
                      (when-not (unchecked-get b "dying")
                        (let [k (+ (* ny GW) nx)
                              other (.get claim k)]
                          (if (and (some? other) (not (identical? other js/undefined)))
                            (do (unchecked-set b "dying" true)
                                (unchecked-set other "dying" true))
                            (.set claim k b))))))))
      (let [h #js []]
        (.forEach alive
                  (fn [b]
                    (if (unchecked-get b "dying")
                      (do
                        (unchecked-set b "alive" false)
                        (let [want (inc (unchecked-get b "color"))
                              n (.-length grid)]
                          (dotimes [i n]
                            (when (identical? (aget grid i) want) (aset grid i 0))))
                        (.push h #js [(.get ^js seat-of (unchecked-get b "id"))
                                      (unchecked-get b "x") (unchecked-get b "y") 0]))
                      (do
                        (unchecked-set b "x" (unchecked-get b "nx"))
                        (unchecked-set b "y" (unchecked-get b "ny"))
                        (aset grid (+ (* (unchecked-get b "y") GW) (unchecked-get b "x"))
                              (inc (unchecked-get b "color")))
                        (.push h #js [(.get ^js seat-of (unchecked-get b "id"))
                                      (unchecked-get b "x") (unchecked-get b "y") 1])))))
        (unchecked-set self "_tickN" (inc (unchecked-get self "_tickN")))
        (let [fs #js [(sim/frame (js-obj "t" "tk" "n" (unchecked-get self "_tickN") "h" h))]
              left (.filter ^js bikes (fn [b] (unchecked-get b "alive")))]
          ;; round end?
          (if (<= (.-length left) (if (> (.-length ^js bikes) 1) 1 0))
            (do
              (unchecked-set self "_running" false)
              (let [w (aget left 0)
                    winner (if (and (some? w) (not (identical? w js/undefined)))
                             (unchecked-get w "id")
                             nil)]
                (when (some? winner) ((unchecked-get self "_addScore") winner))
                (let [roster ((unchecked-get self "_roster"))
                      scores (.map ^js roster (fn [e] #js [(aget e 0) (aget e 3)]))
                      champ (.find ^js roster (fn [e] (>= (aget e 3) WIN-SCORE)))]
                  (.push fs (sim/frame (js-obj "t" "ov" "w" winner "scores" scores)))
                  (if (and (some? champ) (not (identical? champ js/undefined)))
                    (do
                      (unchecked-set self "_champId" (aget champ 0))
                      (unchecked-set self "_lastScores" scores)
                      (js-obj "frames" fs
                              "next" (sim/next-step "match" OVER-MATCH-MS)
                              "matchEnd" (.map ^js roster
                                               (fn [e] #js [(aget e 0) (aget e 1) (aget e 3)]))))
                    (js-obj "frames" fs
                            "next" (sim/next-step "round" OVER-ROUND-MS))))))
            (js-obj "frames" fs
                    "next" (sim/next-step "tick" (unchecked-get self "_tickMs")))))))))

(defn step
  "Execute a scheduled step (\"tick\" | \"match\" | \"lobby\"). A `next` of
   \"round\" is the driver's to execute — it picks the connected riders and
   calls startRound again."
  [self s]
  (case s
    "tick" (tick self)
    "match" (js-obj "frames"
                    #js [(sim/frame (js-obj "t" "ma" "w" (unchecked-get self "_champId")
                                            "scores" (unchecked-get self "_lastScores")))]
                    "next" (sim/next-step "lobby" MATCH-LOBBY-MS))
    "lobby" (do ((unchecked-get self "_resetScores"))
                (js-obj "frames" #js [(sim/frame (js-obj "t" "lo"))] "next" nil))
    sim/NO-EMIT))

(defn abort
  "Void the round (host conceding or closing — ports clearHostTimers)."
  [self]
  (unchecked-set self "_running" false)
  js/undefined)

(defn snapshot
  "Late-joiner snapshot (ports sendSnap; grid RLE as [val,count,…]).
   Six keys in the `sn` frame, so the literal order holds."
  [self to]
  (let [grid (unchecked-get self "_grid")
        runs #js []
        n (.-length grid)]
    (loop [i 0 v (aget grid 0) c 0]
      (if (< i n)
        (if (identical? (aget grid i) v)
          (recur (inc i) v (inc c))
          (do (.push runs v c)
              (recur (inc i) (aget grid i) 1)))
        (.push runs v c)))
    (let [seat-of (unchecked-get self "_seatOf")
          entries #js []]
      (.forEach ^js seat-of (fn [seat id] (.push entries #js [id seat])))
      (js-obj
       "frames"
       #js [(sim/frame
             to
             (js-obj "t" "sn"
                     "round" (unchecked-get self "_round")
                     "tickMs" (unchecked-get self "_tickMs")
                     "n" (unchecked-get self "_tickN")
                     "order" (.map (.sort entries (fn [a b] (- (aget a 1) (aget b 1))))
                                   (fn [e] (aget e 0)))
                     "bikes" (.map ^js (unchecked-get self "_bikes")
                                   (fn [b] #js [(unchecked-get b "x") (unchecked-get b "y")
                                                (if (unchecked-get b "alive") 1 0)
                                                (unchecked-get b "color")]))
                     "runs" runs))]))))

(let [proto (.-prototype NeonGridSim)]
  (unchecked-set proto "newMatch" (fn [] (this-as self (new-match self))))
  (unchecked-set proto "startRound" (fn [riders] (this-as self (start-round self riders))))
  (unchecked-set proto "input" (fn [id d] (this-as self (input self id d))))
  (unchecked-set proto "peerGone" (fn [id] (this-as self (peer-gone self id))))
  (unchecked-set proto "step" (fn [s] (this-as self (step self s))))
  (unchecked-set proto "abort" (fn [] (this-as self (abort self))))
  (unchecked-set proto "snapshot" (fn [to] (this-as self (snapshot self to)))))

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/peer-kit.git