forked from okreng/risk_learning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboard.py
More file actions
77 lines (64 loc) · 2.48 KB
/
board.py
File metadata and controls
77 lines (64 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import networkx as nx
import yaml
from player import Player
class Board:
"""
Class that represents a board. Contains all available territories.
"""
def __init__(self, board=None):
self.graph = nx.Graph() # Graph that holds territories and edges between them
self.territories = {} # Maps territory name to Territory
if board is not None:
self.parse_boardfile(board)
def parse_boardfile(self, boardfile):
"""
Loads in a territory YAML and saves it to local vars.
:param boardfile: path to YAML file
"""
with open(boardfile) as f:
board = yaml.load(f)
for continent_name, continent_dict in board['continents'].items():
for country_name, country_dict in continent_dict.items():
self.territories[country_name] = Territory(country_name, continent_name, country_dict['neighbors'])
for territory in self.territories.values():
for neighbor in territory.neighbors:
self.graph.add_edge(territory, self.territories[neighbor])
def draw(self):
"""
Draws current graph
"""
inv_dict = {v: k for k, v in self.territories.items()}
layout = nx.kamada_kawai_layout(self.graph)
nx.draw(self.graph, pos=layout, labels=inv_dict, with_labels=True)
class Territory:
"""
Class representing a single territory.
"""
def __init__(self, name, continent, neighbors=None):
self.name = name
self.neighbors = neighbors # type: [Territory]
self.continent = continent # type: str
self.num_armies = 0 # number of armies contained
self.owner = None # type: Player
def add_armies(self, num_armies):
"""
Adds armies to territories. Adding conditions should be checked here
:param int num_armies: Armies to add
:return int Num armies not added
"""
self.num_armies = num_armies
return 0
def remove_armies(self, num_armies):
"""
Removes armies from territories. Removal conditions should be checked here.
:param Territory territory:
:param int num_armies:
:return int Num armies not removed
"""
num_under_zero = self.num_armies - num_armies
if num_under_zero > 0:
self.num_armies -= num_armies
return 0
else:
self.num_armies = 0
return num_under_zero