Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #1254: Convert pyspiel game state to dict #1279

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
}