can we call this rewrite 4.5

This commit is contained in:
Tao Tien 2026-02-23 16:18:21 -08:00
parent 2d3993452b
commit a0171b1de6
9 changed files with 128 additions and 120 deletions

View file

@ -1,20 +1,17 @@
use std::time::Duration;
use log::{debug, trace};
use spacetimedb::{
ReducerContext, ScheduleAt::Interval, Table as _, rand::seq::SliceRandom, reducer,
};
use jong_types::{GameState, TurnState};
use crate::{
reducers::deal::{deal_hands, new_shuffled_wall, shuffle_deal},
tables::{
DbTile, DbWall, GameTimer, PlayerClock, PlayerHand, PlayerOrBot, bot, game_timer,
lobby as _, player, player_clock, player_hand, tile as _, wall,
},
use crate::tables::{
DbTile, DbWall, GameTimer, Lobby, PlayerClock, PlayerHand, PlayerOrBot, bot, game_timer,
lobby as _, player, player_clock, player_hand, tile as _, wall,
};
mod deal;
mod hand;
mod lobby;
@ -28,10 +25,12 @@ pub fn advance_game(ctx: &ReducerContext, mut game_timer: GameTimer) -> Result<(
}
if let Some(mut lobby) = ctx.db.lobby().id().find(game_timer.lobby_id) {
trace!("running schedule for lobby {}", lobby.id);
match lobby.game_state {
GameState::Setup => {
// TODO reduce interval beforehand so we don't wait a second?
// TODO keep a count to clear stale lobbies
trace!("shuffle wall");
let tiles = {
let mut rng = ctx.rng();
let mut wall: Vec<_> = jong_types::tiles::tiles()
@ -51,6 +50,7 @@ pub fn advance_game(ctx: &ReducerContext, mut game_timer: GameTimer) -> Result<(
GameState::Deal => {
// TODO reduce interval beforehand so this can animate?
// TODO change loop to be per interval somehow?
trace!("deal hands");
let mut wall = ctx.db.wall().lobby_id().find(lobby.id).unwrap();
for pob in &lobby.players {
let mut tiles = wall.tiles.split_off(wall.tiles.len() - 13);
@ -68,6 +68,12 @@ pub fn advance_game(ctx: &ReducerContext, mut game_timer: GameTimer) -> Result<(
hand: tiles,
working_tile: None,
});
ctx.db.player_clock().insert(PlayerClock {
id: 0,
player_id: p.id,
renewable: 5,
total: 30,
});
}
PlayerOrBot::Bot { id } if let Some(mut b) = ctx.db.bot().id().find(id) => {
b.hand = tiles;
@ -77,16 +83,19 @@ pub fn advance_game(ctx: &ReducerContext, mut game_timer: GameTimer) -> Result<(
}
}
lobby.game_state = jong_types::states::GameState::Play;
trace!("dealt hands");
}
GameState::Play => {
trace!("in play");
let curr_player = lobby.players.get(lobby.current_idx as usize).unwrap();
match curr_player {
PlayerOrBot::Player { id: player_id } => {
trace!("current player is {player_id}");
let mut clock = ctx.db.player_clock().player_id().find(player_id).unwrap();
let mut hand = ctx.db.player_hand().player_id().find(player_id).unwrap();
match hand.turn_state {
TurnState::None => {
// TODO draw tile
trace!("draw a tile");
if let Some(mut wall) = ctx.db.wall().lobby_id().find(lobby.id)
&& let Some(tile) = wall.tiles.pop()
{
@ -100,6 +109,7 @@ pub fn advance_game(ctx: &ReducerContext, mut game_timer: GameTimer) -> Result<(
}
}
TurnState::Tsumo => {
trace!("wait for discard");
if clock.tick() {
ctx.db.player_clock().id().update(clock);
} else {
@ -113,7 +123,18 @@ pub fn advance_game(ctx: &ReducerContext, mut game_timer: GameTimer) -> Result<(
}
}
PlayerOrBot::Bot { id: bot_id } => {
let b = ctx.db.bot().id().find(bot_id).unwrap();
debug!("current bot is {bot_id}");
let bot = ctx.db.bot().id().find(bot_id).unwrap();
match bot.turn_state {
// TurnState::None => todo!(),
// TurnState::Tsumo => todo!(),
// TurnState::Menzen => todo!(),
// TurnState::RiichiKan => todo!(),
// TurnState::RonChiiPonKan => todo!(),
// TurnState::End => todo!(),
_ => {}
}
lobby.next_player();
}
}
}
@ -160,3 +181,13 @@ impl PlayerClock {
self.renewable = 5;
}
}
impl Lobby {
fn next_player(&mut self) {
if self.current_idx + 1 >= 4 {
self.current_idx = 0
} else {
self.current_idx += 1;
}
}
}

View file

@ -1,61 +0,0 @@
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<DbTile> {
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);
}
}

View file

@ -11,6 +11,7 @@ pub fn discard_tile(ctx: &ReducerContext, tile_id: u32) -> Result<(), String> {
let player = ctx.db.player().identity().find(ctx.sender).unwrap();
let mut hand = ctx.db.player_hand().player_id().find(player.id).unwrap();
// TODO we can probably remove a buncha these errors
let dealt_tile = if let Some(dealt) = ctx.db.tile().id().find(tile_id) {
if let Some(drawn) = hand.working_tile {
if drawn.id == dealt.id {
@ -49,6 +50,10 @@ pub fn discard_tile(ctx: &ReducerContext, tile_id: u32) -> Result<(), String> {
ctx.db.player_hand().id().update(hand);
let mut lobby = ctx.db.lobby().id().find(player.lobby_id).unwrap();
lobby.next_player();
ctx.db.lobby().id().update(lobby);
debug!("player {} discarded tile {:?}", player.id, dealt_tile.tile);
Ok(())

View file

@ -14,7 +14,7 @@ pub fn join_or_create_lobby(ctx: &ReducerContext, mut lobby_id: u32) -> Result<(
.find(ctx.sender)
.ok_or(format!("cannot find player {}", ctx.sender))?;
if lobby_id == 0 {
if lobby_id == 0 && player.lobby_id == 0 {
// TODO check first if player is already in a lobby
let lobby = ctx.db.lobby().insert(Lobby {
@ -27,10 +27,17 @@ pub fn join_or_create_lobby(ctx: &ReducerContext, mut lobby_id: u32) -> Result<(
info!("created lobby: {}", lobby.id);
lobby_id = lobby.id;
player.lobby_id = lobby_id;
} else {
let lobby = ctx
.db
.lobby()
.id()
.find(player.lobby_id)
.ok_or(format!("can't find lobby {}", player.lobby_id))?;
lobby_id = lobby.id;
}
player.lobby_id = lobby_id;
let player = ctx.db.player().identity().update(player);
info!("player {} joined lobby {}", player.id, lobby_id);

View file

@ -16,7 +16,7 @@ jong-db.path = "../jong-db"
# bevy
bevy.workspace = true
bevy.features = ["default", "dynamic_linking"]
bevy.features = ["default", "dynamic_linking", "debug"]
bevy_ratatui.workspace = true
# spacetimedb

View file

@ -1,6 +1,7 @@
use bevy::prelude::*;
use bevy_spacetimedb::{
ReadInsertUpdateMessage, ReadStdbConnectedMessage, ReadStdbDisconnectedMessage, StdbPlugin,
ReadInsertUpdateMessage, ReadStdbConnectedMessage, ReadStdbDisconnectedMessage,
ReadUpdateMessage, StdbPlugin,
};
use jong_db::{
@ -9,6 +10,7 @@ use jong_db::{
};
use jong_db::{add_bot, set_ready};
use jong_types::*;
use spacetimedb_sdk::Table;
pub mod player;
use crate::riichi::player::*;
@ -25,10 +27,7 @@ impl Plugin for Riichi {
.add_table(RemoteTables::player)
.add_table(RemoteTables::lobby)
// TODO check bevy_spacetimedb PR status
.add_view_with_pk(RemoteTables::view_hand, |p| p.id)
// semicolon stopper
;
.add_view_with_pk(RemoteTables::view_hand, |p| p.id);
let plugins =
if let Some(token) = creds_store().load().expect("i/o error loading credentials") {
// FIXME patch plugin so this takes Option?
@ -40,27 +39,16 @@ impl Plugin for Riichi {
app.add_plugins(plugins)
.init_state::<jong_types::states::GameState>()
.add_sub_state::<jong_types::states::TurnState>()
// .init_resource::<round::MatchSettings>()
// .init_resource::<round::Compass>()
// .add_systems(Startup, tile::init_tiles)
// .add_systems(Update, hand::sort_hands.run_if(in_state(GameState::Play)))
// .add_systems(OnEnter(TurnState::Tsumo), round::tsumo)
// .add_systems(OnEnter(TurnState::Menzen), round::menzen)
// .add_systems(Update, round::riichi_kan.run_if(in_state(TurnState::RiichiKan)))
// .add_systems(Update, round::discard.run_if(in_state(TurnState::Discard)))
// .add_systems(OnEnter(TurnState::RonChiiPonKan), round::notify_callable)
// .add_systems(Update, round::ron_chi_pon_kan.run_if(in_state(TurnState::RonChiiPonKan)).after(round::notify_callable))
// .add_systems(OnEnter(TurnState::End), round::end)
// stdb
.add_systems(Startup, subscriptions)
.add_systems(Update, on_connect)
.add_systems(Update, on_disconnect)
.add_systems(Update, on_player_insert_update)
.add_systems(Update, on_lobby_insert_update)
// .add_systems(OnEnter(GameState::Lobby), join_or_create_lobby)
// semicolon stopper
;
.add_systems(Update, on_player_insert_update)
.add_systems(
Update,
(on_view_hand_update)
.run_if(in_state(GameState::Play).or(in_state(GameState::Deal))),
);
}
}
fn on_connect(stdb: SpacetimeDB, mut messages: ReadStdbConnectedMessage, _commands: Commands) {
@ -102,34 +90,51 @@ fn subscriptions(stdb: SpacetimeDB) {
// .subscribe_to_all_tables();
}
fn on_view_hand_insert_update(
fn on_view_hand_update(
stdb: SpacetimeDB,
mut messages: ReadInsertUpdateMessage<jong_db::PlayerHand>,
mut messages: ReadUpdateMessage<jong_db::PlayerHand>,
mut commands: Commands,
mut hand: Option<Single<&mut Children, With<Hand>>>,
mut hand: Option<Single<(Entity, &Children), With<Hand>>>,
drawn: Option<Single<Entity, With<Drawn>>>,
tiles: Query<&Tile>,
mut next_turnstate: ResMut<NextState<jong_types::states::TurnState>>,
) {
for msg in messages.read() {
if hand.is_none() {
let hand_tiles: Vec<_> = msg
.new
.hand
.iter()
.map(|dbt| commands.spawn((Tile::from(&dbt.tile), TileId(dbt.id))).id())
.collect();
commands.spawn(Hand).add_children(&hand_tiles);
}
// let mut hand = hand.and_then(|h| Some(*h));
// match msg.new.turn_state {
// jong_db::TurnState::None => todo!(),
// jong_db::TurnState::Tsumo => todo!(),
// jong_db::TurnState::Menzen => todo!(),
// jong_db::TurnState::RiichiKan => todo!(),
// jong_db::TurnState::RonChiiPonKan => todo!(),
// jong_db::TurnState::End => todo!(),
// }
if hand.is_none()
&& let Some(player_hand) = stdb.db().view_hand().iter().next()
{
let hand_tiles: Vec<_> = player_hand
.hand
.iter()
.map(|dbt| commands.spawn((Tile::from(&dbt.tile), TileId(dbt.id))).id())
.collect();
let hand_ent = commands.spawn(Hand).add_children(&hand_tiles).id();
debug!("hand_tiles: {hand_tiles:?}");
// hand = Some(hand_ent);
}
for msg in messages.read() {
// trace!("new hand: {:?}", msg.new);
match msg.new.turn_state {
jong_db::TurnState::None => {
// TODO do we reconcile hand state here or in ::End?
}
jong_db::TurnState::Tsumo => {
let dbt = msg
.new
.working_tile
.as_ref()
.expect("entered tsumo without a drawn tile");
commands.spawn((Drawn, Tile::from(&dbt.tile), TileId(dbt.id)));
}
jong_db::TurnState::Menzen => todo!(),
jong_db::TurnState::RiichiKan => todo!(),
jong_db::TurnState::RonChiiPonKan => todo!(),
jong_db::TurnState::End => todo!(),
}
next_turnstate.set(msg.new.turn_state.into());
}

View file

@ -71,11 +71,11 @@ impl Plugin for TuiPlugin {
open: true,
})
.init_state::<states::TuiState>()
.add_message::<ConfirmSelect>()
.configure_sets(
Update,
(TuiSet::Input, TuiSet::Layout, TuiSet::Render).chain(),
)
.add_message::<ConfirmSelect>()
.add_systems(
Update,
(input::keyboard, input::mouse).in_set(TuiSet::Input),
@ -85,7 +85,11 @@ impl Plugin for TuiPlugin {
.add_systems(
Update,
(
(render::render_hand, render::render_pond).run_if(in_state(GameState::Play)),
(
render::render_hand,
render::render_pond,
)
.run_if(in_state(GameState::Play)),
render::render,
)
.chain()
@ -102,7 +106,8 @@ fn discard_tile(
drawn: Single<(Entity, &TileId), With<Drawn>>,
tiles: Query<&TileId>,
) {
while let Some(message) = selected.read().next() {
// FIXME why is this not consuming the messages?
while let Some(message) = selected.read().last() {
if let Ok(tile_id) = tiles.get(message.0) {
stdb.reducers().discard_tile(tile_id.0).unwrap();
commands.entity(drawn.0).remove::<Drawn>();

View file

@ -41,6 +41,7 @@ pub(crate) fn keyboard(
match curr_tuistate.get() {
TuiState::MainMenu => match key {
KeyCode::Char('p') => {
// TODO this should be a msg/signal and handle the correct lobby
stdb.reducers().join_or_create_lobby(0).unwrap();
next_tuistate.set(TuiState::InGame);
}

View file

@ -93,6 +93,21 @@ pub(crate) fn render(
Ok(())
}
pub(crate) fn query_tester(
mut commands: Commands,
mut tui: ResMut<RatatuiContext>,
hovered: Query<Entity, With<Hovered>>,
layouts: Res<HandLayouts>,
tiles: Query<&jong_types::Tile>,
// main_player: Single<(&Player, Entity /* , &Wind */), With<MainPlayer>>,
hand: Single<(&Children, Entity), With<Hand>>,
drawn_tile: Option<Single<Entity, With<Drawn>>>,
) {
trace!("owo")
}
// FIXME we don't care about other players atm
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
pub(crate) fn render_hand(