Fix remote client (#242)

This commit is contained in:
Gregor Zeitlinger 2025-05-04 13:14:56 +02:00 • committed by GitHub
commit 3536fc63b7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 139 additions and 90 deletions

View file

@ -16,6 +16,6 @@ jobs:
with:
experimental: 'true' # to get lock file support
env:
MISE_DISABLE_TOOLS: cargo:wasm-pack,cargo:wasm-bindgen-cli
MISE_DISABLE_TOOLS: cargo:wasm-pack,cargo:wasm-bindgen-cli,node
- name: Random actions test
run: mise run random-actions

View file

@ -16,6 +16,6 @@ jobs:
with:
experimental: 'true' # to get lock file support
env:
MISE_DISABLE_TOOLS: cargo:wasm-pack,cargo:wasm-bindgen-cli
MISE_DISABLE_TOOLS: cargo:wasm-pack,cargo:wasm-bindgen-cli,node
- name: Check all
run: mise run ci-client

View file

@ -16,6 +16,6 @@ jobs:
with:
experimental: 'true' # to get lock file support
env:
MISE_DISABLE_TOOLS: cargo:wasm-pack,cargo:wasm-bindgen-cli
MISE_DISABLE_TOOLS: cargo:wasm-pack,cargo:wasm-bindgen-cli,node
- name: Check all
run: mise run ci-server

View file

@ -13,7 +13,7 @@
- `./scripts/build-remote-client.sh`
- `cd client/js/dist && basic-http-server .`
- `google-chrome --disable-web-security --user-data-dir=/tmp http://localhost:8612`
- `google-chrome --js-flags='--stack-trace-limit 100' --disable-web-security --user-data-dir=/tmp http://localhost:8612`
### Server wrapper
@ -41,7 +41,7 @@
old
- https://github.com/boardgamers/boardgamers-mono/blob/683f4d473586ffe359ad7e58f7bf08d95c96d821/.gitpod.yml#L12-L18 (if
you have't already)
you haven't already)
- This will create three users, with emails admin@test.com, user@test.com and user2@test.com, and "password"
password".

View file

@ -8,7 +8,7 @@ use macroquad::window::screen_height;
use server::action::execute_action;
use server::advance::{Advance, do_advance};
use server::city::City;
use server::game::{Game, GameData};
use server::game::{Game, GameContext, GameData};
use server::game_setup::setup_game;
use server::map::Terrain;
use server::player::add_unit;
@ -332,7 +332,7 @@ fn import(game: Game) -> Game {
let file = File::open(EXPORT_FILE).expect("Failed to open export file");
let reader = BufReader::new(file);
let data: GameData = serde_json::from_reader(reader).expect("Failed to read export file");
Game::from_data(data, game.cache)
Game::from_data(data, game.cache, GameContext::Server)
}
fn export(game: &Game) {

View file

@ -1,4 +1,4 @@
use server::game::Game;
use server::game::{Game, GameContext};
use macroquad::prelude::next_frame;
@ -39,7 +39,7 @@ extern "C" {
fn receive_player_index(this: &Control) -> JsValue;
#[wasm_bindgen(method)]
fn send_move(this: &Control, action: JsValue);
fn send_move(this: &Control, action: String);
#[wasm_bindgen(method)]
fn send_ready(this: &Control);
@ -129,19 +129,25 @@ impl RemoteClient {
fn update_state(&mut self) -> GameSyncResult {
let s = self.control.receive_state();
if s.is_object() {
log("received state");
let cache = self.game.take().map_or_else(Cache::new, |g| g.cache);
let g = Game::from_data(
serde_wasm_bindgen::from_value(s).expect("game should be of type game data"),
cache,
);
self.state.show_player = g.active_player();
self.game = Some(g);
self.sync_state = SyncState::Playing;
self.control.send_ready();
return GameSyncResult::Update;
if !s.is_null() {
if let Some(state) = s.as_string() {
log("received state");
let cache = self.game.take().map_or_else(Cache::new, |g| g.cache);
let g = Game::from_data(
serde_json::from_str(&state).expect("game should be of type game data"),
cache,
GameContext::Client,
);
self.state.show_player = g.active_player();
self.game = Some(g);
self.sync_state = SyncState::Playing;
self.control.send_ready();
return GameSyncResult::Update;
} else {
log("received state but it was not a string");
}
}
match &self.sync_state {
SyncState::New => GameSyncResult::None,
SyncState::WaitingForUpdate => GameSyncResult::WaitingForUpdate,
@ -151,8 +157,7 @@ impl RemoteClient {
fn execute_action(&mut self, a: &Action) {
if let SyncState::Playing = &self.sync_state {
self.control
.send_move(serde_wasm_bindgen::to_value(&a).unwrap());
self.control.send_move(serde_json::to_string(&a).unwrap());
self.sync_state = SyncState::WaitingForUpdate;
} else {
log("cannot execute action");

View file

@ -74,7 +74,7 @@ run = "./scripts/build-remote-server.sh test"
[tasks.build-remote-client]
description = "Build remote client"
run = "./scripts/build-remote-client.sh --release"
run = "./scripts/build-remote-client.sh"
[tasks.test-pubish-server]
description = "Test publish server (the real one is done in GitHub Actions)"

View file

@ -12,7 +12,7 @@ use crate::content::persistent_events::{EventResponse, PersistentEventType};
use crate::cultural_influence::on_cultural_influence;
use crate::explore::{ask_explore_resolution, move_to_unexplored_tile};
use crate::game::GameState::{Finished, Movement, Playing};
use crate::game::{Game, GameState};
use crate::game::{Game, GameContext, GameState};
use crate::incident::{on_choose_incident, on_trigger_incident};
use crate::log;
use crate::log::{add_action_log_item, current_player_turn_log_mut};
@ -73,7 +73,7 @@ pub enum ActionType {
pub fn execute_action(mut game: Game, action: Action, player_index: usize) -> Game {
assert_eq!(player_index, game.active_player(), "Not your turn");
if game.ai_mode {
if game.context == GameContext::AI {
execute_without_undo(&mut game, action, player_index).expect("action should be executed");
return game;
}

View file

@ -8,6 +8,7 @@ use tokio::runtime::Runtime;
use crate::ai_actions::AiActions;
use crate::cache::Cache;
use crate::game::GameContext;
use crate::movement::MovementAction;
use crate::{
action::{self, Action, ActionType},
@ -313,9 +314,7 @@ fn monte_carlo_score(
}
fn game_from_data(game_data: GameData, cache: Cache) -> Game {
let mut game = Game::from_data(game_data, cache);
game.ai_mode = true;
game
Game::from_data(game_data, cache, GameContext::AI)
}
fn monte_carlo_run(

View file

@ -510,7 +510,7 @@ pub mod tests {
use crate::action::Action;
use crate::cache::Cache;
use crate::game::GameState;
use crate::game::{GameContext, GameState};
use crate::log::{ActionLogAge, ActionLogItem, ActionLogPlayer, ActionLogRound};
use crate::movement::MovementAction;
use crate::utils::tests::FloatEq;
@ -535,6 +535,7 @@ pub mod tests {
round.players.push(log);
age.rounds.push(round);
Game {
context: GameContext::Server,
cache: Cache::new(),
state: GameState::Playing,
events: Vec::new(),
@ -546,7 +547,6 @@ pub mod tests {
action_log_index: 0,
log: Vec::new(),
undo_limit: 0,
ai_mode: false,
actions_left: 3,
successful_cultural_influence: false,
round: 1,

View file

@ -55,6 +55,22 @@ fn pestilence() -> Incident {
.add_simple_incident_listener(IncidentTarget::ActivePlayer, 0, |game, _, _, _| {
game.permanent_effects.push(PermanentEffect::Pestilence);
})
.add_simple_persistent_event_listener(
|event| &mut event.advance,
11,
|game, _player_index, _player_name, i| {
if i.advance == Advance::Sanitation
&& game
.players
.iter()
.all(|p| !p.is_human() || p.has_advance(Advance::Sanitation))
{
game.permanent_effects
.retain(|e| e != &PermanentEffect::Pestilence);
game.add_info_log_item("Pestilence removed");
}
},
)
.build()
}

View file

@ -34,7 +34,15 @@ use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::vec;
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum GameContext {
Client,
Server,
AI,
}
pub struct Game {
pub context: GameContext, // trasient
pub cache: Cache,
pub state: GameState,
pub events: Vec<PersistentEventState>,
@ -48,7 +56,6 @@ pub struct Game {
pub action_log_index: usize,
pub log: Vec<Vec<String>>,
pub undo_limit: usize,
pub ai_mode: bool,
pub actions_left: u32,
pub successful_cultural_influence: bool,
pub round: u32, // starts at 1
@ -69,9 +76,7 @@ pub struct Game {
impl Clone for Game {
fn clone(&self) -> Self {
let mut game = Self::from_data(self.cloned_data(), self.cache.clone());
game.ai_mode = self.ai_mode;
game
Self::from_data(self.cloned_data(), self.cache.clone(), self.context.clone())
}
}
@ -88,8 +93,9 @@ impl Game {
///
/// Panics if any wonder does not exist
#[must_use]
pub fn from_data(data: GameData, cache: Cache) -> Self {
pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Self {
let mut game = Self {
context,
cache,
state: data.state,
players: Vec::new(),
@ -102,7 +108,6 @@ impl Game {
action_log_index: data.action_log_index,
log: data.log,
undo_limit: data.undo_limit,
ai_mode: false,
round: data.round,
age: data.age,
messages: data.messages,
@ -233,7 +238,7 @@ impl Game {
}
pub(crate) fn lock_undo(&mut self) {
if !self.ai_mode {
if self.context != GameContext::AI {
self.undo_limit = self.action_log_index;
current_player_turn_log_mut(self).clear_undo();
}
@ -414,7 +419,7 @@ impl Game {
#[must_use]
pub(crate) fn execute_cost_trigger(&self) -> CostTrigger {
if self.ai_mode {
if self.context == GameContext::AI {
CostTrigger::NoModifiers
} else {
CostTrigger::WithModifiers
@ -423,12 +428,13 @@ impl Game {
#[must_use]
pub fn can_undo(&self) -> bool {
!self.ai_mode && self.undo_limit < self.action_log_index
self.context != GameContext::AI && self.undo_limit < self.action_log_index
}
#[must_use]
pub fn can_redo(&self) -> bool {
!self.ai_mode && self.action_log_index < current_player_turn_log(self).items.len()
self.context != GameContext::AI
&& self.action_log_index < current_player_turn_log(self).items.len()
}
pub(crate) fn is_pirate_zone(&self, position: Position) -> bool {
@ -766,16 +772,3 @@ pub enum GameState {
Movement(MoveState),
Finished,
}
#[derive(Serialize, Deserialize)]
pub struct Messages {
messages: Vec<String>,
data: GameData,
}
impl Messages {
#[must_use]
pub fn new(messages: Vec<String>, data: GameData) -> Self {
Self { messages, data }
}
}

View file

@ -1,5 +1,4 @@
use std::{cmp::Ordering::*, mem};
use super::player::Player;
use crate::action::execute_action;
use crate::content::effects::PermanentEffect;
use crate::content::persistent_events::{
@ -10,10 +9,11 @@ use crate::log::current_player_turn_log_mut;
use crate::utils::Shuffle;
use crate::{
action::Action,
game::{Game, GameState::*, Messages},
game::{Game, GameState::*},
log::LogSliceOptions,
utils::Rng,
};
use std::cmp::Ordering::*;
// Game API methods, see https://docs.boardgamers.space/guide/engine-api.html#required-methods
#[must_use]
@ -33,11 +33,11 @@ pub fn ended(game: &Game) -> bool {
#[must_use]
pub fn scores(game: &Game) -> Vec<f32> {
let mut scores: Vec<f32> = Vec::new();
for player in &game.players {
scores.push(player.victory_points(game));
}
scores
game.players
.iter()
.filter(|p| p.is_human())
.map(|player| player.victory_points(game))
.collect()
}
#[must_use]
@ -78,6 +78,9 @@ pub fn set_player_name(mut game: Game, player_index: usize, name: String) -> Gam
pub fn rankings(game: &Game) -> Vec<u32> {
let mut rankings = Vec::new();
for player in &game.players {
if !player.is_human() {
continue;
}
let mut rank = 1;
for other in &game.players {
if other.compare_score(player, game) == Greater {
@ -101,6 +104,7 @@ pub fn round(game: &Game) -> Option<u32> {
pub fn civilizations(game: Game) -> Vec<String> {
game.players
.into_iter()
.filter(Player::is_human)
.map(|player| player.civilization.name)
.collect()
}
@ -168,9 +172,3 @@ pub fn strip_secret(mut game: Game, player_index: Option<usize>) -> Game {
game
}
#[must_use]
pub fn messages(mut game: Game) -> Messages {
let messages = mem::take(&mut game.messages);
Messages::new(messages, game.data())
}

View file

@ -1,8 +1,10 @@
#![allow(clippy::pedantic)]
use crate::cache::Cache;
use crate::game::GameContext;
use crate::{game::Game, game_api};
use serde::{Deserialize, Serialize};
use std::mem;
use wasm_bindgen::prelude::*;
extern crate console_error_panic_hook;
@ -17,6 +19,7 @@ fn get_game(data: String) -> Game {
Game::from_data(
serde_json::from_str(&data).expect("Could not deserialize game data"),
Cache::new(),
GameContext::Server,
)
}
@ -37,9 +40,9 @@ pub async fn init(
}
#[wasm_bindgen(js_name = move)]
pub fn execute_move(game: String, move_data: JsValue, player_index: usize) -> String {
pub fn execute_move(game: String, move_data: String, player_index: usize) -> String {
let game = get_game(game);
let action = serde_wasm_bindgen::from_value(move_data).expect("move should be of type action");
let action = serde_json::from_str(&move_data).expect("move should be of type action");
let game = game_api::execute(game, action, player_index);
from_game(game)
}
@ -132,7 +135,20 @@ pub fn strip_secret(game: String, player_index: Option<usize>) -> String {
#[wasm_bindgen]
pub fn messages(game: String) -> JsValue {
let game = get_game(game);
let messages = game_api::messages(game);
let mut game = get_game(game);
let messages = Messages::new(mem::take(&mut game.messages), from_game(game));
serde_wasm_bindgen::to_value(&messages).expect("messages should be serializable")
}
#[derive(Serialize, Deserialize)]
pub struct Messages {
messages: Vec<String>,
data: String,
}
impl Messages {
#[must_use]
pub fn new(messages: Vec<String>, data: String) -> Self {
Self { messages, data }
}
}

View file

@ -4,7 +4,7 @@ use crate::cache::Cache;
use crate::consts::{ACTIONS, NON_HUMAN_PLAYERS};
use crate::content::civilizations::{BARBARIANS, PIRATES};
use crate::content::{builtin, civilizations};
use crate::game::{Game, GameState};
use crate::game::{Game, GameContext, GameState};
use crate::map::Map;
use crate::objective_card::gain_objective_card_from_pile;
use crate::player::{Player, add_unit};
@ -82,6 +82,7 @@ pub fn setup_game_with_cache(
.shuffled(&mut rng);
let all = &cache.get_builtins().clone();
let mut game = Game {
context: GameContext::Server,
cache,
state: GameState::Playing,
events: Vec::new(),
@ -96,7 +97,6 @@ pub fn setup_game_with_cache(
.map(|s| vec![s.clone()])
.collect(),
undo_limit: 0,
ai_mode: false,
actions_left: ACTIONS,
successful_cultural_influence: false,
round: 1,

View file

@ -4,6 +4,7 @@ use crate::ability_initializer::{
use crate::cache::Cache;
use crate::card::{HandCard, draw_card_from_pile};
use crate::content::builtin::Builtin;
use crate::content::effects::PermanentEffect;
use crate::content::incidents::great_persons::find_great_seer;
use crate::content::persistent_events::{HandCardsRequest, PersistentEventType};
use crate::events::EventOrigin;
@ -402,6 +403,27 @@ pub(crate) fn gain_objective_card_from_pile(game: &mut Game, player: usize) {
}
pub(crate) fn draw_and_log_objective_card_from_pile(game: &mut Game, player: usize) -> Option<u8> {
draw_great_seer_card(game, player).or_else(|| {
let card = draw_card_from_pile(
game,
"Objective Card",
|g| &mut g.objective_cards_left,
|g| g.cache.get_objective_cards().iter().map(|c| c.id).collect(),
|p| p.objective_cards.clone(),
);
if card.is_some() {
game.add_info_log_item(&format!(
"{} gained an objective card from the pile",
game.player_name(player)
));
}
card
})
}
fn draw_great_seer_card(game: &mut Game, player: usize) -> Option<u8> {
let mut remove_great_seer = false;
let mut result = None;
if let Some(great_seer) = find_great_seer(game) {
if let Some(o) = great_seer.assigned_objectives.iter().find_map(|o| {
if o.player == player {
@ -412,28 +434,22 @@ pub(crate) fn draw_and_log_objective_card_from_pile(game: &mut Game, player: usi
}) {
remove_element(&mut great_seer.assigned_objectives, &o)
.unwrap_or_else(|| panic!("should be able to remove objective card {o:?}"));
remove_great_seer = great_seer.assigned_objectives.is_empty();
game.add_info_log_item(&format!(
"{} gained the Great Seer objective card from the pile",
game.player_name(player)
));
return Some(o.objective_card);
result = Some(o.objective_card);
}
}
let card = draw_card_from_pile(
game,
"Objective Card",
|g| &mut g.objective_cards_left,
|g| g.cache.get_objective_cards().iter().map(|c| c.id).collect(),
|p| p.objective_cards.clone(),
);
if card.is_some() {
game.add_info_log_item(&format!(
"{} gained an objective card from the pile",
game.player_name(player)
));
if remove_great_seer {
remove_element_by(&mut game.permanent_effects, |e| {
matches!(e, PermanentEffect::GreatSeer(_))
})
.unwrap_or_else(|| panic!("should be able to remove great seer"));
}
card
result
}
pub(crate) fn gain_objective_card(game: &mut Game, player_index: usize, objective_card: u8) {

View file

@ -122,6 +122,10 @@ impl Player {
}
for id in objective_cards {
if id == 0 {
// hidden
continue;
}
init_objective_card(game, player_index, id);
}

View file

@ -40,6 +40,7 @@ pub(crate) fn undo(mut game: Game) -> Result<Game, String> {
Ok(Game::from_data(
serde_json::from_value(v).map_err(|e| format!("Failed to deserialize game: {e}"))?,
game.cache,
game.context,
))
}

View file

@ -4,7 +4,7 @@ use server::action::Action;
use server::cache::Cache;
use server::city_pieces::Building::Temple;
use server::content::persistent_events::{SelectedStructure, Structure};
use server::game::Game;
use server::game::{Game, GameContext};
use server::log::current_player_turn_log_mut;
use server::movement::MoveUnits;
use server::movement::MovementAction::Move;
@ -419,6 +419,7 @@ pub fn load_game(path: &GamePath) -> Game {
serde_json::from_str(&read_game_str(path))
.unwrap_or_else(|e| panic!("the game file should be deserializable {path}: {e}",)),
Cache::new(),
GameContext::Server,
);
if update_expected() {
write_result(&to_json(&game), path);

View file

@ -62,7 +62,7 @@ async fn test_random_actions() {
fn random_actions_iteration(mut rng: Rng, cache: Cache) {
let seed = rng.range(0, 10_usize.pow(15)).to_string();
let mut game = game_setup::setup_game_with_cache(2, seed, true, cache);
game.ai_mode = true;
game.context = GameContext::AI;
let mut ai_actions = AiActions::new();
loop {
if matches!(game.state, GameState::Finished) {