%matplotlib inline
The game of Risk
Risk in Python
Genetic Algorithms
Using a genetic algorithm to play Risk



Each player is assigned a mission. By completing the mission the player wins the game.
Missions are, for example:
We built a framework that handles all aspects of the Risk game. It consists of five classes:
Board, which handles the armies on the game board,Cards, which handles the reinforcement cards of a player,Mission, which describes the mission of a player,Player, which makes decisions on how to play, andGame, which handles all other aspects of the game.When initialized, the board randomly distributes the territories amongst the players.
import random
random.seed(42)
from board import Board
b = Board.create(n_players=4)
We can get a graphical representation of the board using plot_board():
b.plot_board()
We can easily manipulate the armies on the board:
b.set_owner(territory_id=0, player_id=5)
b.set_armies(territory_id=0, n=15)
b.plot_board()
The board is aware of the layout of the territories:
for territory_id, player_id, armies in b.neighbors(territory_id=0):
print 'Territory', territory_id, 'owned by player', player_id, 'is occupied by', armies, 'armies'
And can handle attack moves:
b.attack(from_territory=0, to_territory=21, n_armies=3)
b.plot_board()
We can get all available missions using the missions function:
from missions import missions
all_missions = missions(n_players=4)
for m in all_missions:
print m.description
Each mission is aware of the player it is assigned to:
mission = all_missions[0]
mission
mission.assign_to(player_id=0)
mission
...and can evaluate whether the mission has been achieved yet:
mission.evaluate(board=b)
There is a special case when a player's mission is to kill himself:
mission = all_missions[-1]
mission
mission.assign_to(player_id=3)
mission
A player object is required to have four methods:
reinforce(), attack(),fortify(),turn_in_cards()Let's go through a whole game.
We'll use four RandomPlayers, which take a random decision at every step of their turn.
random.seed(42)
import game, player
risk_game = game.Game.create([player.RandomPlayer() for i in range(4)])
risk_game.plot()
Now the players may place armies until they each have 30 armies:
risk_game.initialize_single_army()
risk_game.plot()
Calling initialize_armies() will have them place all armies:
risk_game.initialize_armies()
risk_game.plot()
Now the first player may play his turn.
risk_game.reinforce(risk_game.current_player)
risk_game.plot()
Then the attack phase:
risk_game.attack(risk_game.current_player)
risk_game.attack(risk_game.current_player)
risk_game.plot()
And finally the fortification phase:
risk_game.fortify(risk_game.current_player)
risk_game.next_turn()
risk_game.plot()