peer-kit / src / ardegazu / peer / games / valley_blocks.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
;; ported-from: src/games/valley-blocks.ts @ v1.3.0
;;
;; valley-blocks (game2) — the p2p tetris. Unlike every other game, each seat
;; simulates its own board from the shared round seed and broadcasts "bs" board
;; states; the host only referees the verdict. This client runs the ported
;; engine for real: on "st" it seeds a board, decides one placement per piece
;; (your onPiece policy, or the stock Dellacherie autopilot), and executes it
;; input-by-input at a human-ish pace — a bot that instantly hard-dropped every
;; piece would be unbeatable in a score race, so pacing is the default and
;; configurable, never absent.
;;
;; Views handed to onPiece are field-identical to the gym's (seat, over, score,
;; lines, level, piece, hold, canHold, candidates, rivals, mode, target — in
;; that order), so a policy trained offline plugs in unchanged. With `host` set
;; the client can claim an empty room and referee rounds itself. The old
;; graceful-loser behavior (announce a topped-out board, never steal a win)
;; survives behind `forfeit: true`.
;;
;; Client side: send "hi"/"bs"/"lv" — receive "ro","st","bs","ov","lo","sn".
(ns ardegazu.peer.games.valley-blocks
  (:require [ardegazu.peer.obj :as obj]
            [ardegazu.peer.games.room :as room]
            [ardegazu.peer.games.host.valley-blocks-host :as vb-host]
            [ardegazu.peer.games.host.valley-blocks-engine :as eng]
            [ardegazu.peer.games.host.valley-blocks-protocol :as proto]
            [ardegazu.peer.games.host.valley-blocks-core :as core]
            [ardegazu.peer.games.valley-blocks-brain :as brain]
            [shadow.cljs.modern :refer (defclass)]))

(def ^:private EMPTY-GRID (.repeat "." (* core/COLS core/ROWS)))
(def ^:private TICK-MS 50)

(declare wire start-round start-loop stop-loop tick decide vb-view board-state sync-now force-sync)

(defclass ValleyBlocksClient
  (extends room/GameRoom)
  (constructor [this peer opts]
    (super peer (let [o (js/Object.assign (js-obj) opts)]
                  (unchecked-set o "hiExtra"
                                 (fn [] (js-obj "name" (unchecked-get this "nick")
                                                "wins" (unchecked-get this "roundWins"))))
                  o))
    (unchecked-set this "roundWins" 0)
    (unchecked-set this "_round" 0)
    (unchecked-set this "_seat" -1)
    (unchecked-set this "_mode" "race-survival")
    (unchecked-set this "_target" 5000)
    (unchecked-set this "_order" #js [])
    (unchecked-set this "_phase" "idle")
    (unchecked-set this "_engine" nil)
    (unchecked-set this "_rivals" (js/Map.))
    (unchecked-set this "_onPiece" (unchecked-get opts "onPiece"))
    (unchecked-set this "_autopilot" (not (identical? false (unchecked-get opts "autopilot"))))
    (unchecked-set this "_forfeit" (identical? true (unchecked-get opts "forfeit")))
    (let [pace (unchecked-get opts "pace")
          input-ms (when ^boolean (js* "!!(~{})" pace) (unchecked-get pace "inputMs"))
          think-ms (when ^boolean (js* "!!(~{})" pace) (unchecked-get pace "thinkMs"))]
      (unchecked-set this "_inputMs" (if ^boolean (js* "~{} == null" input-ms) 110 input-ms))
      (unchecked-set this "_thinkMs"
                     (if ^boolean (js* "~{} == null" think-ms)
                       (fn [level] (+ (js/Math.max 200 (- 700 (* 30 level)))
                                      (* (js/Math.random) 150)))
                       think-ms)))
    (unchecked-set this "_timer" nil)
    (unchecked-set this "_lastTickAt" 0)
    (unchecked-set this "_plan" nil)
    (unchecked-set this "_thinkAt" 0)
    (unchecked-set this "_nextInputAt" 0)
    (unchecked-set this "_lastSent" "")
    (unchecked-set this "_lastSentAt" 0)
    (unchecked-set this "_lastSyncAt" 0)
    (unchecked-set this "_host" nil)
    (let [h (unchecked-get opts "host")]
      (when ^boolean (js* "!!(~{})" h)
        (let [driver (vb-host/ValleyBlocksHost. this h)]
          (unchecked-set this "_host" driver)
          (unchecked-set this "hostDriver" driver))))
    (wire this)))

(unchecked-set ValleyBlocksClient "joinBlocks"
               (fn [opts]
                 (let [o (js/Object.assign (js-obj) opts)]
                   (unchecked-set o "app" "valley-blocks")
                   ((unchecked-get ValleyBlocksClient "join") o))))

(defn- board-state [self]
  (let [e (unchecked-get self "_engine")]
    (if (or (unchecked-get self "_forfeit") (not ^boolean (js* "!!(~{})" e)))
      (js-obj "grid" EMPTY-GRID "score" 0 "lines" 0 "level" 1 "snake" nil "over" true)
      (proto/board-state-of e))))

(defn- sync-now
  "Throttled, deduped board broadcast with a keepalive (ports Party.syncFrom)."
  [self now]
  (when-not (< (- now (unchecked-get self "_lastSyncAt")) proto/STATE-INTERVAL-MS)
    (unchecked-set self "_lastSyncAt" now)
    (let [s (board-state self)
          key (js/JSON.stringify s)]
      (when-not (and (identical? key (unchecked-get self "_lastSent"))
                     (< (- now (unchecked-get self "_lastSentAt")) proto/PING-INTERVAL-MS))
        (unchecked-set self "_lastSent" key)
        (unchecked-set self "_lastSentAt" now)
        (let [f (js-obj "t" "bs" "round" (unchecked-get self "_round")
                        "seat" (unchecked-get self "_seat") "s" s)]
          (let [^js p (unchecked-get self "peer")] (.broadcast p f))
          (when (unchecked-get self "hosting")
            (let [d (unchecked-get self "hostDriver")]
              (when ^boolean (js* "!!(~{})" d) (.onSelfFrame ^js d f))))))))
  js/undefined)

(defn- force-sync [self]
  (unchecked-set self "_lastSent" "")
  (unchecked-set self "_lastSentAt" 0)
  (unchecked-set self "_lastSyncAt" 0)
  (sync-now self (js/Date.now))
  js/undefined)

(defn- vb-view [self candidates]
  (let [e (unchecked-get self "_engine")
        my-id (unchecked-get (unchecked-get self "peer") "myId")
        rivals (unchecked-get self "_rivals")]
    ;; ValleyBlocksView — 12 keys, so sequential sets (the eight-pair js-obj
    ;; rule), and the ORDER is the gym contract
    (obj/ordered "seat" (unchecked-get self "_seat")
                 "over" (unchecked-get e "over")
                 "score" (unchecked-get e "score")
                 "lines" (unchecked-get e "lines")
                 "level" (unchecked-get e "level")
                 "piece" (unchecked-get (unchecked-get e "active") "type")
                 "hold" (unchecked-get e "hold")
                 "canHold" (not (unchecked-get e "holdUsed"))
                 "candidates" candidates
                 "rivals" (.map (.filter ^js (unchecked-get self "_order")
                                         (fn [id] (not (identical? id my-id))))
                                (fn [id]
                                  (let [r (.get ^js rivals id)]
                                    (if (identical? r js/undefined)
                                      (js-obj "score" 0 "over" false)
                                      r))))
                 "mode" (unchecked-get self "_mode")
                 "target" (unchecked-get self "_target"))))

(defn- decide [self e]
  (let [candidates (brain/enumerate-placements e)]
    (if (zero? (.-length candidates))
      (do (eng/hard-drop e) nil) ; nothing fits anywhere — commit, let the board end
      (let [on-piece (unchecked-get self "_onPiece")
            idx (volatile! -1)]
        (cond
          ^boolean (js* "!!(~{})" on-piece)
          (vreset! idx (try
                         (let [r (on-piece (vb-view self candidates))]
                           (if ^boolean (js* "~{} == null" r) -1 r))
                         ;; policy error — the stock brain plays on
                         (catch :default _ -1)))

          (not (unchecked-get self "_autopilot"))
          (vreset! idx ::gravity) ; no brain at all: gravity plays

          :else nil)
        (if (identical? @idx ::gravity)
          nil
          (let [i (if (or (< @idx 0) (>= @idx (.-length candidates)))
                    (brain/stock-pick candidates)
                    @idx)]
            (brain/plan-of (aget candidates i))))))))

(defn- stop-loop [self]
  (when ^boolean (js* "!!(~{})" (unchecked-get self "_timer"))
    (js/clearInterval (unchecked-get self "_timer")))
  (unchecked-set self "_timer" nil)
  js/undefined)

(defn- tick [self]
  (when-not (or (not (identical? (unchecked-get self "_phase") "playing"))
                (< (unchecked-get self "_seat") 0))
    (let [now (js/Date.now)
          dt (js/Math.min (/ (- now (unchecked-get self "_lastTickAt")) 1000) 0.25)]
      (unchecked-set self "_lastTickAt" now)
      (if (unchecked-get self "_forfeit")
        (sync-now self now)
        (let [e (unchecked-get self "_engine")]
          (when ^boolean (js* "!!(~{})" e)
            (when-not (unchecked-get e "over")
              (let [before (unchecked-get e "score")]
                (eng/engine-update e dt)
                (cond
                  (unchecked-get e "snake") (brain/snake-step e)

                  ^boolean (js* "!!(~{})" (unchecked-get self "_plan"))
                  (when (>= now (unchecked-get self "_nextInputAt"))
                    (if (identical? "done" (brain/placement-step e (unchecked-get self "_plan")))
                      (unchecked-set self "_plan" nil)
                      (unchecked-set self "_nextInputAt" (+ now (unchecked-get self "_inputMs")))))

                  (identical? 0 (unchecked-get self "_thinkAt"))
                  (unchecked-set self "_thinkAt"
                                 (+ now ((unchecked-get self "_thinkMs") (unchecked-get e "level"))))

                  (>= now (unchecked-get self "_thinkAt"))
                  (do (unchecked-set self "_thinkAt" 0)
                      (unchecked-set self "_plan" (decide self e))
                      (unchecked-set self "_nextInputAt" now))

                  :else nil)
                ;; crossing the target must reach the referee immediately
                (when (and (< before (unchecked-get self "_target"))
                           (>= (unchecked-get e "score") (unchecked-get self "_target")))
                  (force-sync self))))
            (sync-now self now))))))
  js/undefined)

(defn- start-loop [self]
  (stop-loop self)
  (unchecked-set self "_lastTickAt" (js/Date.now))
  (let [t (js/setInterval (fn [] (tick self)) TICK-MS)]
    (unchecked-set self "_timer" t)
    (when ^boolean (js* "!!(~{})" (unchecked-get t "unref")) (.unref ^js t)))
  (when (unchecked-get self "_forfeit") (force-sync self))
  js/undefined)

(defn- start-round [self m]
  (let [nn (fn [v d] (if ^boolean (js* "~{} == null" v) d v))
        my-id (unchecked-get (unchecked-get self "peer") "myId")]
    (unchecked-set self "_round" (nn (unchecked-get m "round")
                                     (inc (unchecked-get self "_round"))))
    (unchecked-set self "_order" (nn (unchecked-get m "order") #js []))
    (when (string? (unchecked-get m "mode")) (unchecked-set self "_mode" (unchecked-get m "mode")))
    (when (identical? "number" (js* "typeof ~{}" (unchecked-get m "target")))
      (unchecked-set self "_target" (unchecked-get m "target")))
    (unchecked-set self "_seat" (.indexOf ^js (unchecked-get self "_order") my-id))
    (.clear ^js (unchecked-get self "_rivals"))
    (unchecked-set self "_phase" "playing")
    (unchecked-set self "_plan" nil)
    (unchecked-set self "_thinkAt" 0)
    (unchecked-set self "_lastSent" "")
    (unchecked-set self "_lastSentAt" 0)
    (unchecked-set self "_lastSyncAt" 0)
    (cond
      (< (unchecked-get self "_seat") 0)
      (unchecked-set self "_engine" nil) ; spectating this round

      (unchecked-get self "_forfeit")
      (do (unchecked-set self "_engine" nil)
          (start-loop self))

      :else
      (do
        (unchecked-set self "_engine"
                       (eng/ValleyBlocksEngine.
                        (bit-or (unchecked-get m "seed") 0)
                        (js-obj "onLock" (fn []
                                           (unchecked-set self "_plan" nil)
                                           (unchecked-set self "_thinkAt" 0)
                                           js/undefined)
                                "onGameOver" (fn [] (force-sync self)))))
        (start-loop self))))
  js/undefined)

(defn- wire [self]
  (.on ^js self "frame"
       (fn [from m]
         (let [t (unchecked-get m "t")
               my-id (unchecked-get (unchecked-get self "peer") "myId")]
           (if (and (identical? t "bs") (not (identical? from my-id)))
             (let [s (unchecked-get m "s")]
               (when (and ^boolean (js* "!!(~{})" s)
                          (identical? (aget (unchecked-get self "_order")
                                            (bit-or (unchecked-get m "seat") 0))
                                      from)
                          (identical? (unchecked-get m "round") (unchecked-get self "_round")))
                 (.set ^js (unchecked-get self "_rivals") from
                       (js-obj "score" (bit-or (unchecked-get s "score") 0)
                               "over" (identical? true (unchecked-get s "over"))))))
             (when (identical? from (unchecked-get self "hostId"))
               (cond
                 (identical? t "ro")
                 (do
                   (when (string? (unchecked-get m "mode"))
                     (unchecked-set self "_mode" (unchecked-get m "mode")))
                   (when (identical? "number" (js* "typeof ~{}" (unchecked-get m "target")))
                     (unchecked-set self "_target" (unchecked-get m "target")))
                   (when (identical? (unchecked-get self "_phase") "idle")
                     (unchecked-set self "_phase" "lobby")))

                 (identical? t "st") (start-round self m)

                 (identical? t "ov")
                 (do (unchecked-set self "_phase" "roundover")
                     (stop-loop self)
                     (let [w (unchecked-get m "w")]
                       (when (identical? w my-id)
                         (unchecked-set self "roundWins" (inc (unchecked-get self "roundWins"))))
                       (.emit ^js self "matchEnd" (if ^boolean (js* "~{} == null" w) nil w))))

                 (identical? t "lo")
                 (do (unchecked-set self "_phase" "lobby")
                     (stop-loop self)
                     (unchecked-set self "_engine" nil))

                 (identical? t "sn")
                 ;; late join mid-round: spectate until the next round
                 (do
                   (let [r (unchecked-get m "round")]
                     (unchecked-set self "_round" (if ^boolean (js* "~{} == null" r)
                                                    (unchecked-get self "_round") r)))
                   (let [o (unchecked-get m "order")]
                     (unchecked-set self "_order" (if ^boolean (js* "~{} == null" o) #js [] o)))
                   (when (string? (unchecked-get m "mode"))
                     (unchecked-set self "_mode" (unchecked-get m "mode")))
                   (when (identical? "number" (js* "typeof ~{}" (unchecked-get m "target")))
                     (unchecked-set self "_target" (unchecked-get m "target")))
                   (unchecked-set self "_seat" -1)
                   (unchecked-set self "_phase" "playing"))

                 :else nil))))
         js/undefined))
  js/undefined)

(let [proto (.-prototype ValleyBlocksClient)]
  (js/Object.defineProperty proto "seat"
                            #js {:get (fn [] (this-as self (unchecked-get self "_seat")))
                                 :configurable true})
  ;; The attached host driver (null when this client can't referee).
  (js/Object.defineProperty proto "host"
                            #js {:get (fn [] (this-as self (unchecked-get self "_host")))
                                 :configurable true})

  ;; My board score while a round is live/settling (the co-sign guard — mirrors
  ;; game2 main.ts matchScore).
  (unchecked-set
   proto "score"
   (fn []
     (this-as self
       (let [phase (unchecked-get self "_phase")]
         (cond
           (< (unchecked-get self "_seat") 0) nil
           (and (not (identical? phase "playing")) (not (identical? phase "roundover"))) nil
           (unchecked-get self "_forfeit") 0
           :else (let [e (unchecked-get self "_engine")]
                   (if ^boolean (js* "!!(~{})" e) (unchecked-get e "score") 0)))))))

  ;; live round beats idle claim, ties to lowest id (game2's bystander rule).
  (unchecked-set
   proto "claimBeats"
   (fn [from m]
     (this-as self
       (if (nil? (unchecked-get self "hostId"))
         true
         (let [their-live (identical? 1 (unchecked-get m "playing"))
               phase (unchecked-get self "_phase")
               my-host-live (or (identical? phase "playing") (identical? phase "roundover"))]
           (if-not (identical? their-live my-host-live)
             their-live
             (< from (unchecked-get self "hostId"))))))))

  (unchecked-set
   proto "close"
   (fn []
     (this-as self
       (stop-loop self)
       ;; super.close()
       (.call (unchecked-get (.-prototype room/GameRoom) "close") self)))))

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