Skip to content

Commit

Permalink
fix: lastMove Bug (#85)
Browse files Browse the repository at this point in the history
change that LastMove of Hares is now collected from the lastMove, not lastAction
change LastMove attributes to accommodate lists of cards
add last_move globally to the game_state
  • Loading branch information
YoEnte authored Jan 1, 2025
1 parent a4bd343 commit 5944560
Show file tree
Hide file tree
Showing 9 changed files with 49 additions and 17 deletions.
3 changes: 2 additions & 1 deletion python/socha/_socha.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -385,9 +385,10 @@ class GameState:

board: Board
turn: int
last_move: Optional[Move]

def __init__(
self, board: Board, turn: int, player_one: Hare, player_two: Hare
self, board: Board, turn: int, player_one: Hare, player_two: Hare, last_move: Optional[Move]
) -> None: ...
def perform_move(self, move: Move) -> GameState:
"""
Expand Down
6 changes: 5 additions & 1 deletion python/socha/api/networking/game_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,11 @@ def _on_move_request(self, room_id):
logging.error(f'{move_response} is not a valid move.')

def _on_state(self, message):
_state = message_to_state(message)
second_last_move = None # last move from last gamestate
if len(self._game_handler.history[-1]) > 0 and isinstance(self._game_handler.history[-1][-1], GameState):
second_last_move = self._game_handler.history[-1][-1].last_move

_state = message_to_state(message, second_last_move)
self._game_handler.history[-1].append(_state)
self._game_handler.on_update(_state)

Expand Down
27 changes: 23 additions & 4 deletions python/socha/api/networking/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,29 +92,47 @@ def handle_move(move_response: _socha.Move) -> Data:
raise ValueError(f'Unknown move response action: {move_response.action}')


def message_to_state(message: Room) -> _socha.GameState:
def message_to_state(message: Room, second_last_move: _socha.Move) -> _socha.GameState:
"""
Constructs a GameState from the provided message, ensuring to reflect the
current state based on the ships' positions, teams, and other attributes.
Args:
message: The input message containing the current game state.
second_last_move: the last_move object from the last game state before this game state
Returns:
GameState: The constructed game state from the message.
"""


state: State = message.data.class_binding

# extract last move of current gameState
state_last_move = _socha.Move(action=state.last_move.class_binding) if state.last_move and state.last_move.class_binding else None

def create_hare(hare: Hare) -> _socha.Hare:

players_last_move = None

if state.turn % 2 == 0: # now is ONE at turn, last turn was None or TWO
if hare.team == 'ONE':
players_last_move = second_last_move
else:
players_last_move = state_last_move
else:
if hare.team == 'TWO':
players_last_move = second_last_move
else:
players_last_move = state_last_move

return _socha.Hare(
cards=[map_string_to_card(card) for card in hare.cards.card]
if hare.cards
else [],
carrots=hare.carrots,
position=hare.position,
last_move=_socha.Move(action=hare.last_action.class_binding)
if hare.last_action and hare.last_action.class_binding
else None,
last_move=players_last_move,
salads=hare.salads,
team=_socha.TeamEnum.One if hare.team == 'ONE' else _socha.TeamEnum.Two,
)
Expand All @@ -124,4 +142,5 @@ def create_hare(hare: Hare) -> _socha.Hare:
player_one=create_hare(state.hare[0]),
player_two=create_hare(state.hare[1]),
turn=state.turn,
last_move=state_last_move,
)
10 changes: 6 additions & 4 deletions python/socha/api/networking/xml_protocol_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,17 @@
from xsdata.formats.dataclass.serializers import XmlSerializer
from xsdata.formats.dataclass.serializers.config import SerializerConfig

from socha.api.protocol.protocol import Data, LastAction
from socha.api.protocol.protocol import Data, LastAction, LastMove


def map_object(data: Data | LastAction, params: dict):
def map_object(data: Data | LastAction | LastMove, params: dict):
try:
params.pop('class_binding')
except KeyError:
...
if params.get('class_value') == 'welcomeMessage':
welcome_message = WelcomeMessage(
_socha.TeamEnum.One if params.get('name') == 'ONE' else _socha.TeamEnum.Two
_socha.TeamEnum.One if params.get('color') == 'ONE' else _socha.TeamEnum.Two
)
return data(class_binding=welcome_message, **params)
elif params.get('class_value') == 'memento':
Expand Down Expand Up @@ -71,14 +71,16 @@ def map_object(data: Data | LastAction, params: dict):
elif params.get('class_value') == 'eatsalad':
salad_object = _socha.EatSalad()
return data(class_binding=salad_object, **params)
elif params.get('class_value') == 'card': # work around for LastAction, because buggy and now prevents warning
return data(**params)
else:
logging.warn('Unknown class value: %s', params.get('class_value'))

return data(**params)


def custom_class_factory(clazz, params: dict):
if clazz.__name__ == 'Data' or clazz.__name__ == 'LastAction':
if clazz.__name__ == 'Data' or clazz.__name__ == 'LastAction' or clazz.__name__ == 'LastMove':
return map_object(clazz, params)

return clazz(**params)
Expand Down
3 changes: 2 additions & 1 deletion python/socha/api/protocol/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,14 @@ class Meta:
'required': True,
},
)
class_binding: Optional[object] = field(default=None)
distance: Optional[int] = field(
default=None,
metadata={
'type': 'Attribute',
},
)
card: Optional[str] = field(
card: Optional[List[str]] = field(
default=None,
metadata={
'type': 'Element',
Expand Down
9 changes: 6 additions & 3 deletions src/plugin/game_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,20 @@ pub struct GameState {
pub turn: usize,
player_one: Hare,
player_two: Hare,
#[pyo3(get, set)]
pub last_move: Option<Move>
}

#[pymethods]
impl GameState {
#[new]
pub fn new(board: Board, turn: usize, player_one: Hare, player_two: Hare) -> Self {
pub fn new(board: Board, turn: usize, player_one: Hare, player_two: Hare, last_move: Option<Move>) -> Self {
Self {
board,
turn,
player_one,
player_two,
last_move,
}
}

Expand Down Expand Up @@ -192,8 +195,8 @@ impl std::fmt::Display for GameState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"GameState(board={}, turn={}, player_one={}, player_two={})",
self.board, self.turn, self.player_one, self.player_two
"GameState(board={}, turn={}, player_one={}, player_two={}, last_move={:?})",
self.board, self.turn, self.player_one, self.player_two, self.last_move
)
}
}
4 changes: 2 additions & 2 deletions src/plugin/test/advance_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ mod tests {
None,
Some(3),
);
GameState::new(board, 0, player_one, player_two)
GameState::new(board, 0, player_one, player_two, None)
}

#[test]
Expand Down Expand Up @@ -93,7 +93,7 @@ mod tests {
Some(0),
);

let mut state = GameState::new(board, 0, player_one, player_two);
let mut state = GameState::new(board, 0, player_one, player_two, None);

let advance = Advance::new(2, vec![]);

Expand Down
2 changes: 1 addition & 1 deletion src/plugin/test/card_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ mod tests {
None,
Some(3),
);
GameState::new(board, 0, player_one, player_two)
GameState::new(board, 0, player_one, player_two, None)
}

#[test]
Expand Down
2 changes: 2 additions & 0 deletions src/plugin/test/state_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ mod tests {
20,
create_player(TeamEnum::One, 2, vec![Card::EatSalad], 37, 1),
create_player(TeamEnum::Two, 6, vec![], 11, 1),
None,
);
let moves = state.possible_moves();
assert!(moves.contains(&Move::new(Action::Advance(Advance::new(
Expand All @@ -70,6 +71,7 @@ mod tests {
0,
),
create_player(TeamEnum::Two, 6, vec![], 11, 0),
None,
);
let moves = state.possible_moves();

Expand Down

0 comments on commit 5944560

Please sign in to comment.