-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.R
2968 lines (2314 loc) · 105 KB
/
app.R
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
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
renv::diagnostics()
library(waiter)
# Prior to app startup ----------------------------------------------------
# Round numbers and labels
rounds = str_c(rep(1:100, each = 2), rep(c("A", "B"), 100))
round_labels = rep(c("Pass the dice", "Next round"),100)
casualty_rules = tribble(~team_A, ~team_B, ~casualty_title, ~casualty_text, ~image,
12, 7, "12-7", "Roll off to see who is taking the kamikaze to the face", 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Attack_on_Pearl_Harbor_Japanese_planes_view.jpg/1280px-Attack_on_Pearl_Harbor_Japanese_planes_view.jpg',
7, 12, "12-7", "Roll off to see who is taking the kamikaze to the face", 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Attack_on_Pearl_Harbor_Japanese_planes_view.jpg/1280px-Attack_on_Pearl_Harbor_Japanese_planes_view.jpg',
18, 12, "War of 1812", "Everyone roll a die, the lowest roll takes a shot.", NULL,
12, 18, "War of 1812", "Everyone roll a die, the lowest roll takes a shot.", NULL,
20, 03, "2003", "Nevar forget: a 9/11 consists of a shot of fireball into a Sam Adams", NULL,
03, 20, "2003", "Nevar forget: a 9/11 consists of a shot of fireball into a Sam Adams", NULL)
# DB Tables ---------------------------------------------------------------
# Pull db tables for tibble templates
players_tbl = dbGetQuery(con, "SELECT * FROM players")
# scores_tbl = dbGetQuery(con, "SELECT * FROM scores")
# player_stats_tbl = dbGetQuery(con, "SELECT * FROM player_stats")
# game_stats_tbl = dbGetQuery(con, "SELECT * FROM game_stats")
# Makea list of table templates
tbls = c("scores", "player_stats", "game_stats", "career_stats")
tbl_templates = map(tbls, function(table){
dbGetQuery(con, str_c("SELECT * FROM ", table, " LIMIT 0"))
}) %>%
set_names(tbls)
# UI ----------------------------------------------------------------------
# Define UI for application that draws a histogram
ui <- dashboardPage(
header = dashboardHeader(title = tagList(
# Corner logo
span(class = "logo-lg", "Snappa Scoreboard"),
img(class = "logo-mini", src = "die_hex.png", style = "padding:.25vw;")
),
# Left side header
leftUi = tagList(
dropdownBlock2(
id = "recent_scores_dropdown",
title = "Recent Scores",
icon = "backward",
badgeStatus = NULL,
reactableOutput("recent_scores_rt"),
actionBttn("game_summary",
"Detailed Game Summary",
style = "material-flat",
color = "primary",
icon = icon("chart-bar"),
size = "sm")
)
# Right side header
),
tags$li(class = "dropdown", socialButton(
href = "https://github.com/mdewey131/Snappa-Scoreboard",
icon = icon("github")
),
style = "padding-top:9px;"
)
),
sidebar = dashboardSidebar(
sidebarMenuOutput("sidebar_menu"),
collapsed = TRUE
),
controlbar = dashboardControlbar(
skin = "dark",
controlbarMenu(
# id = 1,
controlbarItem(
title = "Game Options",
sliderInput(
inputId = "score_to",
label = "What score are you playing to?",
min = 11, max = 50, value = 21
),
br(),
actionBttn("finish_game", "Finish",
icon = icon("check"), size = "sm",
style = "material-flat", color = "warning"),
br(),
actionBttn("debug", label = "debug", icon = icon("bug"),
style = "material-flat", color = "danger")
),
controlbarItem(
title = "Casualties",
disabled(actionBttn("tifu", "Friendly Fire",
style = "material-flat",
size = "sm", color = "danger")),
br(),
actionBttn("highnoon_manual",
"High noon", size = "sm",
style = "material-flat", color = "success"),
br(),
actionBttn("casualty_manual",
"Casualty Check", size = "sm",
style = "material-flat", color = "royal")
)
)
),
body = dashboardBody(
useShinyjs(),
use_waiter(),
tabItems(
# Player Input ------------------------------------------------------------
tabItem(tabName = "player_input",
fluidRow(
team_input_ui("A",
player_choices = dbGetQuery(con, "SELECT player_name FROM thirstiest_players")[,1]),
# Column 2 - empty
column(4, align = "center",
disabled(actionBttn("start_game",
label = "Throw dice?", style = "pill", color = "primary",
icon = icon("dice"), size = "sm")),
uiOutput("validate_start"),
helpText("Note: All players must enter their name before the game can begin"),
# reactableOutput("expected_inputs")
),
# Column 3 - Team B
team_input_ui("B",
player_choices = dbGetQuery(con, "SELECT player_name FROM thirstiest_players")[,1])
)
),
# Scoreboard --------------------------------------------------------------
tabItem(tabName = "scoreboard", #icon = icon("window-maximize"),
div(
fluidRow(id = "dice-row",
column(4, align = "center",
uiOutput("active_die_left")),
column(4, align = "center",
actionBttn("switch_sides",
"Switch Sides", style = "material-flat",
color = "primary",
icon = icon("arrows-rotate"), size = "sm")),
column(4, align = "center",
uiOutput("active_die_right"))
),
team_scoreboard_ui()
)
),
# Career Stats ------------------------------------------------------------
tabItem(tabName = "career_stats",
box(width = 12, title = "Top Snappaneers",
style = str_c("background:", snappa_pal[1]), align = "center",
div(class = "top-snappaneers",
uiOutput("leaderboard_date_filter", width = "100%", class = "leaderboard-row"),
div(class = "snappaneers-header",
# div(class = "snappaneers-title", "Top Snappaneers"),
"The deadliest die-throwers in all the land."
),
reactableOutput("leaderboard_rt", width = "100%"),
div(class = "caption",
p("Toss efficiency = point-scoring tosses as % total tosses"),
p("Players need to play at least 5 games to be eligible for achievements.")
)
)
),
box(width = 8, title = "Score Heatmap",
style = str_c("background:", snappa_pal[1]), align = "center",
p("A heatmap of the different scores that have occurred in games of Snappa."),
plotOutput("scoring_heatmap", height = "38em", width = "100%",
hover = hoverOpts(id = "heat_hover", delay = 100, delayType = c("debounce"))),
uiOutput("heatmap_info")
)
),
# Player Stats ------------------------------------------------------------
tabItem(tabName = "player_stats",
fluidRow(
# Filters
box(width = 12, headerBorder = F, title = "Player Stats",
# Player Select
selectInput("player_select", label = "Player", selectize = F,
choices = dbGetQuery(con, sql("SELECT player_name, p.player_id
FROM players AS p
INNER JOIN player_stats AS ps
ON p.player_id = ps.player_id
GROUP BY player_name, p.player_id
ORDER BY COUNT(ps.*) DESC")) %>%
deframe())
)
)
,
fluidRow(
box(status = "success",
title = "General Stats",
collapsible = T,
icon = icon("list"),
reactableOutput("general_stats", width = "100%")
),
box(status = "success",
title = "Paddle Stats",
collapsible = T,
icon = icon("table-tennis-paddle-ball"),
reactableOutput("paddle_stats", width = "100%")
)
# General and Paddle Stat boxes
),
fluidRow(
box(title = "Casualty Stats",
collapsible = T,
closable = F,
width = 5,
status = "danger",
icon = icon("user-injured"),
plotOutput("casualty_stats_plot")
),
# Top Teammates
box(title = "Top Teammates",
collapsible = T,
closable = F,
width = 7,
status = "primary",
icon = icon("user-group"),
reactableOutput("teammate_tab_rt",
width = "100%")
)
)
,
fluidRow(
box(title = "Player Form",
width = 12,
collapsible = T,
closable = F,
status = "primary",
icon = icon("chart-bar"),
fluidRow(class = "last-n-games",
column(width = 5,
# Stat selection
selectInput("stat_select", label = NULL, selectize = F,
choices = c("Total Points" = "total_points",
"Paddle Points" = "paddle_points",
"Toss Efficiency" = "toss_efficiency"),
selected = "total_points")),
column(width = 1, style = "padding-right:3vw;padding-left:0",
tags$span("Last", style = "font-weight:600;")
),
column(width = 3,
# Sample size selection
selectInput("sample_select", label = NULL, selectize = F,
choices = c(5, 10, 20, 50, 100, 200, "All"),
selected = 5)),
column(width = 1, style = "padding-left:0;",
tags$span(" games", style = "font-weight:600;")
)
),
plotOutput("player_form")
)
# Form plot
),
fluidRow(
box(title = textOutput("game_history_title"),
collapsible = T, width = 12,
closable = F,
collapsed = T,
status = "primary",
icon = icon("timeline"),
reactableOutput("player_game_stats"))
)
)
),
tags$head(
tags$link(rel = "stylesheet", type = "text/css", href = "app.css")
)
)
#
# This is supposed to go at the top tho
# Debugging ---------------------------------------------------------------
# fluidRow(
# column(2, align = "center",
# h3("players"),
# tableOutput("db_output_players")
# ),
# column(5, align = "center",
# h3("scores"),
# tableOutput("db_output_scores")
# ),
# column(5, align = "center",
# h3("player_stats"),
# tableOutput("db_output_player_stats")
# )
#
# )
)
# Server ------------------------------------------------------------------
server <- function(input, output, session) {
observeEvent(input$debug, {
browser()
})
# This is an initial value which will be overwritten when you run
# the simulations
w = Waiter$new(
html = tagList(
spin_pixel(),
str_c("Yeeting Imaginary Dice Into The Sky"
)
))
output$sidebar_menu <- renderUI({
if(input$start_game) {
sidebarMenu(
menuItem("Scoreboard",
tabName = "scoreboard",
icon = icon("window-maximize"), selected = T),
menuItem("Career Stats",
tabName = "career_stats",
icon = icon("chart-column")),
menuItem("Player Stats", tabName = "player_stats",
icon = icon("chart-line"))
)
} else {
sidebarMenu(
menuItem("Player Input",
tabName = "player_input",
icon = icon("users"), selected = T),
menuItem("Career Stats",
tabName = "career_stats",
icon = icon("chart-column")),
menuItem("Player Stats", tabName = "player_stats",
icon = icon("chart-line"))
)
}
})
# Reactive Values Object ---------------------------------------------------------
# reactivePoll watches for changes in the value of checkFunc at the interval
# when it notices changes, it updates using valueFunc
# This checkFunc should update our tables when a game is complete
# Create object to store reactive values
vals <- reactiveValues(
# Initialize new game, player, and score IDs, as well as the shot number
game_id = NULL,
new_player_id = sum(dbGetQuery(con, "SELECT MAX(player_id) FROM players"),1),
score_id = as.integer(0),
shot_num = as.integer(1),
# Current game Tables
game_stats_db = select(tbl_templates$game_stats, 1:5),
player_stats_db = tbl_templates$player_stats,
scores_db = tbl_templates$scores,
players = dbGetQuery(con, sql("SELECT player_id, player_name FROM players")),
# Live data
# Updates when a game is completed
db_tbls = reactivePoll(
intervalMillis = 1000*120,
session = session,
checkFunc = function() {dbGetQuery(con, sql("SELECT COUNT(*) FROM game_stats where game_complete is true"))},
valueFunc = function() {
set_names(
map(tbls,
function(table){
dbGetQuery(con,
sql(
str_c("SELECT * FROM ", table,
if_else(table %in% c("scores", "player_stats", "game_stats"),
" WHERE game_id IN (SELECT game_id FROM game_stats WHERE game_complete is true)",
"")
)
)
)
}),
tbls)
}
),
recent_scores = reactivePoll(
intervalMillis = 100*30,
session = session,
checkFunc = function() {dbGetQuery(con, sql("SELECT COUNT(*) FROM recent_scores"))},
valueFunc = function() {dbGetQuery(con, sql("SELECT * FROM recent_scores"))}
),
casualties = tibble(
casualty_id = integer(),
game_id = integer(),
score_id = integer(),
player_id = integer(),
casualty_type = character(),
reported_player = integer()
),
# setup cooldowns as a list of false bools
cooldowns = setNames(list(F,F,F), unique(casualty_rules$casualty_title)),
# dataframe of the players and their teams
# Current Scores
current_scores = tibble(
team_A = 0,
team_B = 0
),
rebuttal = NULL,
rebuttal_tag = F,
# Values used in scoring events
score = NULL,
error_msg = NULL,
print = FALSE,
score_to = NULL,
# Holds the trolls (more for simplicity of code
# than direct need)
trolls = NULL,
#Records when the extra player ui's are open and
# allows the app to pay attention to empty strings
# only during select times
want_A3 = F,
want_A4 = F,
want_B3 = F,
want_B4 = F,
switch_counter = 1,
game_over = F
)
# Player Inputs, Snappaneers, Other Reactives --------------------------------------
# A reactive for the current score that we're playing to
score_to = reactive({
input$score_to
})
# Increment round number
round_num = reactive({
rounds[vals$shot_num]
})
# Active input buttons
# - List of player inputs which are not null
active_player_inputs = reactive({
list("A1" = input$name_A1, "A2" = input$name_A2, "A3" = input$name_A3, "A4" = input$name_A4, "A5" = input$name_A5,
"B1" = input$name_B1, "B2" = input$name_B2, "B3" = input$name_B3, "B4" = input$name_B4, "B5" = input$name_B5) %>%
discard(is_null)
})
player_inputs = reactive({
tribble(
~input, ~team, ~player_name, ~expected,
"A1", "A", input$name_A1, T,
"A2", "A", input$name_A2, T,
"A3", "A", input$name_A3, input$add_player_A3,
"A4", "A", input$name_A4, input$add_player_A4,
"A5", "A", input$name_A5, input$add_player_A5,
"B1", "B", input$name_B1, T,
"B2", "B", input$name_B2, T,
"B3", "B", input$name_B3, input$add_player_B3,
"B4", "B", input$name_B4, input$add_player_B4,
"B5", "B", input$name_B5, input$add_player_B5
)
})
expected_player_inputs = reactive({
player_inputs() |>
# Keep expected players
filter(expected)
})
output$expected_inputs = renderReactable({
reactable(expected_player_inputs())
})
# Snappaneers - | Team | Player name | Player ID | Shots
snappaneers = reactive({
player_inputs() |>
filter(player_name !="") |>
select(-expected) |>
# Remove empty player inputs
filter(player_name != "") %>%
left_join(vals$players, by = "player_name") %>%
# Add shot count
add_shot_count(shot_num = vals$shot_num)
})
# Vector of players, with current players removed
current_choices = reactive({
dbGetQuery(con, "SELECT player_id, player_name FROM thirstiest_players") %>%
anti_join(., snappaneers(), by = "player_name") %>%
pull(player_name)
})
# Length of active player inputs
num_players = reactive({
length(active_player_inputs()[active_player_inputs() != ""])
})
# Outputs -----------------------------------------------------------------
# Score Validation --------------------------------------------------------
output$A_score_val = renderUI({
# Check that the round/shooter combination makes sense / indicated a paddle
validate(
need(
validate_scores(player = input$scorer,
shot = vals$shot_num,
snappaneers = snappaneers(),
paddle = any(input$paddle, input$foot),
scores_table = vals$scores_db,
rebuttal = vals$rebuttal_tag) == "valid",
message = "That entry doesn't make sense for this round/shooter combination"),
if (snappaneers()[snappaneers()$player_name == input$scorer, "player_id", drop=T] %in%
vals$scores_db[vals$scores_db$round_num == round_num() & vals$scores_db$paddle == F, "player_id", drop=T]){
need(
validate_scores(player = input$scorer,
shot = vals$shot_num,
snappaneers = snappaneers(),
paddle = any(input$paddle, input$foot),
scores_table = vals$scores_db,
rebuttal = vals$rebuttal_tag) == "valid",
message = "That person has already scored a non paddle point this round")
}
)
actionButton("ok_A", "OK")
})
output$B_score_val = renderUI({
validate(
# General needs for typical shooting
need(
validate_scores(player = input$scorer,
shot = vals$shot_num,
snappaneers = snappaneers(),
paddle = any(input$paddle, input$foot),
scores_table = vals$scores_db,
rebuttal = vals$rebuttal_tag) == "valid",
message = "That entry doesn't make sense for this round/shooter combination"
),
# Make sure that the last person to score in this round on offense can't paddle
if (snappaneers()[snappaneers()$player_name == input$scorer, "player_id", drop=T] %in%
vals$scores_db[vals$scores_db$round_num == round_num() & vals$scores_db$paddle == F, "player_id", drop=T]){
need(
validate_scores(player = input$scorer,
shot = vals$shot_num,
snappaneers = snappaneers(),
paddle = any(input$paddle, input$foot),
scores_table = vals$scores_db,
rebuttal = vals$rebuttal_tag) == "valid",
message = "That person has already scored a non paddle point this round")
}
)
actionButton("ok_B", "OK")
})
# Output the round number
output$round_num = renderUI({
team_colours = list("A" = "#e26a6a", "B" = "#2574a9")
HTML(str_c('<h3 class="numbers">',
str_extract(round_num(), "[0-9]+"),
'<span style="color:', team_colours[[str_extract(round_num(), "[AB]+")]], ';">', str_extract(round_num(), "[AB]+"), "</span>",
"</h3>"))
})
output$round_control_buttons = renderUI({
team_colours = list("A" = "danger", "B" = "primary")
div(class = "round-control",
actionBttn("previous_round",
label = "Previous Round", style = "jelly", icon = icon("arrow-left"), color =
team_colours[[str_extract(round_num(), "[AB]+")]], size = "lg"),
actionBttn("next_round",
label = "Pass the dice", style = "jelly", icon = icon("arrow-right"),
color = team_colours[[str_extract(round_num(), "[AB]+")]], size = "lg")
)
})
output$playing_to = renderUI({
p("Playing to: ", strong(score_to()))
})
# Die icon indicating the active team
output$active_die_left = renderUI({
# switch_counter is a counter for how many times switch_sides
# even means that B should be on the left side
switch_is_even = (vals$switch_counter %% 2 == 0)
if(switch_is_even){
# If sides have been switched
img(src = "die_hex.png", style = str_c("background: transparent;display: flex;transform: scale(1.25);position: relative;top: -1vh; display:",
if_else(str_extract(round_num(), "[AB]+") == "B", "block;", "none;")))
} else {
img(src = "die_hex.png", style = str_c("background: transparent;display: flex;transform: scale(1.25);position: relative;top: -1vh; display:",
if_else(str_extract(round_num(), "[AB]+") == "A", "block;", "none;")))
}
})
output$active_die_right = renderUI({
# switch_counter is a counter for how many times switch_sides
# even means that A should be on the right side
switch_is_even = (vals$switch_counter %% 2 == 0)
if(switch_is_even){
img(src = "die_hex.png", style = str_c("background: transparent;display: flex;transform: scale(1.25);position: relative;top: -1vh; display:",
if_else(str_extract(round_num(), "[AB]+") == "A", "block;", "none;")))
} else {
img(src = "die_hex.png", style = str_c("background: transparent;display: flex;transform: scale(1.25);position: relative;top: -1vh; display:",
if_else(str_extract(round_num(), "[AB]+") == "B", "block;", "none;")))
}
})
# Output Team A's score
output$score_A = renderText({
vals$current_scores$team_A
})
output$score_B = renderText({
vals$current_scores$team_B
})
output$recent_scores_rt = renderReactable({
# Take the max sentence length to set width of column in col defs
sentence_width = as.numeric(dbGetQuery(con, sql("SELECT MAX(char_length(what_happened)*6.5) FROM recent_scores")))
column_defs = list(
scoring_team = colDef(show = F),
player_name = colDef(
align = "right",
minWidth = 80,
# Use team colours for player names
style = JS(str_c("function(rowInfo) {
var value = rowInfo.row['scoring_team']
if (value == 'A') {
var color = '", snappa_pal[2], "'
} else {
var color = '", snappa_pal[3], "'
}
return { color: color, fontWeight: 'bold', padding: '5px' }
}")
)
),
what_happened = colDef(
width = sentence_width
)
)
# Take top 5 recent scores
reactable(head(vals$recent_scores(), n = 5),
compact = T,
defaultColDef = colDef(name = "", style = list(padding = "5px 0px"),
# Hide header
headerStyle = list(
alignSelf = "flex-end",
display = "none"
)),
columns = column_defs
)
})
# Output error message
output$skip_error_msg <- renderText({
vals$error_msg
})
# Download button
output$downloadData <- downloadHandler(
filename = function() {
paste('data-', Sys.Date(), '.csv', sep='')
},
content = function(con) {
write.csv(vals$scores_db, con)
}
)
# Game Summary Stats ------------------------------------------------------
team_a_summary_stats = reactive({
scores = vals$db_tbls()[["scores"]]
if(input$start_game == 0){
past_games_scores = filter(scores, game_id != max(game_id))
player_performance_summary(game_started = input$start_game,
player_stats = vals$db_tbls()[["player_stats"]],
team_name = "A",
# current_round,
past_scores = past_games_scores)
} else {
past_games_scores = filter(scores, game_id != vals$game_id)
player_performance_summary(game_started = input$start_game,
game_obj = vals,
player_stats = vals$db_tbls()[["player_stats"]],
team_name = "A",
current_round = round_num(),
past_scores = past_games_scores)
}
}, label = "Team A Summary")
team_b_summary_stats = reactive({
scores = vals$db_tbls()[["scores"]]
if(input$start_game == 0){
past_games_scores = filter(scores, game_id != max(game_id))
player_performance_summary(game_started = input$start_game,
player_stats = vals$db_tbls()[["player_stats"]],
team_name = "B",
# current_round,
past_scores = past_games_scores)
} else {
past_games_scores = filter(scores, game_id != vals$game_id)
player_performance_summary(game_started = input$start_game,
game_obj = vals,
player_stats = vals$db_tbls()[["player_stats"]],
team_name = "B",
current_round = round_num(),
past_scores = past_games_scores)
}
}, label = "Team A Summary")
output$a_breakdown = renderPlot({
max_player_points = max(team_b_summary_stats()$total_points, team_a_summary_stats()$total_points)+1
if(input$start_game == 0){
player_score_breakdown(snappaneers = select(filter(vals$db_tbls()[["player_stats"]], game_id == max(game_id), team == "A"), player_id, team, shots),
scores = filter(vals$db_tbls()[["scores"]], game_id == max(game_id)),
ps_players = vals$players,
ps_team = "A",
chart_max = max_player_points)
} else {
player_score_breakdown(snappaneers = select(filter(vals$player_stats_db, game_id == vals$game_id, team == "A"), player_id, team, shots),
scores = vals$scores_db,
ps_players = vals$players,
ps_game = vals$game_id,
ps_team = "A",
chart_max = max_player_points)
}
}, bg = snappa_pal[1])
output$b_breakdown = renderPlot({
max_player_points = max(team_b_summary_stats()$total_points, team_a_summary_stats()$total_points)+1
if(input$start_game == 0){
player_score_breakdown(snappaneers = select(filter(vals$db_tbls()[["player_stats"]], game_id == max(game_id), team == "B"), player_id, team, shots),
scores = filter(vals$db_tbls()[["scores"]], game_id == max(game_id)),
ps_players = vals$players,
ps_team = "B",
chart_max = max_player_points)
} else {
player_score_breakdown(snappaneers = select(filter(vals$player_stats_db, game_id == vals$game_id, team == "B"), player_id, team, shots),
scores = vals$scores_db,
ps_players = vals$players,
ps_game = vals$game_id,
ps_team = "B",
chart_max = max_player_points)
}
}, bg = snappa_pal[1])
output$game_flow = renderPlot({
if(input$start_game == 0){
game_flow(player_stats = filter(vals$db_tbls()[["player_stats"]], game_id == max(game_id)),
players = vals$players,
scores = filter(vals$db_tbls()[["scores"]], game_id == max(game_id)),
game = filter(vals$db_tbls()[["game_stats"]], game_id == max(game_id))$game_id)
} else {
game_flow(player_stats = vals$player_stats_db,
players = vals$players,
scores = vals$scores_db,
game = vals$game_id)
}
})
output$team_a_summary = renderReactable({
team_summary_tab_rt(right_join(vals$players, team_a_summary_stats(), by = "player_id"))
})
output$team_b_summary = renderReactable({
team_summary_tab_rt(right_join(vals$players, team_b_summary_stats(), by = "player_id"))
})
# Stats Outputs --------------------------------------------------------------
output$leaderboard_rt = renderReactable({
req(input$leaderboard_range)
# Create the rank column, arrange the data, and select the columns
# aggregated_data = vals$db_tbls()[["career_stats"]]
leaderboard_stats = calculate_leaderboard_stats(con, min_date = input$leaderboard_range[1], max_date = input$leaderboard_range[2])
# Separate out those with under 5 games
# dividing_line = min(aggregated_data[aggregated_data$games_played < 5, "rank"])
# leaderboard_table_rt(aggregated_data, dividing_line = dividing_line)
leaderboard_table_rt(collect(leaderboard_stats))
})
output$leaderboard_date_filter = renderUI({
games = tbl(con, "game_stats") |>
summarise(min_date = min(as.Date(game_start), na.rm=T))
current_date = today(tzone = "America/Los_Angeles")
tagList(
dateRangeInput("leaderboard_range", label = "Timeframe",
startview = "year",
start = floor_date(current_date, unit = "year"), end = current_date,
min = pull(games, min_date), max = current_date, format = "M d, yyyy"),
# Quick filters
actionButton("leaderboard_all", label = "All", class = "btn-primary"),
actionButton("leaderboard_past_year", label = "Past 12 Months", class = "btn-primary"),
actionButton("leaderboard_past_6mo", label = "Past 6 Months", class = "btn-primary"),
actionButton("leaderboard_past_3mo", label = "Past 3 Months", class = "btn-primary"),
actionButton("leaderboard_past_month", label = "Past Month", class = "btn-info")
)
})
# Observe quick filters
observeEvent(input$leaderboard_all, {
games = tbl(con, "game_stats") |>
summarise(min_date = min(as.Date(game_start), na.rm=T))
updateDateRangeInput(inputId = "leaderboard_range",
start = pull(games, min_date),
end = today(tzone = "America/Los_Angeles"))
})
observeEvent(input$leaderboard_past_year, {
updateDateRangeInput(inputId = "leaderboard_range",
start = today(tzone = "America/Los_Angeles") %m-% months(12),
end = today(tzone = "America/Los_Angeles"))
})
observeEvent(input$leaderboard_past_6mo, {
updateDateRangeInput(inputId = "leaderboard_range",
start = today(tzone = "America/Los_Angeles") %m-% months(6),
end = today(tzone = "America/Los_Angeles"))
})
observeEvent(input$leaderboard_past_3mo, {
updateDateRangeInput(inputId = "leaderboard_range",
start = today(tzone = "America/Los_Angeles") %m-% months(3),
end = today(tzone = "America/Los_Angeles"))
})
observeEvent(input$leaderboard_past_month, {
updateDateRangeInput(inputId = "leaderboard_range",
start = today(tzone = "America/Los_Angeles") %m-% months(1),
end = today(tzone = "America/Los_Angeles"))
})
output$scoring_heatmap = renderPlot({
score_heatmap(tbl(con, "score_progression"))
}, res = 96)
output$heatmap_info <- renderUI({
req(input$heat_hover)
x <- round(input$heat_hover$x, 0)
y <- round(input$heat_hover$y, 0)
freq = filter(tbl(con, "score_progression"), score_a == y, score_b == x) %>%
pull(n)
HTML(str_c("<p><span style='font-weight:500'>Team B</span>: ", x, " ", "<span style='font-weight:500'>Team A</span>: ", y, "</p>",
"<p><span style='font-weight:500'>How many occurrences?</span>: ", freq))
})
player_game_stats = reactive({
completed_games = tbl(con, "game_stats") |>
filter(game_complete) |>
select(game_id, points_a, points_b)
inner_join(tbl(con, "players"),
tbl(con, "player_stats"),
by = "player_id") |>
inner_join(completed_games, by = "game_id") |>