diff --git a/src/commands/games/cookie.rs b/src/commands/games/cookie.rs index 56cbcbb..53ba436 100644 --- a/src/commands/games/cookie.rs +++ b/src/commands/games/cookie.rs @@ -23,6 +23,80 @@ const UPGRADES: [(&str, f64, f64, &str); 10] = [ ("Alchemy Lab", 75_000_000_000.0, 1_600_000.0, "⚗️"), ]; const ACCENT: u32 = 0xF8C471; + +// ---- the game's own artwork ---------------------------------------------------------------------------------------------- +// Cookie Clicker's pictures belong to Orteil (DashNet). They are not part of this repository: the big cookie and the +// golden cookie are linked straight from the game's website, and the building icons are fetched from there once and +// kept in data/cache/cookieclicker. +const ART: &str = "https://orteil.dashnet.org/cookieclicker/img/"; +const COOKIE_PICTURE: &str = "https://orteil.dashnet.org/cookieclicker/img/perfectCookie.png"; +const GOLDEN_PICTURE: &str = "https://orteil.dashnet.org/cookieclicker/img/goldCookie.png"; +const PICTURE_NAME: &str = "bakery.png"; +/// Row of each upgrade's icon in the game's buildings.png (64 px cells; row 2 is an angry grandma). +const SHEET_ROWS: [u32; 10] = [0, 1, 3, 4, 5, 6, 7, 8, 9, 10]; + +async fn building_sheet(state: &State) -> Option> { + static SHEET: tokio::sync::OnceCell>> = tokio::sync::OnceCell::const_new(); + SHEET + .get_or_init(|| async { + let file = paths::data(&["cache", "cookieclicker", "buildings.png"]); + let bytes = match std::fs::read(&file) { + Ok(b) => b, + Err(_) => { + let b = crate::commands::media::fetch_limited(state, &format!("{ART}buildings.png"), 2 * 1024 * 1024).await?; + if let Some(dir) = file.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = std::fs::write(&file, &b); + b + } + }; + image::load_from_memory(&bytes).ok().map(|i| Arc::new(i.to_rgba8())) + }) + .await + .clone() +} + +/// The owned buildings as the game draws them, each with how many you have. +fn building_strip(sheet: &image::RgbaImage, owned: &[u64; 10]) -> Option> { + use crate::text::{layout, Look}; + use cosmic_text::Align; + let shown: Vec<(usize, u64)> = owned.iter().copied().enumerate().filter(|(_, n)| *n > 0).collect(); + if shown.is_empty() { + return None; + } + const CELL_W: u32 = 150; + const CELL_H: u32 = 76; + let per_row = 5usize; + let rows = shown.len().div_ceil(per_row) as u32; + let width = CELL_W * shown.len().min(per_row) as u32; + let mut img = image::RgbaImage::new(width, CELL_H * rows); + let white = Look::new(None, true, [255, 255, 255]); + let shadow = Look::new(None, true, [20, 12, 6]); + for (n, (index, count)) in shown.iter().enumerate() { + let (cx, cy) = ((n % per_row) as u32 * CELL_W, (n / per_row) as u32 * CELL_H); + let top = SHEET_ROWS[*index] * 64; + if top + 64 <= sheet.height() && sheet.width() >= 64 { + let icon = image::imageops::crop_imm(sheet, 0, top, 64, 64).to_image(); + image::imageops::overlay(&mut img, &icon, (cx + 6) as i64, (cy + 6) as i64); + } + let label = format!("×{}", short(*count as f64)); + let (x, y) = ((cx + 76) as i32, (cy + 22) as i32); + for (dx, dy) in [(-2, 0), (2, 0), (0, -2), (0, 2), (2, 2)] { + layout(&label, 26.0, &shadow, None, Align::Left).draw(&mut img, x + dx, y + dy); + } + layout(&label, 26.0, &white, None, Align::Left).draw(&mut img, x, y); + } + let mut out = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).ok()?; + Some(out) +} + +async fn strip_for(state: &State, b: &Bakery) -> Option> { + let sheet = building_sheet(state).await?; + let owned = b.owned; + tokio::task::spawn_blocking(move || building_strip(&sheet, &owned)).await.ok().flatten() +} const GOLDEN_CHANCE: f64 = 0.03; fn store() -> &'static Arc { @@ -114,11 +188,16 @@ impl Bakery { } } -fn card(user: u64, name: &str, b: &Bakery, note: Option<&str>) -> Component { +fn card(user: u64, name: &str, b: &Bakery, note: Option<&str>, art: bool) -> Component { let who = if name.is_empty() { format!("<@{user}>") } else { escape(name) }; - let mut c = Card::new(Some(ACCENT)).text(&format!("### 🍪 {who}'s bakery\n# {} cookies\n**{}**/sec · {} clicks · {} baked all-time", short(b.cookies), short(b.cps()), thousands(b.clicks), short(b.baked))); - let owned: Vec = UPGRADES.iter().zip(b.owned).filter(|(_, n)| *n > 0).map(|(u, n)| format!("{} {} ×{n}", u.3, u.0)).collect(); - c = c.text(&if owned.is_empty() { "-# Buy a Cursor to start baking automatically.".to_string() } else { owned.join(" · ") }); + let golden = note.is_some_and(|n| n.contains("Golden cookie")); + let mut c = Card::new(Some(ACCENT)).header(&[&format!("### 🍪 {who}'s bakery\n# {} cookies", short(b.cookies)), &format!("**{}**/sec · {} clicks · {} baked all-time", short(b.cps()), thousands(b.clicks), short(b.baked))], Some(if golden { GOLDEN_PICTURE } else { COOKIE_PICTURE })); + if art && b.owned.iter().any(|n| *n > 0) { + c = c.gallery(&[&format!("attachment://{PICTURE_NAME}")]); + } else { + let owned: Vec = UPGRADES.iter().zip(b.owned).filter(|(_, n)| *n > 0).map(|(u, n)| format!("{} {} ×{n}", u.3, u.0)).collect(); + c = c.text(&if owned.is_empty() { "-# Buy a Cursor to start baking automatically.".to_string() } else { owned.join(" · ") }); + } if let Some(n) = note { c = c.text(n); } @@ -132,7 +211,7 @@ fn card(user: u64, name: &str, b: &Bakery, note: Option<&str>) -> Component { select_option(&format!("{name} — {} 🍪", short(price)), name, emoji, &format!("+{}/sec · own {}{}", short(*cps), b.owned[i], if b.cookies >= price { " · ✅ affordable" } else { "" }), false) }) .collect(); - c.select(select_menu(&id("buy"), "🛒 Buy an upgrade…", options)).footer("Your bakery keeps baking while you're away · 🌟 golden cookies drop sometimes").build() + c.select(select_menu(&id("buy"), "🛒 Buy an upgrade…", options)).footer("Your bakery keeps baking while you're away · 🌟 golden cookies drop sometimes · Cookie Clicker art © Orteil").build() } fn btn_style(id: &str, label: &str, emoji: &str, style: ButtonStyle) -> Button { @@ -150,7 +229,10 @@ pub async fn start(ctx: &Arc) -> Result<()> { b.gained_offline = 0.0; b.save(); let name = display_name_of(&ctx.state, ctx.guild_id, ctx.user_id).await; - ctx.reply(card(ctx.user_id.get(), &name, &b, note.as_deref())).await + match strip_for(&ctx.state, &b).await { + Some(png) => ctx.reply_file(card(ctx.user_id.get(), &name, &b, note.as_deref(), true), PICTURE_NAME, png).await, + None => ctx.reply(card(ctx.user_id.get(), &name, &b, note.as_deref(), false)).await, + } } pub async fn on_component(state: &Arc, i: &Interaction) { @@ -162,12 +244,15 @@ pub async fn on_component(state: &Arc, i: &Interaction) { return interact::private_text(state, i, "🍪 That's not your bakery — open yours with `D!cookie`.").await; } let mut b = Bakery::load(owner); + let has_picture = i.message.as_ref().is_some_and(|m| !m.attachments.is_empty()); + let mut bought = false; let note = match action { "click" => b.click().map(|bonus| format!("🌟 **Golden cookie!** +{}", short(bonus))), "buy" => { let Some(index) = d.values.first().and_then(|v| UPGRADES.iter().position(|u| u.0 == v)) else { return interact::ack(state, i).await }; let price = cost(index, b.owned[index]); if b.buy(index) { + bought = true; Some(format!("🛒 Bought a **{}** for {} 🍪", UPGRADES[index].0, short(price))) } else { Some(format!("💸 A {} costs {} — you need {} more.", UPGRADES[index].0, short(price), short(price - b.cookies))) @@ -178,7 +263,14 @@ pub async fn on_component(state: &Arc, i: &Interaction) { b.gained_offline = 0.0; b.save(); let name = display_name_of(state, i.guild_id, user.id).await; - interact::update(state, i, card(owner, &name, &b, note.as_deref())).await; + // the picture only changes when the buildings do; clicks keep the one already on the message + if bought || (!has_picture && b.owned.iter().any(|n| *n > 0)) || action == "refresh" && !has_picture { + if let Some(png) = strip_for(state, &b).await { + interact::ack(state, i).await; + return interact::edit_with_file(state, i, card(owner, &name, &b, note.as_deref(), true), PICTURE_NAME, png).await; + } + } + interact::update(state, i, card(owner, &name, &b, note.as_deref(), has_picture || bought)).await; } /// Top bakers by cookies baked all-time. @@ -220,10 +312,29 @@ mod tests { assert!(b.cookies > before && b.clicks == 1); } + #[test] + fn the_building_strip_draws_only_what_you_own() { + let sheet = image::RgbaImage::from_pixel(256, 1344, image::Rgba([200, 100, 50, 255])); + assert!(building_strip(&sheet, &[0; 10]).is_none()); + let png = building_strip(&sheet, &[5, 3, 1, 0, 0, 0, 0, 0, 0, 12]).unwrap(); + let img = image::load_from_memory(&png).unwrap(); + assert_eq!((img.width(), img.height()), (150 * 4, 76)); + } + + /// Draws a strip from the real sheet if it was fetched (run by hand to look at it). + #[test] + #[ignore = "writes a picture for a human to look at"] + fn preview_with_the_real_sheet() { + let Ok(bytes) = std::fs::read(std::env::var("DEZIO_SHEET").unwrap_or_default()) else { return }; + let sheet = image::load_from_memory(&bytes).unwrap().to_rgba8(); + let png = building_strip(&sheet, &[43, 3, 1, 12, 2, 1, 7, 0, 0, 120]).unwrap(); + std::fs::write(std::env::var("DEZIO_OUT").unwrap(), png).unwrap(); + } + #[test] fn the_card_is_clickable_by_id() { let b = Bakery { user: 9, cookies: 20.0, owned: [0; 10], clicks: 0, baked: 20.0, last: now(), gained_offline: 0.0 }; - let json = serde_json::to_string(&card(9, "Me", &b, None)).unwrap(); + let json = serde_json::to_string(&card(9, "Me", &b, None, false)).unwrap(); assert!(json.contains("cookie:9:click") && json.contains("cookie:9:buy") && json.contains("affordable")); } }