Skip to content

Commit

Permalink
Fix google-deepmind#1254: Convert pyspiel game state to dict
Browse files Browse the repository at this point in the history
  • Loading branch information
Ayah-Saleh committed Sep 26, 2024
1 parent 08543bd commit 2cb0170
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
11 changes: 11 additions & 0 deletions open_spiel/spiel.h
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,17 @@ class State {
public:
virtual ~State() = default;

// convert from current state to a dictionary of array-likes
virtual std::unordered_map<std::string, std::vector<float>> ToDict() const {
SpielFatalError("ToDict is not implemented for this game state.");
}

// method to restore the state from a dictionary of array-likes.
virtual void FromDict(const std::unordered_map<std::string, std::vector<float>>& dict) {
SpielFatalError("FromDict is not implemented for this game state.");
}


// Derived classes must call one of these constructors. Note that a state must
// be passed a pointer to the game which created it. Some methods in some
// games rely on this and so it must correspond to a valid game object.
Expand Down
24 changes: 24 additions & 0 deletions open_spiel/tests/spiel_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,28 @@ void PolicySerializationTest() {
} // namespace testing
} // namespace open_spiel

void TestStateToDictAndFromDict() {
// Load Tic-Tac-Toe
std::shared_ptr<const Game> game = LoadGame("tic_tac_toe");
std::unique_ptr<State> state = game->NewInitialState();

// apply some moves to change the state
state->ApplyAction(0); // Player 1 places an 'X' in the top-left corner
state->ApplyAction(4); // Player 2 places an 'O' in the center

// convert the state to a dictionary using ToDict()
std::unordered_map<std::string, std::vector<float>> state_dict = state->ToDict();

// create a new initial state and restore it using FromDict()
std::unique_ptr<State> new_state = game->NewInitialState();
new_state->FromDict(state_dict);

// check that the original state and the restored state are equivalent
SPIEL_CHECK_EQ(state->ToString(), new_state->ToString());

}


int main(int argc, char** argv) {
open_spiel::testing::GeneralTests();
open_spiel::testing::KuhnTests();
Expand All @@ -349,4 +371,6 @@ int main(int argc, char** argv) {
open_spiel::testing::LeducPokerDeserializeTest();
open_spiel::testing::GameParametersTest();
open_spiel::testing::PolicySerializationTest();
// new test function
open_spiel::testing::TestStateToDictAndFromDict();
}

0 comments on commit 2cb0170

Please sign in to comment.