LINE1 10 20 30 40 50 60 70 80 90 100 1101234use rand::seq::SliceRandom;5use serde::{Deserialize, Serialize};67use crate::map::{HEIGHT, Map, TILE, WIDTH};89pub const TICK_SECS: f64 = 1.0 / 15.0;10const SPEED: f32 = 90.0;11const MAX_PLAYERS: usize = 8;12const IDLE_TIMEOUT: f64 = 10.0;13const ROUND_SECS: f64 = 240.0;14const RESET_DELAY: f64 = 15.0;15const CHOP_SECS: f64 = 2.0;16const SOUP_SECS: f64 = 10.0;17const ROAST_SECS: f64 = 12.0;18const EAT_SECS: f64 = 4.0;19const POT_MAX: usize = 3;20const SPAWN_TILES: [(i32, i32); 8] = [(13, 13), (15, 13), (17, 13), (19, 13), (13, 14), (15, 14), (17, 14), (19, 14)];21const POT_MIN: usize = 2;222324const DIRS: [(i32, i32); 4] = [(0, 1), (-1, 0), (0, -1), (1, 0)];252627const SKIN_COUNT: u8 = 5;28const HAIR_STYLE_COUNT: u8 = 5;29const HAIR_COLOR_COUNT: u8 = 6;30const SHIRT_COUNT: u8 = 7;31const PANTS_COUNT: u8 = 5;32const HAT_COUNT: u8 = 4;3334#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]35#[serde(rename_all = "snake_case")]36pub enum Food {37 Veg,38 Greens,39 Loaf,40 ChoppedVeg,41 ChoppedGreens,42 Soup,43 Roast,44 Bread,45 Salad,46}4748impl Food {49 pub fn name(self) -> &'static str {50 match self {51 Food::Veg => "vegetables",52 Food::Greens => "greens",53 Food::Loaf => "bread loaf",54 Food::ChoppedVeg => "chopped vegetables",55 Food::ChoppedGreens => "chopped greens",56 Food::Soup => "soup",57 Food::Roast => "roasted vegetables",58 Food::Bread => "bread",59 Food::Salad => "salad",60 }61 }6263 pub fn is_dish(self) -> bool {64 matches!(self, Food::Soup | Food::Roast | Food::Bread | Food::Salad)65 }66}6768#[derive(Clone, Copy, Debug, Serialize, Deserialize)]69#[serde(rename_all = "camelCase")]70pub struct Look {71 pub skin: u8,72 pub hair_style: u8,73 pub hair_color: u8,74 pub shirt: u8,75 pub pants: u8,76 pub hat: u8,77}7879impl Look {80 fn clamped(self) -> Self {81 Self {82 skin: self.skin % SKIN_COUNT,83 hair_style: self.hair_style % HAIR_STYLE_COUNT,84 hair_color: self.hair_color % HAIR_COLOR_COUNT,85 shirt: self.shirt % SHIRT_COUNT,86 pants: self.pants % PANTS_COUNT,87 hat: self.hat % HAT_COUNT,88 }89 }90}9192#[derive(Serialize)]93pub struct Player {94 pub id: String,95 pub name: String,96 pub look: Look,97 pub x: f32,98 pub y: f32,99 pub dir: u8,100 pub moving: bool,101 pub hand: Option<Food>,102 #[serde(skip)]103 input: (f32, f32),104 #[serde(skip)]105 last_seen: f64,106}107108#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]109#[serde(rename_all = "snake_case")]110pub enum Kind {111 Dispenser(Food),112 Board,113 Pot,114 Oven,115 Bowl,116 Seat(usize),117}118119#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]120#[serde(rename_all = "snake_case")]121pub enum Phase {122 Idle,123 Busy,124 Ready,125}126127pub struct Station {128 pub tx: i32,129 pub ty: i32,130 pub kind: Kind,131 pub items: Vec<Food>,132 pub phase: Phase,133 until: f64,134}135136#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]137#[serde(rename_all = "snake_case")]138pub enum WantState {139 Pending,140 Eating,141 Done,142}143144#[derive(Serialize)]145pub struct Want {146 pub food: Food,147 pub state: WantState,148 #[serde(skip)]149 until: f64,150}151152pub struct Guest {153 pub name: &'static str,154 pub look: Look,155 pub seat: usize,156 pub wants: Vec<Want>,157}158159impl Guest {160 fn done(&self) -> bool {161 self.wants.iter().all(|w| w.state == WantState::Done)162 }163}164165#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]166#[serde(rename_all = "snake_case")]167pub enum RoundState {168 Playing,169 Won,170 Lost,171}172173pub struct Round {174 pub number: u32,175 pub state: RoundState,176 pub started: f64,177 pub ended: f64,178 pub served: u32,179}180181pub struct World {182 pub map: Map,183 pub players: Vec<Player>,184 pub stations: Vec<Station>,185 pub guests: Vec<Guest>,186 pub round: Round,187 now: f64,188}189190#[derive(Debug)]191pub enum JoinError {192 Full,193}194195fn seat_looks() -> [(&'static str, Look); 4] {196 [197 ("Mira", Look { skin: 1, hair_style: 4, hair_color: 2, shirt: 4, pants: 2, hat: 1 }),198 ("Tomas", Look { skin: 3, hair_style: 0, hair_color: 1, shirt: 0, pants: 0, hat: 0 }),199 ("Ines", Look { skin: 0, hair_style: 2, hair_color: 3, shirt: 5, pants: 4, hat: 3 }),200 ("Ola", Look { skin: 2, hair_style: 3, hair_color: 4, shirt: 3, pants: 1, hat: 1 }),201 ]202}203204fn station_kind(c: u8, seat_count: &mut usize) -> Option<Kind> {205 Some(match c {206 b'F' => Kind::Dispenser(Food::Veg),207 b'G' => Kind::Dispenser(Food::Greens),208 b'L' => Kind::Dispenser(Food::Loaf),209 b'B' => Kind::Board,210 b'S' => Kind::Pot,211 b'O' => Kind::Oven,212 b'N' => Kind::Bowl,213 b'c' => {214 *seat_count += 1;215 Kind::Seat(*seat_count - 1)216 }217 _ => return None,218 })219}220221fn raw_for_board(f: Food) -> Option<Food> {222 match f {223 Food::Veg => Some(Food::ChoppedVeg),224 Food::Greens => Some(Food::ChoppedGreens),225 Food::Loaf => Some(Food::Bread),226 _ => None,227 }228}229230impl World {231 pub fn new() -> Self {232 let map = Map::new();233 let mut stations = Vec::new();234 let mut seats = 0;235 for ty in 0..HEIGHT as i32 {236 for tx in 0..WIDTH as i32 {237 if let Some(kind) = station_kind(map.char_at(tx, ty), &mut seats) {238 stations.push(Station {239 tx,240 ty,241 kind,242 items: Vec::new(),243 phase: Phase::Idle,244 until: 0.0,245 });246 }247 }248 }249 let mut world = Self {250 map,251 players: Vec::new(),252 stations,253 guests: Vec::new(),254 round: Round { number: 0, state: RoundState::Playing, started: 0.0, ended: 0.0, served: 0 },255 now: 0.0,256 };257 world.start_round();258 world259 }260261 fn start_round(&mut self) {262 let mut foods = [Food::Soup, Food::Roast, Food::Bread, Food::Salad];263 self.guests = seat_looks()264 .into_iter()265 .enumerate()266 .map(|(seat, (name, look))| {267 foods.shuffle(&mut rand::rng());268 Guest {269 name,270 look,271 seat,272 wants: foods[..2]273 .iter()274 .map(|&food| Want { food, state: WantState::Pending, until: 0.0 })275 .collect(),276 }277 })278 .collect();279 for st in &mut self.stations {280 st.items.clear();281 st.phase = Phase::Idle;282 st.until = 0.0;283 }284 for p in &mut self.players {285 p.hand = None;286 }287 self.round.number += 1;288 self.round.state = RoundState::Playing;289 self.round.started = self.now;290 self.round.served = 0;291 }292293 pub fn join(&mut self, name: &str, look: Look) -> Result<String, JoinError> {294 if self.players.len() >= MAX_PLAYERS {295 return Err(JoinError::Full);296 }297 let id = format!("{:032x}", rand::random::<u128>());298 299 let (tx, ty) = SPAWN_TILES[self.players.len() % SPAWN_TILES.len()];300 let spawn = (tx as f32 * TILE + TILE / 2.0, ty as f32 * TILE + TILE / 2.0);301 let name: String = name.trim().chars().take(12).collect();302 let name = if name.is_empty() { "Friend".to_string() } else { name };303 self.players.push(Player {304 id: id.clone(),305 name,306 look: look.clamped(),307 x: spawn.0,308 y: spawn.1,309 dir: 0,310 moving: false,311 hand: None,312 input: (0.0, 0.0),313 last_seen: self.now,314 });315 Ok(id)316 }317318 pub fn set_input(&mut self, id: &str, dx: f32, dy: f32) -> bool {319 let now = self.now;320 let Some(p) = self.players.iter_mut().find(|p| p.id == id) else {321 return false;322 };323 let len = (dx * dx + dy * dy).sqrt();324 p.input = if len > 1.0 { (dx / len, dy / len) } else { (dx, dy) };325 p.last_seen = now;326 if dx.abs() > 0.1 || dy.abs() > 0.1 {327 p.dir = if dx.abs() >= dy.abs() {328 if dx < 0.0 { 1 } else { 3 }329 } else if dy < 0.0 {330 2331 } else {332 0333 };334 }335 true336 }337338 pub fn leave(&mut self, id: &str) -> Vec<String> {339 let mut logs = Vec::new();340 self.players.retain(|p| {341 if p.id == id {342 logs.push(format!("{} left the flat.", p.name));343 false344 } else {345 true346 }347 });348 logs349 }350351 352 pub fn act(&mut self, id: &str) -> Option<Vec<String>> {353 let pi = self.players.iter().position(|p| p.id == id)?;354 let mut logs = Vec::new();355 if self.round.state != RoundState::Playing {356 return Some(logs);357 }358 let (fx, fy) = DIRS[self.players[pi].dir as usize];359 let tx = (self.players[pi].x / TILE).floor() as i32 + fx;360 let ty = (self.players[pi].y / TILE).floor() as i32 + fy;361 let Some(si) = self.stations.iter().position(|s| s.tx == tx && s.ty == ty) else {362 return Some(logs);363 };364 let now = self.now;365 let p = &mut self.players[pi];366 let st = &mut self.stations[si];367 match st.kind {368 Kind::Dispenser(food) => {369 if p.hand.is_none() {370 p.hand = Some(food);371 }372 }373 Kind::Board => match (st.phase, p.hand) {374 (Phase::Idle, Some(f)) if matches!(f, Food::Veg | Food::Greens | Food::Loaf) => {375 st.items = vec![f];376 st.phase = Phase::Busy;377 st.until = now + CHOP_SECS;378 p.hand = None;379 logs.push(format!("{} is chopping {}.", p.name, f.name()));380 }381 (Phase::Ready, None) => {382 p.hand = st.items.pop();383 st.items.clear();384 st.phase = Phase::Idle;385 }386 _ => {}387 },388 Kind::Pot | Kind::Oven => match (st.phase, p.hand) {389 (Phase::Idle, Some(Food::ChoppedVeg)) if st.items.len() < POT_MAX => {390 st.items.push(Food::ChoppedVeg);391 p.hand = None;392 }393 (Phase::Idle, None) if st.items.len() >= POT_MIN => {394 let secs = if st.kind == Kind::Pot { SOUP_SECS } else { ROAST_SECS };395 st.phase = Phase::Busy;396 st.until = now + secs;397 let what = if st.kind == Kind::Pot { "soup" } else { "roasted vegetables" };398 logs.push(format!("{} started the {what}.", p.name));399 }400 (Phase::Ready, None) => {401 p.hand = st.items.pop();402 st.items.clear();403 st.phase = Phase::Idle;404 }405 _ => {}406 },407 Kind::Bowl => match (st.phase, p.hand) {408 (Phase::Idle, Some(f))409 if matches!(f, Food::ChoppedGreens | Food::ChoppedVeg) && !st.items.contains(&f) =>410 {411 st.items.push(f);412 p.hand = None;413 if st.items.len() == 2 {414 st.items = vec![Food::Salad];415 st.phase = Phase::Ready;416 logs.push(format!("{} tossed a salad.", p.name));417 }418 }419 (Phase::Ready, None) => {420 p.hand = st.items.pop();421 st.items.clear();422 st.phase = Phase::Idle;423 }424 _ => {}425 },426 Kind::Seat(gi) => {427 let guest = &mut self.guests[gi];428 let Some(food) = p.hand.filter(|f| f.is_dish()) else {429 return Some(logs);430 };431 match guest.wants.iter_mut().find(|w| w.food == food && w.state == WantState::Pending) {432 Some(want) => {433 want.state = WantState::Eating;434 want.until = now + EAT_SECS;435 p.hand = None;436 logs.push(format!("{} brings {} to {}.", p.name, food.name(), guest.name));437 }438 None => logs.push(format!("{} does not need {} right now.", guest.name, food.name())),439 }440 }441 }442 Some(logs)443 }444445 fn collides(&self, x: f32, y: f32) -> bool {446 447 let (hw, hh) = (5.0, 3.0);448 [(x - hw, y - hh), (x + hw, y - hh), (x - hw, y + hh), (x + hw, y + hh)]449 .iter()450 .any(|&(px, py)| self.map.solid((px / TILE).floor() as i32, (py / TILE).floor() as i32))451 }452453 pub fn step(&mut self, dt: f64) -> Vec<String> {454 self.now += dt;455 let now = self.now;456 let mut logs = Vec::new();457458 459 for i in 0..self.players.len() {460 let (dx, dy) = self.players[i].input;461 let moving = dx != 0.0 || dy != 0.0;462 self.players[i].moving = moving;463 if !moving {464 continue;465 }466 let step = SPEED * dt as f32;467 let (x, y) = (self.players[i].x, self.players[i].y);468 if !self.collides(x + dx * step, y) {469 self.players[i].x = x + dx * step;470 }471 let (x, y) = (self.players[i].x, self.players[i].y);472 if !self.collides(x, y + dy * step) {473 self.players[i].y = y + dy * step;474 }475 }476477 478 let mut gone = Vec::new();479 self.players.retain(|p| {480 if now - p.last_seen > IDLE_TIMEOUT {481 gone.push(p.name.clone());482 false483 } else {484 true485 }486 });487 for name in gone {488 logs.push(format!("{name} left the flat."));489 }490491 492 for st in &mut self.stations {493 if st.phase == Phase::Busy && now >= st.until {494 st.phase = Phase::Ready;495 match st.kind {496 Kind::Board => {497 let f = st.items[0];498 st.items = vec![raw_for_board(f).unwrap_or(f)];499 }500 Kind::Pot => st.items = vec![Food::Soup],501 Kind::Oven => st.items = vec![Food::Roast],502 _ => {}503 }504 }505 }506507 508 for g in &mut self.guests {509 for w in &mut g.wants {510 if w.state == WantState::Eating && now >= w.until {511 w.state = WantState::Done;512 self.round.served += 1;513 logs.push(format!("{} has finished the {}.", g.name, w.food.name()));514 }515 }516 }517518 519 match self.round.state {520 RoundState::Playing => {521 if self.guests.iter().all(|g| g.done()) {522 self.round.state = RoundState::Won;523 self.round.ended = now;524 logs.push("Everyone has eaten. Thanks for coming.".into());525 } else if now - self.round.started >= ROUND_SECS {526 self.round.state = RoundState::Lost;527 self.round.ended = now;528 logs.push("The food has gone cold. The guests head home.".into());529 }530 }531 _ => {532 if now - self.round.ended >= RESET_DELAY {533 self.start_round();534 logs.push("A new evening starts. Four guests are at the table.".into());535 }536 }537 }538539 logs540 }541542 pub fn snapshot_json(&self) -> String {543 let time_left = match self.round.state {544 RoundState::Playing => (ROUND_SECS - (self.now - self.round.started)).max(0.0),545 _ => 0.0,546 };547 let stations: Vec<StationView> = self548 .stations549 .iter()550 .filter(|s| !matches!(s.kind, Kind::Dispenser(_) | Kind::Seat(_)))551 .map(|s| StationView {552 x: s.tx,553 y: s.ty,554 kind: s.kind,555 phase: s.phase,556 items: &s.items,557 left: if s.phase == Phase::Busy { (s.until - self.now).max(0.0) } else { 0.0 },558 })559 .collect();560 let guests: Vec<GuestView> = self561 .guests562 .iter()563 .map(|g| {564 let (sx, sy) = self565 .stations566 .iter()567 .find(|s| s.kind == Kind::Seat(g.seat))568 .map(|s| (s.tx, s.ty))569 .unwrap_or((0, 0));570 GuestView { name: g.name, look: g.look, x: sx, y: sy, wants: &g.wants }571 })572 .collect();573 let snap = Snapshot {574 t: self.now,575 round: RoundView {576 number: self.round.number,577 state: self.round.state,578 time_left,579 served: self.round.served,580 },581 players: &self.players,582 guests,583 stations,584 };585 serde_json::to_string(&snap).unwrap_or_else(|_| "{}".into())586 }587}588589#[derive(Serialize)]590struct Snapshot<'a> {591 t: f64,592 round: RoundView,593 players: &'a [Player],594 guests: Vec<GuestView<'a>>,595 stations: Vec<StationView<'a>>,596}597598#[derive(Serialize)]599struct RoundView {600 number: u32,601 state: RoundState,602 time_left: f64,603 served: u32,604}605606#[derive(Serialize)]607struct GuestView<'a> {608 name: &'static str,609 look: Look,610 x: i32,611 y: i32,612 wants: &'a [Want],613}614615#[derive(Serialize)]616struct StationView<'a> {617 x: i32,618 y: i32,619 kind: Kind,620 phase: Phase,621 items: &'a [Food],622 left: f64,623}624625#[cfg(test)]626mod tests {627 use super::*;628629 fn look() -> Look {630 Look { skin: 0, hair_style: 0, hair_color: 0, shirt: 0, pants: 0, hat: 0 }631 }632633 fn station_at(w: &World, tx: i32, ty: i32) -> usize {634 w.stations.iter().position(|s| s.tx == tx && s.ty == ty).unwrap()635 }636637 638 fn run(w: &mut World, id: &str, secs: f64) {639 let steps = (secs / TICK_SECS).ceil() as usize;640 for _ in 0..steps {641 let (dx, dy) = w.players.iter().find(|p| p.id == id).unwrap().input;642 w.set_input(id, dx, dy);643 w.step(TICK_SECS);644 }645 }646647 648 fn place(w: &mut World, id: &str, tx: f32, ty: f32, dir: u8) {649 let p = w.players.iter_mut().find(|p| p.id == id).unwrap();650 p.x = tx * TILE + TILE / 2.0;651 p.y = ty * TILE + TILE / 2.0;652 p.dir = dir;653 }654655 #[test]656 fn stations_and_seats_are_found() {657 let w = World::new();658 assert_eq!(w.guests.len(), 4);659 assert_eq!(w.stations.iter().filter(|s| matches!(s.kind, Kind::Seat(_))).count(), 4);660 }661662 #[test]663 fn soup_is_chopped_cooked_served() {664 let mut w = World::new();665 let id = w.join("Ola", look()).unwrap();666 667 place(&mut w, &id, 9.0, 2.0, 2);668 w.act(&id);669 assert_eq!(w.players[0].hand, Some(Food::Veg));670 671 place(&mut w, &id, 7.0, 2.0, 2);672 w.act(&id);673 assert_eq!(w.players[0].hand, None);674 run(&mut w, &id, CHOP_SECS + 0.1);675 w.act(&id);676 assert_eq!(w.players[0].hand, Some(Food::ChoppedVeg));677 678 place(&mut w, &id, 5.0, 2.0, 2);679 for _ in 0..2 {680 w.players[0].hand = Some(Food::ChoppedVeg);681 w.act(&id);682 }683 w.players[0].hand = None;684 w.act(&id);685 let pot = station_at(&w, 5, 1);686 assert_eq!(w.stations[pot].phase, Phase::Busy);687 run(&mut w, &id, SOUP_SECS + 0.1);688 assert_eq!(w.stations[pot].phase, Phase::Ready);689 w.act(&id);690 assert_eq!(w.players[0].hand, Some(Food::Soup));691 }692693 #[test]694 fn a_seat_only_takes_a_wanted_dish() {695 let mut w = World::new();696 let id = w.join("Ola", look()).unwrap();697 let wanted = w.guests[0].wants[0].food;698 let unwanted = [Food::Soup, Food::Roast, Food::Bread, Food::Salad]699 .into_iter()700 .find(|f| !w.guests[0].wants.iter().any(|x| x.food == *f))701 .unwrap();702 let seat = w.stations.iter().find(|s| s.kind == Kind::Seat(0)).unwrap();703 let (sx, sy) = (seat.tx, seat.ty);704 place(&mut w, &id, sx as f32, sy as f32 + 1.0, 2);705 w.players[0].hand = Some(unwanted);706 w.act(&id);707 assert_eq!(w.guests[0].wants[0].state, WantState::Pending);708 assert_eq!(w.players[0].hand, Some(unwanted));709 w.players[0].hand = Some(wanted);710 w.act(&id);711 assert_eq!(w.players[0].hand, None);712 let want = w.guests[0].wants.iter().find(|x| x.food == wanted).unwrap();713 assert_eq!(want.state, WantState::Eating);714 }715716 #[test]717 fn the_round_is_won_when_everyone_has_eaten() {718 let mut w = World::new();719 let id = w.join("Ola", look()).unwrap();720 for g in &mut w.guests {721 for want in &mut g.wants {722 want.state = WantState::Eating;723 want.until = 0.5;724 }725 }726 run(&mut w, &id, 1.0);727 assert_eq!(w.round.state, RoundState::Won);728 assert_eq!(w.round.served, 8);729 }730731 #[test]732 fn players_cannot_walk_through_walls() {733 let mut w = World::new();734 let id = w.join("Ola", look()).unwrap();735 w.set_input(&id, 0.0, -1.0);736 run(&mut w, &id, 26.0);737 738 assert!(w.players[0].y / TILE >= 8.0);739 }740}