use log::debug; use spacetimedb::{ReducerContext, Table, rand::seq::SliceRandom, reducer}; use crate::tables::*; pub fn shuffle_deal(ctx: &ReducerContext, lobby_id: u32) { debug!("lobby_id: {lobby_id}"); let mut lobby = ctx.db.lobby().id().find(lobby_id).unwrap(); if lobby.game_state == jong_types::states::GameState::Deal { let tiles = new_shuffled_wall(ctx); ctx.db.wall().insert(DbWall { // id: 0, lobby_id, tiles, }); deal_hands(ctx, lobby_id); lobby.game_state = jong_types::states::GameState::Play; ctx.db.lobby().id().update(lobby); } } pub fn new_shuffled_wall(ctx: &ReducerContext) -> Vec { let mut rng = ctx.rng(); let mut wall: Vec<_> = jong_types::tiles::tiles() .into_iter() .map(|tile| ctx.db.tile().insert(DbTile { id: 0, tile })) .collect(); wall.shuffle(&mut rng); wall } pub fn deal_hands(ctx: &ReducerContext, lobby_id: u32) { let players = ctx.db.player().lobby_id().filter(lobby_id); let bots = ctx.db.bot().lobby_id().filter(lobby_id); let mut wall = ctx.db.wall().lobby_id().find(lobby_id).unwrap(); // FIXME rectify deal orders for player in players { let mut tiles = wall.tiles.split_off(wall.tiles.len() - 13); wall = ctx.db.wall().lobby_id().update(wall); tiles.sort_by_key(|t| t.tile); ctx.db.player_hand().insert(PlayerHand { id: 0, player_id: player.id, turn_state: jong_types::TurnState::None, pond: vec![], hand: tiles, working_tile: None, }); } for mut bot in bots { let mut tiles = wall.tiles.split_off(wall.tiles.len() - 13); wall = ctx.db.wall().lobby_id().update(wall); tiles.sort_by_key(|t| t.tile); bot.hand = tiles; ctx.db.bot().id().update(bot); } }