Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Created March 26, 2025 17:37
Show Gist options
  • Save matt-dray/9937fe4bfd55dca9eb03ea362ee1414e to your computer and use it in GitHub Desktop.
Save matt-dray/9937fe4bfd55dca9eb03ea362ee1414e to your computer and use it in GitHub Desktop.
A simple R Shiny app to demonstrate use of reactive values via a gacha-style interface
ui <- bslib::page_fillable(
bslib::card(
bslib::card_header("Gacha"),
shiny::textOutput("rolled_details"),
shiny::textOutput("rolled_emoji"),
shiny::actionButton("btn_roll", "Roll!")
),
bslib::card(
bslib::card_header("Collection"),
shiny::tableOutput("dex")
)
)
server <- function(input, output, session) {
emoji_set <- tibble::tribble(
~Number, ~Name, ~Image, ~Rarity,
1L, "Shrimp", "🦐", "⭐️",
2L, "Crab", "🦀", "⭐️",
3L, "Lobster", "🦞", "⭐️⭐️",
4L, "Squid", "🦑", "⭐️⭐️⭐️"
)
empty_dex <- emoji_set |>
dplyr::mutate(
Name = "<Unknown>",
Image = "",
Count = 0L
)
empty_rolled <- tibble::tibble(
Number = "<Number>",
Name = "<Name>",
Image = "",
Rarity = "<Rarity>"
)
rv <- shiny::reactiveValues(rolled = empty_rolled, dex = empty_dex)
shiny::observeEvent(input$btn_roll, {
emoji_sampled <- emoji_set |>
dplyr::mutate(
Weight = dplyr::case_match(
Rarity,
"⭐️" ~ 0.6,
"⭐️⭐️" ~ 0.3,
"⭐️⭐️⭐️" ~ 0.1
)
) |>
dplyr::slice_sample(n = 1, weight_by = Weight) |>
dplyr::select(-Weight)
rv[["rolled"]] <- emoji_sampled
dex_num <- rv[["rolled"]][["Number"]]
rv[["dex"]][dex_num, "Count"] <- rv[["dex"]][dex_num, "Count"] + 1L
rv[["dex"]][dex_num, "Name"] <- rv[["rolled"]][["Name"]]
rv[["dex"]][dex_num, "Image"] <- rv[["rolled"]][["Image"]]
})
output$rolled_details <- shiny::renderText({
paste0(
"[", rv[["rolled"]][["Number"]], "] ",
rv[["rolled"]][["Name"]], " ",
rv[["rolled"]][["Rarity"]]
)
})
output$rolled_emoji <- shiny::renderText(rv[["rolled"]][["Image"]])
output$dex <- shiny::renderTable(rv[["dex"]])
}
shiny::shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment