diplomacy.engine.game

Game

  • Contains the game engine
class diplomacy.engine.game.Game(game_id=None, **kwargs)[source]

Bases: diplomacy.utils.jsonable.Jsonable

Game class.

Properties:

  • combat:
    • Dictionary of dictionaries containing the strength of every attack on a location (including units who don’t count toward dislodgment)
    • Format: {loc: attack_strength: [ [‘src loc’, [support loc] ]}
    • e.g. { 'MUN': { 1 : [ ['A MUN', [] ], ['A RUH', [] ] ], 2 : [ ['A SIL', ['A BOH'] ] ] } }. MUN is holding, being attack without support from RUH and being attacked with support from SIL (S from BOH)
  • command: contains the list of finalized orders to be processed (same format as orders, but without .order). e.g. {‘A PAR’: ‘- A MAR’}
  • controlled_powers: (for client games only). List of powers currently controlled by associated client user.
  • convoy_paths:
    • Contains the list of remaining convoys path for each convoyed unit to reach their destination
    • Note: This is used to see if there are still active convoy paths remaining.
    • Note: This also include the start and ending location
    • e.g. {‘A PAR’: [ [‘PAR’, ‘ION’,’NAO’, ‘MAR], [‘PAR’, ‘ION’, ‘MAR’] ], … }
  • convoy_paths_possible:
    • Contains the list of possible convoy paths given the current fleet locations or None
    • e.g. [(START_LOC, {Fleets Req}, {possible dest}), …]
  • convoy_paths_dest:
    • Contains a dictionary of possible paths to reach destination from start or None
    • e.g. {start_loc: {dest_loc_1: [{fleets}, {fleets}, {fleets}], dest_loc_2: [{fleets, fleets}]}
  • daide_port: (for client games only). Port when a DAIDE bot can connect, to play with this game.
  • deadline: integer: game deadline in seconds.
  • dislodged: contains a dictionary of dislodged units (and the site that dislodged them’). e.g. { ‘A PAR’: ‘MAR’ }
  • error: contains a list of errors that the game generated. e.g. [‘NO MASTER SPECIFIED’]
  • fixed_state:
    • used when game is a context of a with-block.
    • Store values that define the game state when entered in with-statement.
    • Compared to actual fixed state to detect any changes in methods where changes are not allowed.
    • Reset to None when exited from with-statement.
  • game_id: String that contains the current game’s ID. e.g. ‘123456’
  • lost:
    • Contains a dictionary of centers that have been lost during the term
    • e.g. {‘PAR’: ‘FRANCE’} to indicate that PAR was lost by France (previous owner)
  • map: Contains a reference to the current map (Map instance). e.g. map = Map(‘standard’)
  • map_name: Contains a reference to the name of the map that was loaded (or a path to a custom map file) e.g. map_name = ‘standard’ or map_name = ‘/some/path/to/file.map’
  • messages (for non-observer games only):
    • history of messages exchanged inside this game.
    • Sorted dict mapping message timestamps to message objects (instances of diplomacy.Message).
    • Format: {message.time_sent => message}
  • message_history:
    • history of messages through all played phases.
    • Sorted dict mapping a short phase name to a message dict (with same format as field message describe above).
    • Format: {short phase name => {message.time_sent => message}}
    • Wrapped in a sorted dict at runtime, see method __init__().
  • meta_rules: contains the rules that have been processed as directives. e.g. [‘NO_PRESS’]
  • n_controls: integer:
    • exact number of controlled powers allowed for this game.
    • If game start mode is not START_MASTER, then game starts as soon as this number of powers are controlled.
  • no_rules: contains the list of rules that have been disabled (prefixed with ‘!’). e.g [‘NO_PRESS’]
  • note: a note to display on the rendering. e.g. ‘Winner: FRANCE’
  • observer_level (for client games only):
    • Highest observation level allowed for associated client user.
    • Either “master_type”, “omniscient_type” or “observer_type”.
  • orders: contains the list of current orders (not yet processed). e.g. {‘A PAR’: ‘- A MAR’}
  • ordered_units:
    • Contains a dictionary of the units ordered by each power in the last phase
    • e.g. {‘FRANCE’: [‘A PAR’, ‘A MAR’], ‘ENGLAND’: … }
  • order_history:
    • Contains the history of orders from each player from the beginning of the game.
    • Sorted dict mapping a short phase name to a dictionary of orders (powers names as keys, powers orders as values).
    • Format: {short phase name => {power name => [orders]}}
    • Wrapped in a sorted dict at runtime, see method __init__().
  • outcome: contains the game outcome. e.g. [lastPhase, victor1, victor2, victor3]
  • phase: string that contains a long representation of the current phase. e.g. ‘SPRING 1901 MOVEMENT’
  • phase_type: indicates the current phase type. e.g. ‘M’ for Movement, ‘R’ for Retreats, ‘A’ for Adjustment, ‘-‘ for non-playing phase
  • popped: contains a list of all retreaters who didn’t make it. e.g. [‘A PAR’, ‘A MAR’]
  • powers:
    • Contains a dictionary mapping power names to power instances in the game
    • e.g. {‘FRANCE’: FrancePower, ‘ENGLAND’: EnglishPower, …}
  • registration_password: ** hashed ** version of password to be sent by a player to join this game.
  • renderer: contains the object in charge of rendering the map. e.g. Renderer()
  • result:
    • Contains the result of the action for each unit.
    • In Movement Phase, result can be ‘no convoy’, ‘bounce’, ‘void’, ‘cut’, ‘dislodged’, ‘disrupted’. e.g. { ‘A PAR’: [‘cut’, ‘void’] }
    • In Retreats phase, result can be ‘bounce’, ‘disband’, ‘void’. e.g. { ‘A PAR’: [‘cut’, ‘void’] }
    • In Adjustments phase, result can be ‘void’ or ‘’. e.g. { ‘A PAR’: [‘’, ‘void’] } # e.g. to indicate a successful build, and a void build.
  • result_history:
    • Contains the history of orders results for all played phases.
    • Sorted dict mapping a short phase name to a dictionary of order results for this phase.
    • Dictionary of order results maps a unit to a list of results. See field result for more details.
    • Format: {short phase name => {unit => [results]}}
    • Wrapped in a sorted dict at runtime, see method __init__().
  • role: Either a power name (for player game) or a value in diplomacy.utils.strings.ALL_ROLE_TYPES.
  • rules: Contains a list of active rules. e.g. [‘NO_PRESS’, …]. Default is diplomacy.utils.constants.DEFAULT_GAME_RULES.
  • state_history:
    • history of previous game states (returned by method get_state()) for this game.
    • Sorted dict mapping a short phase name to a game state.
    • Each game state is associated to a timestamp generated when state is created by method get_state().
    • State timestamp then represents the “end” time of the state, ie. time when this state was saved and archived in state history.
    • Format: {short phase name => state}
    • Wrapped in a sorted dict at runtime, see method __init__().
  • status: game status (forming, active, paused, completed or canceled). Possible values in diplomacy.utils.strings.ALL_GAME_STATUSES.
  • supports:
    • Contains a dictionary of support for each unit
    • Format: { ‘unit’: [nb_of_support, [list of supporting units]] }
    • e.g. { ‘A PAR’: [2, [‘A MAR’]] }. 2 support, but the Marseille support does NOT count toward dislodgment
  • timestamp_created: timestamp in microseconds when game object was created on server side.
  • victory:
    • Indicates the number of SUPPLY [default] centers one power must control to win the game
    • Format: [reqFirstYear, reqSecondYear, …, reqAllFurtherYears]
    • e.g. [10,10,18] for 10 the 1st year, 10 the 2nd year, 18 year 3+
  • win - Indicates the minimum number of centers required to win. e.g. 3
  • zobrist_hash - Contains the zobrist hash representing the current state of this game. e.g. 12545212418541325

Cache properties:

  • unit_owner_cache:
    • Contains a dictionary with (unit, coast_required) as key and owner as value
    • Set to Note when the cache is not built
    • e.g. {(‘A PAR’, True): <FRANCE>, (‘A PAR’, False): <FRANCE>), …}
__init__(game_id=None, **kwargs)[source]

Constructor

power

(only for player games) Return client power associated to this game.

Returns:a Power object.
Return type:diplomacy.engine.power.Power
is_game_done

Returns a boolean flag that indicates if the game is done

current_state()[source]

Returns the game object. To be used with the following syntax:

with game.current_state():
    orders = players.get_orders(game, power_name)
    game.set_orders(power_name, orders)
is_fixed_state_unchanged(log_error=True)[source]

Check if actual state matches saved fixed state, if game is used as context of a with-block.

Parameters:log_error – Boolean that indicates to log an error if state has changed
Returns:boolean that indicates if the state has changed.
is_player_game()[source]

Return True if this game is a player game.

is_observer_game()[source]

Return True if this game is an observer game.

is_omniscient_game()[source]

Return True if this game is an omniscient game.

is_server_game()[source]

Return True if this game is a server game.

is_valid_password(registration_password)[source]

Return True if given plain password matches registration password.

is_controlled(power_name)[source]

Return True if given power name is currently controlled.

Parameters:power_name (str) – power name
Return type:bool
is_dummy(power_name)[source]

Return True if given power name is not currently controlled.

does_not_wait()[source]

Return True if the game does not wait anything to process its current phase. The game is not waiting is all controlled powers have defined orders and wait flag set to False. If it’s a solitaire game (with no controlled powers), all (dummy, not eliminated) powers must have defined orders and wait flag set to False. By default, wait flag for a dummy power is True. Note that an empty orders set is considered as a defined order as long as it was explicitly set by the power controller.

has_power(power_name)[source]

Return True if this game has given power name.

has_expected_controls_count()[source]

Return True if game has expected number of map powers to be controlled. If True, the game can start (if not yet started).

count_controlled_powers()[source]

Return the number of controlled map powers.

get_controlled_power_names(username)[source]

Return the list of power names currently controlled by given user name.

get_expected_controls_count()[source]

Return the number of map powers expected to be controlled in this game. This number is either specified in settings or the number of map powers.

get_dummy_power_names()[source]

Return sequence of not eliminated dummy power names.

get_dummy_unordered_power_names()[source]

Return a sequence of playable dummy power names without orders but still orderable and with orderable locations.

get_controllers()[source]

Return a dictionary mapping each power name to its current controller name.

get_controllers_timestamps()[source]

Return a dictionary mapping each power name to its controller timestamp.

get_random_power_name()[source]

Return a random power name from remaining dummy power names. Raise an exception if there are no dummy power names.

get_latest_timestamp()[source]

Return timestamp of latest data saved into this game (either current state, archived state or message).

Returns:a timestamp
Return type:int
classmethod filter_messages(messages, game_role, timestamp_from=None, timestamp_to=None)[source]

Filter given messages based on given game role between given timestamps (bounds included). See method diplomacy.utils.SortedDict.sub() about bound rules.

Parameters:
  • messages (diplomacy.utils.sorted_dict.SortedDict) – a sorted dictionary of messages to filter.
  • game_role – game role requiring messages. Either a special power name (PowerName.OBSERVER or PowerName.OMNISCIENT), a power name, or a list of power names.
  • timestamp_from – lower timestamp (included) for required messages.
  • timestamp_to – upper timestamp (included) for required messages.
Returns:

a dict of corresponding messages (empty if no corresponding messages found), mapping messages timestamps to messages.

get_phase_history(from_phase=None, to_phase=None, game_role=None)[source]

Return a list of game phase data from game history between given phases (bounds included). Each GamePhaseData object contains game state, messages, orders and order results for a phase.

Parameters:
  • from_phase

    either:

    • a string: phase name
    • an integer: index of phase in game history
    • None (default): lowest phase stored in game history
  • to_phase

    either:

    • a string: phase name
    • an integer: index of phase in game history
    • None (default): latest phase stored in game history
  • game_role – (optional) role of game for which phase history is retrieved. If none, messages in game history will not be filtered.
Returns:

a list of GamePhaseHistory objects

get_phase_from_history(short_phase_name, game_role=None)[source]

Return a game phase data corresponding to given phase from phase history.

phase_history_from_timestamp(timestamp)[source]

Return list of game phase data from game history for which state timestamp >= given timestamp.

extend_phase_history(game_phase_data)[source]

Add data from a game phase to game history.

Parameters:game_phase_data (GamePhaseData) – a GamePhaseData object.
set_status(status)[source]

Set game status with given status (should be in diplomacy.utils.strings.ALL_GAME_STATUSES).

draw(winners=None)[source]

Force a draw for this game, set status as COMPLETED and finish the game.

Parameters:winners – (optional) either None (all powers remaining to map are considered winners) or a sequence of required power names to be considered as winners.
Returns:a couple (previous state, current state) with game state before the draw and game state after the draw.
set_controlled(power_name, username)[source]

Control power with given username (may be None to set dummy power). See method diplomacy.Power#set_controlled.

update_dummy_powers(dummy_power_names)[source]

Force all power associated to given dummy power names to be uncontrolled.

Parameters:dummy_power_names – Sequence of required dummy power names.
update_powers_controllers(powers_controllers, timestamps)[source]

Update powers controllers.

Parameters:
  • powers_controllers (dict) – a dictionary mapping a power name to a controller name.
  • timestamps – a dictionary mapping a power name to timestamp when related controller (in powers_controllers) was associated to power.
new_power_message(recipient, body)[source]

Create a undated (without timestamp) power message to be sent from a power to another via server. Server will answer with timestamp, and message will be updated and added to local game messages.

Parameters:
  • recipient – recipient power name (string).
  • body – message body (string).
Returns:

a new GameMessage object.

Return type:

GameMessage

new_global_message(body)[source]

Create an undated (without timestamp) global message to be sent from a power via server. Server will answer with timestamp, and message will be updated and added to local game messages.

Parameters:body – message body (string).
Returns:a new GameMessage object.
Return type:Message
add_message(message)[source]

Add message to current game data. Only a server game can add a message with no timestamp: game will auto-generate a timestamp for the message.

Parameters:message – a GameMessage object to add.
Returns:message timestamp.
Return type:int
has_draw_vote()[source]

Return True if all controlled non-eliminated powers have voted YES to draw game at current phase.

count_voted()[source]

Return the count of controlled powers who already voted for a draw for current phase.

clear_vote()[source]

Clear current vote.

get_map_power_names()[source]

Return sequence of map power names.

get_current_phase()[source]

Returns the current phase (format ‘S1901M’ or ‘FORMING’ or ‘COMPLETED’)

get_units(power_name=None)[source]

Retrieves the list of units for a power or for all powers

Parameters:power_name – Optional. The name of the power (e.g. 'FRANCE') or None for all powers
Returns:A list of units (e.g. ['A PAR', 'A MAR']) if a power name is provided or a dictionary of powers with their units if None is provided (e.g. {'FRANCE': [...], ...})

Note: Dislodged units will appear with a leading asterisk (e.g. '*A PAR')

get_centers(power_name=None)[source]

Retrieves the list of owned supply centers for a power or for all powers

Parameters:power_name – Optional. The name of the power (e.g. ‘FRANCE’) or None for all powers
Returns:A list of supply centers (e.g. [‘PAR’, ‘MAR’]) if a power name is provided or a dictionary of powers with their supply centers if None is provided (e.g. {‘FRANCE’: […], …}
get_orders(power_name=None)[source]

Retrieves the orders submitted by a specific power, or by all powers

Parameters:power_name – Optional. The name of the power (e.g. ‘FRANCE’) or None for all powers
Returns:A list of orders (e.g. [‘A PAR H’, ‘A MAR - BUR’]) if a power name is provided or a dictionary of powers with their orders if None is provided (e.g. {‘FRANCE’: [‘A PAR H’, ‘A MAR - BUR’, …], …}
get_orderable_locations(power_name=None)[source]

Find the location requiring an order for a power (or for all powers)

Parameters:power_name – Optionally, the name of the power (e.g. ‘FRANCE’) or None for all powers
Returns:A list of orderable locations (e.g. [‘PAR’, ‘MAR’]) if a power name is provided or a dictionary of powers with their orderable locations if None is not provided (e.g. {‘FRANCE’: […], …}
get_order_status(power_name=None, unit=None, loc=None)[source]

Returns a list or a dict representing the order status (‘’, ‘no convoy’, ‘bounce’, ‘void’, ‘cut’, ‘dislodged’, ‘disrupted’) for orders submitted in the last phase

Parameters:
  • power_name – Optional. If provided (e.g. ‘FRANCE’) will only return the order status of that power’s orders
  • unit – Optional. If provided (e.g. ‘A PAR’) will only return that specific unit order status.
  • loc – Optional. If provided (e.g. ‘PAR’) will only return that specific loc order status. Mutually exclusive with unit
  • phase_type – Optional. Returns the results of a specific phase type (e.g. ‘M’, ‘R’, or ‘A’)
Returns:

  • If unit is provided a list (e.g. [] or [‘void’, ‘dislodged’])
  • If loc is provided, a couple of unit and list (e.g. (‘A PAR’, [‘void’, ‘dislodged’])), or (loc, []) if unit not found.
  • If power is provided a dict (e.g. {‘A PAR’: [‘void’], ‘A MAR’: []})
  • Otherwise a 2-level dict (e.g. {‘FRANCE: {‘A PAR’: [‘void’], ‘A MAR’: []}, ‘ENGLAND’: {}, … }

get_power(power_name)[source]

Retrieves a power instance from given power name.

Parameters:power_name – name of power instance to retrieve. Power name must be as given in map file.
Returns:the power instance, or None if power name is not found.
Return type:diplomacy.engine.power.Power
set_units(power_name, units, reset=False)[source]

Sets units directly on the map

Parameters:
  • power_name – The name of the power who will own the units (e.g. ‘FRANCE’)
  • units – An unit (e.g. ‘A PAR’) or a list of units (e.g. [‘A PAR’, ‘A MAR’]) to set Note units starting with a ‘*’ will be set as dislodged
  • reset – Boolean. If, clear all units of the power before setting them
Returns:

Nothing

set_centers(power_name, centers, reset=False)[source]

Transfers supply centers ownership

Parameters:
  • power_name – The name of the power who will control the supply centers (e.g. ‘FRANCE’)
  • centers – A loc (e.g. ‘PAR’) or a list of locations (e.g. [‘PAR’, ‘MAR’]) to transfer
  • reset – Boolean. If, removes ownership of all power’s SC before transferring ownership of the new SC
Returns:

Nothing

set_orders(power_name, orders, expand=True, replace=True)[source]

Sets the current orders for a power

Parameters:
  • power_name – The name of the power (e.g. ‘FRANCE’)
  • orders – The list of orders (e.g. [‘A MAR - PAR’, ‘A PAR - BER’, …])
  • expand – Boolean. If set, performs order expansion and reformatting (e.g. adding unit type, etc.) If false, expect orders in the following format. False gives a performance improvement.
  • replace – Boolean. If set, replace previous orders on same units, otherwise prevents re-orders.
Returns:

Nothing

Expected format:

A LON H, F IRI - MAO, A IRI - MAO VIA, A WAL S F LON, A WAL S F MAO - IRI,
F NWG C A NWY - EDI, A IRO R MAO, A IRO D, A LON B, F LIV B
set_wait(power_name, wait)[source]

Set wait flag for a power.

Parameters:
  • power_name – name of power to set wait flag.
  • wait – wait flag (boolean).
clear_units(power_name=None)[source]

Clear the power’s units

Parameters:power_name – Optional. The name of the power whose units will be cleared (e.g. ‘FRANCE’), otherwise all units on the map will be cleared
Returns:Nothing
clear_centers(power_name=None)[source]

Removes ownership of supply centers

Parameters:power_name – Optional. The name of the power whose centers will be cleared (e.g. ‘FRANCE’), otherwise all centers on the map will lose ownership.
Returns:Nothing
clear_orders(power_name=None)[source]

Clears the power’s orders

Parameters:power_name – Optional. The name of the power to clear (e.g. ‘FRANCE’) or will clear orders for all powers if None.
Returns:Nothing
clear_cache()[source]

Clears all caches

set_current_phase(new_phase)[source]

Changes the phase to the specified new phase (e.g. ‘S1901M’)

render(incl_orders=True, incl_abbrev=False, output_format='svg', output_path=None)[source]

Renders the current game and returns its image representation

Parameters:
  • incl_orders (bool, optional) – Optional. Flag to indicate we also want to render orders.
  • incl_abbrev (bool, optional) – Optional. Flag to indicate we also want to display the provinces abbreviations.
  • output_format (str, optional) – The desired output format. Currently, only ‘svg’ is supported.
  • output_path (str | None, optional) – Optional. The full path where to save the rendering on disk.
Returns:

The rendered image in the specified format.

add_rule(rule)[source]

Adds a rule to the current rule list

Parameters:rule – Name of rule to add (e.g. ‘NO_PRESS’)
Returns:Nothing
remove_rule(rule)[source]

Removes a rule from the current rule list

Parameters:rule – Name of rule to remove (e.g. ‘NO_PRESS’)
Returns:Nothing
load_map(reinit_powers=True)[source]

Load a map and process directives

Parameters:reinit_powers – Boolean. If true, empty powers dict.
Returns:Nothing, but stores the map in self.map
process()[source]

Processes the current phase of the game.

Returns:game phase data with data before processing.
build_caches()[source]

Rebuilds the various caches

rebuild_hash()[source]

Completely recalculate the Zobrist hash

Returns:The updated hash value
get_hash()[source]

Returns the zobrist hash for the current game

update_hash(power, unit_type='', loc='', is_dislodged=False, is_center=False, is_home=False)[source]

Updates the zobrist hash for the current game

Parameters:
  • power – The name of the power owning the unit, supply center or home
  • unit_type – Contains the unit type of the unit being added or remove from the board (‘A’ or ‘F’)
  • loc – Contains the location of the unit, supply center, of home being added or remove
  • is_dislodged – Indicates that the unit being added/removed is dislodged
  • is_center – Indicates that the location being added/removed is a supply center
  • is_home – Indicates that the location being added/removed is a home
Returns:

Nothing

get_phase_data()[source]

Return a GamePhaseData object representing current game.

set_phase_data(phase_data, clear_history=True)[source]

Set game from phase data.

Parameters:
  • phase_data – either a GamePhaseData or a list of GamePhaseData. If phase_data is a GamePhaseData, it will be treated as a list of GamePhaseData with 1 element. Last phase data in given list will be used to set current game internal state. Previous phase data in given list will replace current game history.
  • clear_history – Indicate if we must clear game history fields before update.
get_state()[source]

Gets the internal saved state of the game. This state is intended to represent current game view (powers states, orders results for previous phase, and few more info). See field message_history to get messages from previous phases. See field order_history to get orders from previous phases. To get a complete state of all data in this game object, consider using method Game.to_dict().

Parameters:make_copy – Boolean. If true, a deep copy of the game state is returned, otherwise the attributes are returned directly.
Returns:The internal saved state (dict) of the game
set_state(state, clear_history=True)[source]

Sets the game from a saved internal state

Parameters:
  • state – The saved state (dict)
  • clear_history – Boolean. If true, all game histories are cleared.
Returns:

Nothing

get_all_possible_orders()[source]

Computes a list of all possible orders for all locations

Returns:A dictionary with locations as keys, and their respective list of possible orders as values