-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.rkt
1167 lines (1064 loc) · 42.5 KB
/
server.rkt
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#lang racket
; vim: lw+=define-bidi-match-expander,define-bidi-match-expander/coercions,page,define/page,lambda/page,define/summon,define/monster
(provide
(contract-out
[launch-server (-> state?
procedure?
(values string? (-> any)))]))
(require
(prefix-in files: web-server/dispatchers/dispatch-files)
(prefix-in filter: web-server/dispatchers/dispatch-filter)
(prefix-in sequencer: web-server/dispatchers/dispatch-sequencer)
alexis/multicast
file/convertible
frosthaven-manager/constants
frosthaven-manager/defns
(prefix-in elements: frosthaven-manager/elements)
frosthaven-manager/manager
frosthaven-manager/observable-operator
(submod frosthaven-manager/gui/rich-text-display model)
json
nat-traversal
net/url
(prefix-in pict: pict)
(except-in racket/gui
null
newline
#%app)
racket/gui/easy
racket/runtime-path
racket/async-channel
syntax/parse/define
(for-syntax racket/syntax)
(prefix-in tx: txexpr)
web-server/dispatch/syntax
web-server/dispatch/url-patterns
web-server/dispatch/extend
web-server/dispatchers/filesystem-map
(prefix-in form: web-server/formlets)
web-server/http
web-server/http/bindings
web-server/managers/lru
web-server/page
web-server/servlet-dispatch
web-server/servlet/web
web-server/web-server
(only-in xml xexpr->string string->xexpr))
;;;; PREAMBLE
;;;; Macros, parameters, other definitions
(define-runtime-path static "static")
;; simplify calling convention for server-generated pages
(define s (make-parameter #f))
(define reverse-uri (make-parameter #f))
(define send-event (make-parameter #f))
;; "do" e in a different context… (namely, the one which invoked the server)
(define-syntax-parser do
[(_ e:expr ...+)
#:with s (format-id this-syntax "s" #:source this-syntax)
(syntax/loc this-syntax
((send-event)
(λ (s) e ...)))])
(define-syntax-rule (define-bidi-match-expander/coercions id in-test? in out-test? out)
(begin
(define-coercion-match-expander in/m in-test? in)
(define-coercion-match-expander out/m out-test? out)
(define-bidi-match-expander id in/m out/m)))
(define-constant-format/parse
format-element parse-element
([elements:fire "Fire"]
[elements:ice "Ice"]
[elements:air "Air"]
[elements:earth "Earth"]
[elements:light "Light"]
[elements:dark "Dark"]))
(define-constant-format/parse
format-element-style parse-element-style
([elements:element-pics-infused "infused"]
[elements:element-pics-waning "waning"]
[elements:element-pics-unfused "unfused"]))
(define-bidi-match-expander/coercions element-name-arg
(or/c "Fire" "Ice" "Air" "Earth" "Light" "Dark") parse-element
{(one-of? elements:fire elements:ice elements:air
elements:earth elements:light elements:dark)} format-element)
(define-bidi-match-expander/coercions element-style-arg
(or/c "infused" "waning" "unfused") string->symbol
(or/c 'infused 'waning 'unfused) symbol->string)
;; evaluates e if player id (pid) and summon id (sid) can be extracted from req
(define-syntax-parser define/summon
[(_ name:id (req:id {~literal =>} [pid:id sid:id]) e:expr ...+)
(syntax/loc this-syntax
(define (name req)
(-do-summon req (λ (req pid sid) e ...))))])
;; evalutes e if monster group id and monster number can be extracted from req
(define-syntax-parser define/monster
[(_ name:id (req:id {~literal =>} [monster-group-id:id monster-number:id])
e:expr ...+)
(syntax/loc this-syntax
(define (name req)
(-do-monster req (λ (req monster-group-id monster-number) e ...))))])
;; tags procedures that need state to yield the action to apply (see
;; do-monster-group/mgid): IOW, proc should be state -> Action (for some
;; "Action" type).
(struct needs-state [proc]
#:transparent
#:property prop:procedure (struct-field-index proc))
;; safe way to evaluate selector:condition, which contract errors when the
;; input is outside the domain; if this produces #t, input is a valid condition
;; number
(define selector:condition? (make-coerce-safe? selector:condition))
;; formlet shorthand
(define input-int
(make-keyword-procedure
(λ (kws kw-vals . rest)
(define numeric-text-input
(keyword-apply form:text-input kws kw-vals rest
#:attributes '([inputmode "numeric"])))
(form:to-number (form:to-string (form:required numeric-text-input))))))
(define input-int-optional
(make-keyword-procedure
(λ (kws kw-vals . rest)
;; extract #:value for form:default
(define value (~>> (kws kw-vals) (map cons) (assoc '#:value) (and _ cdr)))
(define numeric-text-input
;; #:value will be supplied automatically if needed
(keyword-apply form:text-input kws kw-vals rest
#:attributes '([inputmode "numeric"])))
(~>> (numeric-text-input)
(form:default (string->bytes/utf-8 (~a value)))
form:to-string form:to-number))))
;;;; MAIN ENTRYPOINT
(define (launch-server an-s a-send-event)
;; each request thread get its own receiver, so that they can all see the
;; updates
(define ch (make-multicast-channel))
(for ([e (elements:elements)]
[@e-state (state-@elements an-s)])
(obs-observe!
@e-state
(λ (new-e-state)
(thread
(thunk
(multicast-channel-put ch `(element ,(elements:element-pics-name e) ,new-e-state)))))))
(obs-observe!
(state-@creatures an-s)
(let ([ids (box null)])
(λ (creatures)
(thread
(thunk
(define env (@! (state-@env an-s)))
(define ads (@! (state-@ability-decks an-s)))
(for ([c creatures])
(cond
[(player? (creature-v c)) (multicast-channel-put ch `(player ,c))]
[(creature-is-mg*? c) (multicast-channel-put ch `(monster-group* ,c ,env ,ads))]))
(define new-ids (map creature-css-id (sort creatures < #:key (creature-initiative ads))))
(unless (equal? (unbox ids) new-ids)
(set-box! ids new-ids)
(multicast-channel-put ch `(reorder ,(unbox ids)))))))))
(obs-observe! (state-@round an-s) (λ (r) (multicast-channel-put ch `(number round ,r))))
(obs-observe! (state-@num-players an-s)
(λ (n) (multicast-channel-put ch `(number inspiration ,(inspiration-reward n)))))
(obs-observe!
(state-@level an-s)
(λ (level)
(define info (get-level-info level))
(for ([id '(trap hazardous-terrain gold xp)]
[f (list level-info-trap-damage level-info-hazardous-terrain level-info-gold level-info-exp)])
(define n (f info))
(multicast-channel-put ch `(number ,id ,n)))))
(obs-observe!
(state-@in-draw? an-s)
(λ (in-draw?)
(thread
(thunk
(define N (@! (state-@round an-s)))
(multicast-channel-put ch `(alert ,(if in-draw?
(format "Start of Round ~a" N)
;; state-@round has already incremented
(format "End of Round ~a" (sub1 N)))))
(define env (@! (state-@env an-s)))
(define ads (@! (state-@ability-decks an-s)))
(define cs (@! (state-@creatures an-s)))
(for ([c cs])
(cond
[(player? (creature-v c)) (multicast-channel-put ch `(player ,c))]
[(creature-is-mg*? c) (multicast-channel-put ch `(monster-group* ,c ,env ,ads))]))
(define ids (map creature-css-id (sort cs < #:key (creature-initiative ads))))
(multicast-channel-put ch `(reorder ,ids))
(multicast-channel-put ch `(text progress-game ,(if in-draw? "Next Round" "Draw Abilities")))))))
(obs-observe!
(state-@env an-s)
(λ (env)
(define ads (@! (state-@ability-decks an-s)))
(for ([c (@! (state-@creatures an-s))])
(cond
[(creature-is-mg*? c) (multicast-channel-put ch `(monster-group* ,c ,env ,ads))]))))
(obs-observe!
(state-@ability-decks an-s)
(λ (ads)
(thread
(thunk
(define env (@! (state-@env an-s)))
(for ([c (@! (state-@creatures an-s))])
(cond
[(creature-is-mg*? c) (multicast-channel-put ch `(monster-group* ,c ,env ,ads))]))))))
(obs-observe!
(state-@modifier an-s)
(λ (m)
(multicast-channel-put ch `(text modifier-discard ,(~a (if m
(format-monster-modifier m)
"N/A"))))
(when m
(multicast-channel-put ch `(alert
,(format "The monster drew: ~a." (format-monster-modifier m)))))))
(obs-observe!
(state-@curses an-s)
(λ (cs)
(multicast-channel-put ch `(number curses ,(length cs)))))
(obs-observe!
(state-@blesses an-s)
(λ (cs)
(multicast-channel-put ch `(number blesses ,(length cs)))))
(define-values (app the-reverse-uri)
(dispatch-rules
[("") overview]
[("rewards") rewards]
[("discard-pile") discard-pile]
[("action" "player" (string-arg) (string-arg) ...) #:method "post" player-action]
[("action" "summon" (string-arg) (string-arg) ...) #:method "post" summon-action]
[("action" "monster" (string-arg) (string-arg) ...) #:method "post" monster-action]
[("action" "element" "transition") #:method "post" element-transition]
[("action" "draw-modifier") #:method "post" web-draw-modifier]
[("action" "progress-game") #:method "post" progress-game]
[("events") (event-source ch)]
[("element-pics" (element-name-arg) (element-style-arg)) element-pic]
[else not-found]))
(define url->path/static
(make-url->path static))
(define static-dispatcher
(files:make #:url->path (λ (u)
(url->path/static
(struct-copy url u [path (cdr (url-path u))])))
#:cache-no-cache #t))
(define port-ch (make-async-channel 1))
(define manager
(make-threshold-LRU-manager expired-page (* 1024 1024 1024)))
(define stop
(parameterize ([s an-s]
[reverse-uri the-reverse-uri]
[send-event a-send-event])
(serve
#:dispatch (sequencer:make
(filter:make #rx"^/static/" static-dispatcher)
(dispatch/servlet app #:manager manager))
#:port (if (file-exists? ".frosthaven-manager-port")
(file->value ".frosthaven-manager-port")
0)
#:confirmation-channel port-ch)))
(match (async-channel-get port-ch)
[(? port-number? port) (values (~a "http://" (best-interface-ip-address) ":" port) stop)]
[(? exn? e) (raise e)]))
;;;; X-EXPRS
(define common-heads
`((meta ([name "viewport"] [content "width=device-width, initial-scale=1.0"]))
(meta ([charset "UTF-8"]))
(link ([rel "stylesheet"] [href "/static/style.css"]))))
(define (expired-page req)
(response/xexpr
`(html
(head
(title "Page Has Expired.")
,@common-heads)
(body
(p "Sorry, this page has expired. "
(a ([href ,(url->string (url-sans-param (request-uri req)))])
"This page")
" may be the one you wanted.")))))
(define (not-found _req)
(response/xexpr
#:code 404
`(html
(head
(title "Not Found")
,@common-heads)
(body
(h1 "Not Found")))))
(define/page (overview)
(response/xexpr
`(html
(head
(title "Frosthaven Manager")
(script ([src "/static/events.js"]))
,@common-heads)
(body
(dialog ([id "dialog"]
[onclick "this.close()"]))
(h1 "Frosthaven Manager")
,@(elements-body embed/url)
,@(creatures-body embed/url)
,@(bottom-info-body embed/url)
))))
(define/page (rewards)
(define players
(for/list ([c (@! (state-@creatures (s)))]
#:when (player? (creature-v c)))
(creature-v c)))
(define num-players (@! (state-@num-players (s))))
(define level (@! (state-@level (s))))
(define level-info (get-level-info level))
(define gold-factor (level-info-gold level-info))
(define bonus-xp (level-info-exp level-info))
(response/xexpr
`(html
(head
(title "Frosthaven Manager Rewards")
,@common-heads)
(body
(h1 "Rewards")
(div
([class "table-wrapper"])
(table
(thead
(tr (th "Player")
(th "Random Item?")
(th "XP")
(th "Gold")
,@(map {~>> format-material-kind (list 'th)} material-kinds)
,@(map {~>> format-herb-kind (list 'th)} herb-kinds)
(th "Special Loot")))
(tbody
,@(for/list ([p players])
(define loots (player->rewards p num-players level))
`(tr ,@(map {~>> (list 'td)} loots))))))
(p "Gold Conversion Rate: " ,(~a gold-factor))
(p "Bonus Experience: " ,(~a bonus-xp))
;; individual loot cards
,@(append*
(for/list ([p players])
`((h2 ,(~a (player-name p) "'s Loot Cards"))
(ul
,@(for/list ([loot-text (map (format-loot-card num-players) (player-loot p))])
`(li ,loot-text))))))))))
(define/page (discard-pile)
(define discard (@! (state-@monster-discard (s))))
(response/xexpr
`(html
(head
(title "Frosthaven Manager Discard Pile")
,@common-heads)
(body
(h1 "Discard Pile")
(p "Most Recent First")
(ol
,@(for/list ([m discard])
`(li ,(format-monster-modifier m))))))))
(define (bottom-info-body embed/url)
(define level-info (@! (@> (state-@level (s)) get-level-info)))
(define num-players (@! (state-@num-players (s))))
(define in-draw? (@! (state-@in-draw? (s))))
(define discard (@! (@> (state-@modifier (s)) {(if _ format-monster-modifier "N/A")})))
(define curses (@! (@> (state-@curses (s)) {~> length ~a})))
(define blesses (@! (@> (state-@blesses (s)) {~> length ~a})))
`((div
([class "bottom-info"])
(p ,(action-button
(list "draw-modifier")
empty
"Draw Modifier")
(span ([id "modifier-discard"])
,discard)
" "
(a ([href "/discard-pile"]) "Discard Pile")
,(action-button
(list "progress-game")
empty
(if in-draw?
"Next Round"
"Draw Abilities")
'([id "progress-game"])))
(p ,(action-button
(list "monster" "curse")
empty
`(span "Curse Monster ("
(span ([id "curses"]) ,curses)
"/" ,(~a (length monster-curse-deck)) ")"))
,(action-button
(list "monster" "bless")
empty
`(span "Bless Monster ("
(span ([id "blesses"]) ,blesses)
"/" ,(~a (length bless-deck)) ")")))
(p "Round "
(span ([id "round"])
,(number->string (@! (state-@round (s)))))
". "
"Trap: "
(span ([id "trap"])
,(number->string (level-info-trap-damage level-info)))
". "
"Hazardous Terrain: "
(span ([id "hazardous-terrain"])
,(number->string (level-info-hazardous-terrain level-info)))
". "
"Gold: "
(span ([id "gold"])
,(number->string (level-info-gold level-info)))
". "
"Bonus XP: "
(span ([id "xp"])
,(number->string (level-info-exp level-info)))
". "
"Inspiration: "
(span ([id "inspiration"])
,(number->string (inspiration-reward num-players)))
". "
(a ([href "/rewards"]) "Rewards.")))))
(define (elements-body embed/url)
`((h2 "Elements")
(div ([id "elements"])
,@(for/list ([e (list elements:fire elements:ice elements:air elements:earth elements:light elements:dark)]
[@e-state (state-@elements (s))])
`(img ([id ,(format-element e)]
[src ,((reverse-uri) element-pic e (@! @e-state))]
,(action-click
(list "element" "transition")
(list (list (~s "id") (~s (format-element e)))))))))))
(define (creatures-body embed/url)
`((h2 "Creatures")
(ul ([class "creatures"])
,@(let ([env (@! (state-@env (s)))]
[ability-decks (@! (state-@ability-decks (s)))]
[cs (@! (state-@creatures (s)))])
(creatures-xexprs embed/url cs env ability-decks)))))
(define (creatures-xexprs embed/url cs env ability-decks)
(for/list ([c (sort cs < #:key (creature-initiative ability-decks))])
(define v (creature-v c))
(cond
[(player? v) (player-xexpr embed/url (creature-id c) v)]
[(monster-group*? v)
(define mg (monster-group*-mg v))
(define ability (~>> (mg) monster-group-set-name (hash-ref ability-decks) ability-decks-current))
(monster-group-xexpr (creature-id c) mg ability env)])))
(define (player-xexpr embed/url id p)
(define id-binding (list (~s "id") (~s (~s id))))
`(li ([id ,(player-css-id id)])
(div ([class "smash-inline"])
(a ([href ,(embed/url {(edit-player id)})])
(span ([class "player-name"])
,(on ((player-name p))
(if non-empty-string? _ "???"))))
" ("
(span ([class "player-initiative"])
,(~a (player-initiative p)))
") "
(a ([href ,(embed/url {(set-initiative-form id)})])
"Set Initiative")
(p ,(action-button
(list "player" "hp" "-")
(list id-binding)
"-")
(span ([class "player-HP"])
,(player->hp-text p))
,(action-button
(list "player" "hp" "+")
(list id-binding)
"+")
,(action-button
(list "player" "xp" "-")
(list id-binding)
"-")
"XP: "
(span ([class "player-XP"])
,(~a (player-xp p)))
,(action-button
(list "player" "xp" "+")
(list id-binding)
"+")
(button ([type "button"]
[onclick
,(string-join
(list
(string-trim (action-script (list "player" "loot") (list id-binding)) ";" #:left? #f)
".then((r) => r.json())"
".then((j) => { showDialog(`You got ${j.loot}!`); },"
" (_) => { showDialog('The loot deck is empty.'); })"))])
"Loot!")))
(div ([class "smash-inline"])
(p (select ([id ,(~a "select-conditions-" id)]
[aria-label ,(~a "Add conditions to " (player-name p))])
,@(for/list ([c conditions])
`(option ([value ,(~a (discriminator:condition c))])
,(format-condition c))))
,(action-button
(list "player" "condition" "add")
(list id-binding
(list (~s "condition")
(~a "document.querySelector("
(~s (~a "#select-conditions-" id))
").value")))
"Add Condition"))
(p (span
([class "player-conditions"])
(span
,@(~> (p) player-conditions* (active-conditions->xexpr id-binding))))))
(p (a ([href ,(embed/url {(new-summon-form id)})])
"Summon"))
(ol ([class "summons"])
,@(summons->xexprs id (player-summons p)))))
(define (edit-player-form p)
(form:formlet
(form:#%#
(p "Player Name" ,[=> (form:to-string
(form:default
(string->bytes/utf-8 (player-name p))
(form:text-input #:value (player-name p))))
name])
(p "Max HP" ,[=> (input-int-optional #:value (~a (player-max-hp p)))
max-hp])
(p ,[=> (form:submit "Edit Player") _submit]))
(list name max-hp)))
(define/page (edit-player player-id)
(define p
(~>> ((s)) state-@creatures @!
(findf {~> creature-id (equal? player-id)})
;; fallible, but let's assume we have a valid player-id
creature-v))
(define (handle-form-response r)
(define form-response
(with-handlers ([exn:fail? values])
(form:formlet-process (edit-player-form p) r)))
(match form-response
[(list (? string? new-name) (? natural? new-max-hp))
(update-player-info player-id new-name new-max-hp)]
[_ (void)])
(my-redirect/get ((reverse-uri) overview)))
(response/xexpr
`(html
(head (title "Edit Player") ,@common-heads)
(body
(form ([action ,(embed/url handle-form-response)]
[method "post"])
,@(form:formlet-display (edit-player-form p)))))))
(define set-initiative
(form:formlet
(form:#%#
(p "Initiative" ,{=> (input-int) init})
(p ,{=> (form:submit "Set Initiative") _submit}))
init))
(define/page (set-initiative-form player-id)
(define (handle-form-response r)
(define form-response
(with-handlers ([exn:fail? values])
(form:formlet-process set-initiative r)))
(match form-response
[(? initiative? init) (set-player-initiative player-id init)]
[_ (void)])
(my-redirect/get ((reverse-uri) overview)))
(response/xexpr
`(html
(head (title "Set Initiative") ,@common-heads)
(body
(form ([action ,(embed/url handle-form-response)]
[method "post"])
,@(form:formlet-display set-initiative))))))
;; s: summon?
;; id: string? unique to whole page
(define (summon-xexpr s id)
(define id-binding (list (~s "id") (~s id)))
`(li ([id ,id])
,(action-button
(list "summon" "kill")
(list id-binding)
"Kill")
(span ([class "summon-name"])
,(summon-name s))
,(action-button
(list "summon" "hp" "-")
(list id-binding)
"-")
(span ([class "summon-HP"])
,(summon->hp-text s))
,(action-button
(list "summon" "hp" "+")
(list id-binding)
"+")
(div ([class "smash-inline"])
(p (select ([id ,(~a "select-conditions-" id)]
[aria-label ,(~a "Add conditions to " (summon-name s))])
,@(for/list ([c conditions])
`(option ([value ,(~a (discriminator:condition c))])
,(format-condition c))))
,(action-button
(list "summon" "condition" "add")
(list id-binding
(list (~s "condition")
(~a "document.querySelector("
(~s (~a "#select-conditions-" id))
").value")))
"Add Condition"))
(p (span
([class "summon-conditions"])
(span
,@(~> (s) summon-conditions* (active-conditions->xexpr id-binding "summon"))))))))
;; required => exn:fail if not present
(define new-summon
(form:formlet
(form:#%#
(p "Name:" ,{=> form:input-string name})
(p "Max HP:" ,{=> (input-int) max-hp})
(p ,{=> (form:submit "Summon") _submit}))
(list name max-hp)))
(define/page (new-summon-form player-id)
(define (handle-form-response r)
(define form-response
(with-handlers ([exn:fail? values])
(form:formlet-process new-summon r)))
(match form-response
[(list name max-hp)
(do-player/id player-id
(const #f)
{(player-summon name max-hp)})]
[_ (void)])
(my-redirect/get ((reverse-uri) overview)))
(response/xexpr
`(html
(head (title "Summon") ,@common-heads)
(body
(form ([action ,(embed/url handle-form-response)]
[method "post"])
,@(form:formlet-display new-summon))))))
(define (summons->xexprs summoner-id ss)
(for/list ([(s i) (in-indexed ss)])
(define id (~a "summon-" summoner-id "-" i))
(summon-xexpr s id)))
(define (monster-group-xexpr id mg ability env)
(define normal-stats (monster-group-normal-stats mg))
(define elite-stats (monster-group-elite-stats mg))
(define (both-empty? f)
(~> (normal-stats elite-stats)
(>< f) (all empty?)))
(define (empty-row label f sf)
(if (both-empty? f)
empty
`((tr (td ,(sf normal-stats))
(td ,label)
(td ,(sf elite-stats))))))
`(li ([id ,(monster-group-css-id id)])
(span ([class "monster-group-name"])
,(monster-group-name mg))
" ("
(span ([class "monster-group-initiative"])
,(monster-ability-initiative->text ability))
")"
(details
([class "stats-summary"])
(summary "Stats")
(table
([class "monster-group-stats"])
(tr (th "Normal") (th "Stat") (th "Elite"))
(tr (td ,(~> (normal-stats) monster-stats-move (if _ ~a "-")))
(td "Move")
(td ,(~> (elite-stats) monster-stats-move (if _ ~a "-"))))
(tr (td ,(~a (monster-stats-attack* normal-stats env)))
(td "Attack")
(td ,(~a (monster-stats-attack* elite-stats env))))
,@(empty-row "Bonuses" monster-stats-bonuses monster-stats-bonuses-string)
,@(empty-row "Effects" monster-stats-effects monster-stats-effects-string)
,@(empty-row "Immunities" monster-stats-immunities monster-stats-immunities-string)
(tr (td ,(~a (monster-stats-max-hp* normal-stats env)))
(td "Max HP")
(td ,(~a (monster-stats-max-hp* elite-stats env))))))
(p ([class "monster-ability"])
(span ([class "monster-ability-name"]) ,(monster-ability-name->text ability))
(ol ([class "monster-ability-abilities"])
,@(monster-ability-xexpr mg ability env)))
(ul ([class "monsters"])
,@(monsters->xexprs id (monster-group-monsters mg) mg env))))
(define (monster-ability-xexpr mg ability env)
(for/list ([the-ability (if ability (monster-ability-abilities ability) empty)])
`(li
(span
([class "monster-ability-ability"])
,@(for/list ([content (in-list (monster-ability-ability->rich-text the-ability ability mg env))])
(match content
[(? string? s) s]
[(? newline?) `(br)]
[(or (? pict:pict? p) (pict/alt-text p _))
(define svg (string->xexpr (bytes->string/utf-8 (convert p 'svg-bytes))))
(cond
[(>= (pict:pict-height p) 50) svg]
[else (tx:attr-set svg 'class "icon")])]))))))
(define (monsters->xexprs group-id monsters mg env)
(for/list ([monster monsters])
(define id (~a "monster-" group-id "-" (monster-number monster)))
(monster-xexpr id monster mg env)))
(define (monster-xexpr id m mg env)
(define id-binding (list (~s "id") (~s id)))
`(li ([id ,id])
,(action-button (list "monster" "kill")
(list id-binding)
"Kill")
(span ([class "monster-number"])
,(~a (monster-group-name mg) " ")
,(~a (monster-number m))
,(if (monster-elite? m) "(E)" ""))
,(action-button (list "monster" "hp" "-")
(list id-binding)
"-")
(span ([class "monster-HP"])
,(monster->hp-text m (get-monster-stats mg m) env))
,(action-button (list "monster" "hp" "+")
(list id-binding)
"+")
(div ([class "smash-inline"])
(p (select ([id ,(~a "select-conditions-" id)]
[aria-label ,(~a "Add conditions to " (monster-group-name mg) " " (monster-number m))])
,@(for/list ([c conditions])
`(option ([value ,(~a (discriminator:condition c))])
,(format-condition c))))
,(action-button
(list "monster" "condition" "add")
(list id-binding
(list (~s "condition")
(~a "document.querySelector("
(~s (~a "#select-conditions-" id))
").value")))
"Add Condition"))
(p (span ([class "monster-conditions"])
(span
,@(~> (m) monster-conditions (active-conditions->xexpr id-binding "monster"))))))))
(define (action-button actions bindings body [attrs empty])
`(button ([type "button"]
,(action-click actions bindings)
,@attrs)
,body))
(define (active-conditions->xexpr cs id-binding [who "player"])
(~> (cs)
(map {(active-condition->xexpr id-binding who)} _)
(add-between ", " #:before-last " and ")))
(define (active-condition->xexpr c id-binding [who "player"])
`(span ([class "condition"])
,(format-condition c)
,(action-button
(list who "condition" "remove")
(list id-binding
(list (~s "condition") (~s (~s (discriminator:condition c)))))
"X")))
;;;; ELEMENT PICTURES
(define (element-pic _req name style)
(response/output
(λ (o)
(write-bytes (convert (get-pic name style) 'svg-bytes) o))
#:mime-type #"image/svg+xml"))
(define (get-pic pics style)
((parse-element-style (symbol->string style))
(pics)))
;;;; SSE
(define ((event-source ch) _req)
(define receiver (make-multicast-receiver ch))
(response/output
#:headers (list (header #"Cache-Control" #"no-store")
(header #"Content-Type" #"text/event-stream")
;; Don't use Connection in HTTP/2 or HTTP/3, but Racket's
;; web-server is HTTP/1.1 as confirmed by
;; `curl -vso /dev/null --http2 <addr>`.
(header #"Connection" #"keep-alive")
;; Pairs with Connection; since our event source sends data
;; every 5 seconds at minimum, this 10s timeout should be
;; sufficient.
(header #"Keep-Alive" #"timeout=10"))
(λ (out)
(let loop ()
(cond
[(sync/timeout 5 receiver) => (event-stream out)]
[else (displayln ":" out)])
(loop)))))
(define (event-stream out)
(match-lambda
[`(element ,name ,state)
(define data (hash 'name name 'state (symbol->string state)))
(displayln "event: element" out)
(display (format "data: ~a" (jsexpr->string data)) out)
(display "\n\n" out)]
[`(player ,c)
(define p (creature-v c))
(define id (creature-id c))
(define id-binding (list (~s "id") (~s (~s id))))
(define css-id (player-css-id id))
(define data
(hash 'id css-id
'data (hash
'player-name (on ((player-name p))
(if non-empty-string? _ "???"))
'player-initiative (~a (player-initiative p))
'player-HP (player->hp-text p)
'player-XP (~a (player-xp p))
'player-conditions
(~> (p) player-conditions*
(active-conditions->xexpr id-binding)
(cons 'span _)
xexpr->string))
'summons (map xexpr->string (summons->xexprs id (player-summons p)))
'xexpr (xexpr->string `(li (p ([id ,css-id])
"New players have been added; please refresh the page.")))))
(displayln "event: player" out)
(display (format "data: ~a" (jsexpr->string data)) out)
(displayln "\n\n" out)]
[(list 'monster-group* c env ads)
(define mg (monster-group*-mg (creature-v c)))
(define id (creature-id c))
(define css-id (monster-group-css-id id))
(define ability (~> (mg) monster-group-set-name (hash-ref ads _ #f) (and _ ability-decks-current)))
(define data
(hash 'id css-id
'data (hash
'monster-group-name (monster-group-name mg)
'monster-group-initiative (monster-ability-initiative->text ability)
'monster-ability-name (monster-ability-name->text ability)
'monster-ability-abilities (~>> (mg ability env)
monster-ability-xexpr
(map xexpr->string))
'monsters (~>> (id (monster-group-monsters mg) mg env)
monsters->xexprs
(map xexpr->string)))
'xexpr (xexpr->string (monster-group-xexpr id mg ability env))))
(displayln "event: monster-group" out)
(display (format "data: ~a" (jsexpr->string data)) out)
(displayln "\n\n" out)]
[`(reorder ,ids)
(define data ids)
(displayln "event: reorder-ids" out)
(display (format "data: ~a" (jsexpr->string data)) out)
(displayln "\n\n" out)]
[`(number ,id ,(? number? n))
(define data (hash 'id (~a id) 'n n))
(displayln "event: number" out)
(display (format "data: ~a" (jsexpr->string data)) out)
(displayln "\n\n" out)]
[`(text ,id ,(? string? s))
(define data (hash 'id (~a id) 'text s))
(displayln "event: text" out)
(display (format "data: ~a" (jsexpr->string data)) out)
(displayln "\n\n" out)]
[`(alert ,(? string? text))
(displayln "event: alert" out)
(display (format "data: ~a" (jsexpr->string text)) out)
(displayln "\n\n" out)]))
;;;; ACTIONS
(define (player-action req what args)
(let/ec return
(match (cons what args)
['("hp" "+") (increment-player-hp req)]
['("hp" "-") (decrement-player-hp req)]
['("xp" "+") (increment-player-xp req)]
['("xp" "-") (decrement-player-xp req)]
['("condition" "remove") (remove-player-condition req)]
['("condition" "add") (add-player-condition req)]
['("loot") (loot! req return)]
[_ (return (not-found req))])
(response/empty)))
(define (summon-action req what args)
(let/ec return
(match (cons what args)
['("kill") (kill-summon req)]
['("hp" "-") (decrement-summon-hp req)]
['("hp" "+") (increment-summon-hp req)]
['("condition" "add") (add-summon-condition req)]
['("condition" "remove") (remove-summon-condition req)]
[_ (return (not-found req))])
(response/empty)))
(define (monster-action req what args)
(let/ec return
(match (cons what args)
['("kill") (do-kill-monster req)]
['("hp" "-") (decrement-monster-hp req)]
['("hp" "+") (increment-monster-hp req)]
['("condition" "add") (add-monster-condition req)]
['("condition" "remove") (remove-monster-condition req)]
['("curse") (curse-monster req)]
['("bless") (bless-monster req)]
[_ (return (not-found req))])
(response/empty)))
(define (element-transition req)
(match (assq 'id (request-bindings req))
[`(id . ,(element-name-arg e))
(define @e-state
(~>> ((list elements:fire elements:ice elements:air
elements:earth elements:light elements:dark)
(state-@elements (s)))
(map cons) (assq e) cdr))
(do (<@ @e-state transition-element-state))
(response/empty)]
[(or `(id . ,_) #f) (not-found req)]))
(define (web-draw-modifier _req)
(do ((draw-modifier s)))
(response/empty))
(define (progress-game _req)
(define transition
(cond
[(@! (state-@in-draw? (s))) (next-round (s))]
[else (draw-abilities (s))]))
(do (transition))
(response/empty))
(define-flow (increment-player-hp _req)
(do-player player-at-max-health? (player-act-on-hp add1)))
(define-flow (decrement-player-hp _req)
(do-player player-dead? (player-act-on-hp sub1)))
(define-flow (increment-player-xp _req)
(do-player (const #f) (player-act-on-xp add1)))
(define-flow (decrement-player-xp _req)
(do-player {~> player-xp zero?} (player-act-on-xp sub1)))
(define-flow (remove-player-condition _req)
(do-player-condition #f))
(define-flow (add-player-condition _req)
(do-player-condition #t))
(define (set-player-initiative id init)
(do (<@ (state-@creatures s)
{(update-players id {(player-set-initiative init)})})))
(define (update-player-info id new-name new-max-hp)
(do (<@ (state-@creatures s)
{(update-players id
{~> (esc (player-update-name new-name))
(esc (player-act-on-max-hp (const new-max-hp)))})})))
(define (loot! req return)
(match (req->player-id req)
[(and id (not #f))
(define card
(@! (@> (state-@loot-deck (s)) {(and (not empty?) first)})))