Exemple #1
0
def main(_):
  games_list = pyspiel.registered_games()
  print("Registered games:")
  for game in games_list:
    print(" ", game.short_name)
  print()

  print("Creating game:", FLAGS.game)
  params = {}
  if FLAGS.players is not None:
    params["players"] = FLAGS.players
  game = pyspiel.load_game(FLAGS.game, params)

  print("Getting all states; depth_limit = {}".format(FLAGS.depth_limit))
  all_states = get_all_states.get_all_states(game, FLAGS.depth_limit,
                                             FLAGS.include_terminals,
                                             FLAGS.include_chance_states)

  count = 0
  for state in all_states:
    print(state)
    count += 1

  print()
  print("Total: {} states.".format(count))
def main(_):
    games_list = pyspiel.registered_games()
    print("Registered games:")
    print(games_list)

    print("Creating game: " + FLAGS.game)
    if FLAGS.players is not None:
        # If passing parameters, must use game creator.
        game = pyspiel.load_game(
            FLAGS.game, {"players": pyspiel.GameParameter(FLAGS.players)})
    else:
        # Otherwise can create directly.
        game = pyspiel.load_game(FLAGS.game)

    print("Getting all states; depth_limit = {}".format(FLAGS.depth_limit))
    all_states = get_all_states.get_all_states(game, FLAGS.depth_limit,
                                               FLAGS.include_terminals,
                                               FLAGS.include_chance_states)

    count = 0
    for state in all_states:
        print("")
        print(str(state))
        count += 1

    print("")
    print("Total: {} states.".format(count))
Exemple #3
0
 def test_registered_game_attributes(self):
     games = {game.short_name: game for game in pyspiel.registered_games()}
     self.assertEqual(games["kuhn_poker"].dynamics,
                      pyspiel.GameType.Dynamics.SEQUENTIAL)
     self.assertEqual(games["kuhn_poker"].chance_mode,
                      pyspiel.GameType.ChanceMode.EXPLICIT_STOCHASTIC)
     self.assertEqual(games["kuhn_poker"].information,
                      pyspiel.GameType.Information.IMPERFECT_INFORMATION)
     self.assertEqual(games["kuhn_poker"].utility,
                      pyspiel.GameType.Utility.ZERO_SUM)
     self.assertEqual(games["kuhn_poker"].min_num_players, 2)
def main(_):
    games_list = pyspiel.registered_games()
    print("Registered games:")
    print(games_list)

    # Load a two-player normal-form game as a two-player matrix game.
    blotto_matrix_game = pyspiel.load_matrix_game("blotto")
    print(
        "Number of rows in 2-player Blotto with default settings is {}".format(
            blotto_matrix_game.num_rows()))

    # Several ways to load/create the same game of matching pennies.
    print("Creating matrix game...")
    game = pyspiel.load_matrix_game("matrix_mp")
    game = _manually_create_game()
    game = _import_data_create_game()
    game = _easy_create_game()
    game = _even_easier_create_game()

    # Quick test: inspect top-left utility values:
    print("Values for joint action ({},{}) is {},{}".format(
        game.row_action_name(0), game.col_action_name(0),
        game.player_utility(0, 0, 0), game.player_utility(1, 0, 0)))

    state = game.new_initial_state()

    # Print the initial state
    print("State:")
    print(str(state))

    assert state.is_simultaneous_node()

    # Simultaneous node: sample actions for all players.
    chosen_actions = [
        random.choice(state.legal_actions(pid))
        for pid in range(game.num_players())
    ]
    print("Chosen actions: ", [
        state.action_to_string(pid, action)
        for pid, action in enumerate(chosen_actions)
    ])
    state.apply_actions(chosen_actions)

    assert state.is_terminal()

    # Game is now done. Print utilities for each player
    returns = state.returns()
    for pid in range(game.num_players()):
        print("Utility for player {} is {}".format(pid, returns[pid]))
Exemple #5
0
    def test_no_mandatory_parameters(self):
        # Games with mandatory parameters will be skipped by several standard
        # tests. Mandatory parameters should therefore be avoided if at all
        # possible. We make a list of such games here in order to make implementors
        # think twice about adding mandatory parameters.
        def has_mandatory_params(game):
            return any(param.is_mandatory()
                       for param in game.parameter_specification.values())

        games_with_mandatory_parameters = [
            game.short_name for game in pyspiel.registered_games()
            if has_mandatory_params(game)
        ]
        expected = [
            # Mandatory parameters prevent various sorts of automated testing.
            # Only add games here if there is no sensible default for a parameter.
            "misere",
            "turn_based_simultaneous_game",
        ]
        self.assertCountEqual(games_with_mandatory_parameters, expected)
Exemple #6
0
 def teste_default_loadable(self):
     # Games which cannmot be loaded with default parameters will be skipped by
     # several standard tests. We make a list of such games here in order to make
     # implementors think twice about making new games non-default-loadable
     non_default_loadable = [
         game.short_name for game in pyspiel.registered_games()
         if not game.default_loadable
     ]
     expected = [
         # Being non-default-loadable prevents various automated tests.
         # Only add games here if there is no sensible default for a parameter.
         "efg_game",
         "nfg_game",
         "misere",
         "turn_based_simultaneous_game",
         "normal_form_extensive_game",
         "repeated_game",
         "start_at",
     ]
     self.assertCountEqual(non_default_loadable, expected)
def main(_):
  if FLAGS.games == "*":
    games_list = [
        game.short_name
        for game in pyspiel.registered_games()
        if game.default_loadable
    ]
  else:
    games_list = FLAGS.games.split(";")

  logging.info("Running benchmark for %s games.", len(games_list))
  logging.info("This will take approximately %d seconds.",
               len(games_list) * FLAGS.time_limit)

  game_stats = []
  for game_name in games_list:
    logging.info("Running benchmark on %s", game_name)
    game_stats.append(
        _rollout_until_timeout(game_name, FLAGS.time_limit, FLAGS.give_up_after,
                               FLAGS.if_simultaneous_convert_to_turn_based))

  with pd.option_context("display.max_rows", None,
                         "display.max_columns", None,
                         "display.width", 200):
    df = pd.DataFrame(game_stats)
    # Use nice header names.
    df.rename(columns={
        "game_name": "Game",
        "ms_per_rollouts": "msec/rollout",
        "ms_per_moves": "msec/move",
        "giveups_per_rollout": "Give ups/rollouts",
        "time_elapsed": "Time elapsed [sec]"
    }, inplace=True)

    print("---")
    print("Results for following benchmark configuration:")
    print("time_limit =", FLAGS.time_limit)
    print("give_up_after =", FLAGS.give_up_after)
    print("---")
    print(df)
Exemple #8
0
import collections
import logging
import random
import time
import unittest

from absl.testing import absltest
from absl.testing import parameterized

import numpy as np

from open_spiel.python.algorithms import get_all_states
import pyspiel

_ALL_GAMES = pyspiel.registered_games()

_GAMES_TO_TEST = [g.short_name for g in _ALL_GAMES if g.default_loadable]

_GAMES_NOT_UNDER_TEST = [
    g.short_name for g in _ALL_GAMES if not g.default_loadable
]

# The list of game instances to test on the full tree as tuples
# (name to display, string to pass to load_game).
_GAMES_FULL_TREE_TRAVERSAL_TESTS = [
    ("catch", "catch(rows=6,columns=3)"),
    ("cliff_walking", "cliff_walking(horizon=7)"),
    ("deep_sea", "deep_sea(size=3)"),
    ("kuhn_poker", "kuhn_poker"),
    ("leduc_poker", "leduc_poker"),
Exemple #9
0
import pickle
from absl import app
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np

from open_spiel.python import games  # pylint: disable=unused-import
import pyspiel
from open_spiel.python.utils import file_utils

# Put a bound on length of game so test does not timeout.
MAX_ACTIONS_PER_GAME = 1000

# All games registered in the main spiel library.
SPIEL_GAMES_LIST = pyspiel.registered_games()

# All games loadable without parameter values.
SPIEL_LOADABLE_GAMES_LIST = [g for g in SPIEL_GAMES_LIST if g.default_loadable]

# TODO(b/141950198): Stop hard-coding the number of loadable games.
assert len(SPIEL_LOADABLE_GAMES_LIST) >= 38, len(SPIEL_LOADABLE_GAMES_LIST)

# All simultaneous games.
SPIEL_SIMULTANEOUS_GAMES_LIST = [
    g for g in SPIEL_LOADABLE_GAMES_LIST
    if g.dynamics == pyspiel.GameType.Dynamics.SIMULTANEOUS
]
assert len(SPIEL_SIMULTANEOUS_GAMES_LIST) >= 14, len(
    SPIEL_SIMULTANEOUS_GAMES_LIST)
Exemple #10
0
def main(_):
    games_list = pyspiel.registered_games()
    print("Registered games:")
    print(games_list)

    action_string = None

    print("Creating game: " + FLAGS.game)
    if FLAGS.players is not None:
        game = pyspiel.load_game(
            FLAGS.game, {"players": pyspiel.GameParameter(FLAGS.players)})
    else:
        game = pyspiel.load_game(FLAGS.game)

    # Get a new state
    if FLAGS.load_state is not None:
        # Load a specific state
        state_string = ""
        with open(FLAGS.load_state, encoding="utf-8") as input_file:
            for line in input_file:
                state_string += line
        state_string = state_string.rstrip()
        print("Loading state:")
        print(state_string)
        print("")
        state = game.deserialize_state(state_string)
    else:
        state = game.new_initial_state()

    # Print the initial state
    print(str(state))

    while not state.is_terminal():
        # The state can be three different types: chance node,
        # simultaneous node, or decision node
        if state.is_chance_node():
            # Chance node: sample an outcome
            outcomes = state.chance_outcomes()
            num_actions = len(outcomes)
            print("Chance node, got " + str(num_actions) + " outcomes")
            action_list, prob_list = zip(*outcomes)
            action = np.random.choice(action_list, p=prob_list)
            print("Sampled outcome: ",
                  state.action_to_string(state.current_player(), action))
            state.apply_action(action)

        elif state.is_simultaneous_node():
            # Simultaneous node: sample actions for all players.
            chosen_actions = [
                random.choice(state.legal_actions(pid))
                for pid in range(game.num_players())
            ]
            print("Chosen actions: ", [
                state.action_to_string(pid, action)
                for pid, action in enumerate(chosen_actions)
            ])
            state.apply_actions(chosen_actions)

        else:
            # Decision node: sample action for the single current player
            action = random.choice(state.legal_actions(state.current_player()))
            action_string = state.action_to_string(state.current_player(),
                                                   action)
            print("Player ", state.current_player(),
                  ", randomly sampled action: ", action_string)
            state.apply_action(action)

        print(str(state))

    # Game is now done. Print utilities for each player
    returns = state.returns()
    for pid in range(game.num_players()):
        print("Utility for player {} is {}".format(pid, returns[pid]))
def registered_games():
    return pyspiel.registered_games()
Exemple #12
0
from __future__ import division
from __future__ import print_function

import random
import unittest

from absl.testing import absltest
from absl.testing import parameterized

import numpy as np

from open_spiel.python.algorithms import get_all_states
import pyspiel

_GAMES_TO_TEST = [
    g.short_name for g in pyspiel.registered_games() if g.default_loadable
]

# The list of game instances to test on the full tree as tuples
# (name to display, string to pass to load_game).
_GAMES_FULL_TREE_TRAVERSAL_TESTS = [
    ("catch", "catch(rows=6,columns=3)"),
    ("cliff_walking", "cliff_walking(horizon=7)"),
    ("deep_sea", "deep_sea(size=3)"),
    ("kuhn_poker", "kuhn_poker"),
    ("leduc_poker", "leduc_poker"),
    ("iigoofspiel4", "turn_based_simultaneous_game(game=goofspiel("
     "imp_info=True,num_cards=4,points_order=descending))"),
    ("kuhn_poker3p", "kuhn_poker(players=3)"),
    ("first_sealed_auction", "first_sealed_auction(max_value=2)"),
    ("tiny_hanabi", "tiny_hanabi"),
Exemple #13
0
import pyspiel
for game in pyspiel.registered_games():
    print(game)
Exemple #14
0
def list_games():
  return [game.short_name for game in pyspiel.registered_games()]