jong/jong-line/src/reducers/deal.rs

65 lines
1.9 KiB
Rust
Raw Normal View History

2026-02-15 09:09:04 -08:00
use log::debug;
use spacetimedb::{ReducerContext, Table, rand::seq::SliceRandom, reducer};
2026-02-15 09:09:04 -08:00
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();
2026-02-20 15:36:04 -08:00
if lobby.game_state == jong_types::states::GameState::Deal {
let tiles = new_shuffled_wall(ctx);
2026-02-12 17:06:28 -08:00
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);
}
}
2026-02-12 17:06:28 -08:00
pub fn new_shuffled_wall(ctx: &ReducerContext) -> Vec<DbTile> {
let mut rng = ctx.rng();
let mut wall: Vec<_> = jong_types::tiles::tiles()
2026-02-12 17:06:28 -08:00
.into_iter()
.map(|tile| ctx.db.tile().insert(DbTile { id: 0, tile }))
.collect();
wall.shuffle(&mut rng);
wall
}
2026-02-20 15:36:04 -08:00
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);
}
}