├── catan ├── test │ ├── test_catan.py │ ├── test_states.py │ ├── test_boardbuilder.py │ └── __init__.py ├── __init__.py ├── pieces.py ├── trading.py ├── boardbuilder.py ├── board.py ├── game.py └── states.py ├── version.py ├── requirements.txt ├── MANIFEST.in ├── .gitignore ├── setup.py ├── README.md └── LICENSE /catan/test/test_catan.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /catan/test/test_states.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /catan/test/test_boardbuilder.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /version.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.4.3' 2 | -------------------------------------------------------------------------------- /catan/test/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = 'ross' 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | hexgrid 2 | catanlog 3 | undoredo 4 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | include LICENSE 3 | include version.py 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | *.iml 3 | dist 4 | MANIFEST 5 | .egg-info 6 | *.egg-info 7 | -------------------------------------------------------------------------------- /catan/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | module catan provides classes and enums useful for representing a catan game. 3 | 4 | The main class is Game, which contains Players, a Board, and a CatanLog. 5 | 6 | See module boardbuilder for the mechanics of creating and modifying Board objects. 7 | 8 | All classes in this module: 9 | - Game 10 | - Player 11 | - Board 12 | - Tile 13 | - Terrain 14 | - HexNumber 15 | - Port 16 | - Piece 17 | - PieceType 18 | """ 19 | -------------------------------------------------------------------------------- /catan/pieces.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class PieceType(Enum): 5 | settlement = 'settlement' 6 | road = 'road' 7 | city = 'city' 8 | robber = 'robber' 9 | 10 | 11 | class Piece(object): 12 | """ 13 | class Piece represents a single game piece on the board. 14 | 15 | Allowed types are described in enum PieceType 16 | """ 17 | def __init__(self, type, owner): 18 | self.type = type 19 | self.owner = owner 20 | 21 | def __repr__(self): 22 | return ''.format(self.type.value, self.owner) 23 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | 3 | with open("README.md", "r") as fp: 4 | long_description = fp.read() 5 | 6 | version = dict() 7 | with open('version.py', 'r') as fp: 8 | exec(fp.read(), version) 9 | 10 | setup(name="catan", 11 | version=version['__version__'], 12 | author="Ross Anderson", 13 | author_email="ross.anderson@ualberta.ca", 14 | url="https://github.com/rosshamish/catan-py/", 15 | download_url = 'https://github.com/rosshamish/catan-py/tarball/' + version['__version__'], 16 | description="models for representing and manipulating a game of catan", 17 | long_description=long_description, 18 | keywords=[], 19 | classifiers=[], 20 | license="GPLv3", 21 | 22 | packages=["catan"], 23 | install_requires=[ 24 | 'hexgrid', 25 | 'catanlog', 26 | 'undoredo', 27 | ], 28 | ) 29 | 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | catan 2 | ----- 3 | 4 | Package catan provides models for representing and manipulating a game of catan 5 | 6 | Board coordinates must be specified as described in module [`hexgrid`](https://github.com/rosshamish/hexgrid). 7 | 8 | `.catan` files will be written to the working directory by class Game (see [`catanlog`](https://github.com/rosshamish/catanlog)). 9 | 10 | class Game also supports undo and redo, which is useful for building GUIs. 11 | 12 | Supports Python 3. Might work in Python 2. 13 | 14 | > Author: Ross Anderson ([rosshamish](https://github.com/rosshamish)) 15 | 16 | ### Installation 17 | 18 | ``` 19 | pip install catan 20 | ``` 21 | 22 | ### Usage 23 | 24 | ``` 25 | import catan.board 26 | import catan.game 27 | import catan.trading 28 | 29 | players = [Player(1, 'ross', 'red'), 30 | Player(2, 'josh', 'blue'), 31 | Player(3, 'yuri', 'green'), 32 | Player(4, 'zach', 'orange')] 33 | board = catan.board.Board() 34 | game = catan.game.Game(board=board) 35 | 36 | game.start(players=players) 37 | print(game.get_cur_player()) # -> ross (red) 38 | game.buy_settlement(0x37) 39 | game.buy_road(0x37) 40 | game.end_turn() 41 | ... 42 | game.roll(6) 43 | game.trade(trade=catan.trading.CatanTrade(...)) 44 | game.undo() 45 | game.redo() 46 | game.play_knight(...) 47 | game.end_turn() 48 | ... 49 | game.end() 50 | ``` 51 | 52 | See [`catan-spectator`](https://github.com/rosshamish/catan-spectator) for extensive usage. 53 | 54 | ### File Format 55 | 56 | 57 | 58 | catan-spectator writes game logs in the `.catan` format described by package [`catanlog`](https://github.com/rosshamish/catanlog). 59 | 60 | They look like this: 61 | 62 | ``` 63 | green rolls 6 64 | blue buys settlement, builds at (1 NW) 65 | orange buys city, builds at (1 SE) 66 | red plays dev card: monopoly on ore 67 | ``` 68 | 69 | ### Documentation 70 | 71 | Most classes and modules are documented. Read the docstrings! If something is confusing or missing, open an issue. 72 | 73 | ### License 74 | 75 | GPLv3 76 | -------------------------------------------------------------------------------- /catan/trading.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from collections import Counter 3 | 4 | 5 | class CatanTrade(object): 6 | """ 7 | class CatanTrade provides a mutable trade object for catan 8 | 9 | The trade relationship is one-to-one, and supports any number of 10 | each of the resources going in both directions. 11 | 12 | Usually, the current player is the giver, and the other entity the getter. 13 | Think of it as: the current player gives resources, and gets some in return. 14 | 15 | Use give() and get() to add resources to the trade. 16 | 17 | Resources cannot be removed from the trade. If you want this functionality, 18 | delete the trade and build a new one instead. 19 | """ 20 | def __init__(self, giver=None, getter=None): 21 | self._give = list() 22 | self._get = list() 23 | self._giver = giver 24 | self._getter = getter 25 | 26 | def give(self, terrain, num=1): 27 | """ 28 | Add a certain number of resources to the trade from giver->getter 29 | :param terrain: resource type, models.Terrain 30 | :param num: number to add, int 31 | :return: None 32 | """ 33 | for _ in range(num): 34 | logging.debug('terrain={}'.format(terrain)) 35 | self._give.append(terrain) 36 | 37 | def get(self, terrain, num=1): 38 | """ 39 | Add a certain number of resources to the trade from getter->giver 40 | :param terrain: resource type, models.Terrain 41 | :param num: number to add, int 42 | :return: None 43 | """ 44 | for _ in range(num): 45 | logging.debug('terrain={}'.format(terrain)) 46 | self._get.append(terrain) 47 | 48 | def giver(self): 49 | return self._giver 50 | 51 | def getter(self): 52 | return self._getter 53 | 54 | def giving(self): 55 | """ 56 | Returns tuples corresponding to the number and type of each 57 | resource in the trade from giver->getter 58 | 59 | :return: eg [(2, Terrain.wood), (1, Terrain.brick)] 60 | """ 61 | logging.debug('give={}'.format(self._give)) 62 | c = Counter(self._give.copy()) 63 | return [(n, t) for t, n in c.items()] 64 | 65 | def getting(self): 66 | """ 67 | Returns tuples corresponding to the number and type of each 68 | resource in the trade from getter->giver 69 | 70 | :return: eg [(2, Terrain.wood), (1, Terrain.brick)] 71 | """ 72 | c = Counter(self._get.copy()) 73 | return [(n, t) for t, n in c.items()] 74 | 75 | def num_giving(self): 76 | return len(self._give) 77 | 78 | def num_getting(self): 79 | return len(self._get) 80 | 81 | def set_giver(self, giver): 82 | self._giver = giver 83 | 84 | def set_getter(self, getter): 85 | self._getter = getter 86 | -------------------------------------------------------------------------------- /catan/boardbuilder.py: -------------------------------------------------------------------------------- 1 | """ 2 | module boardbuilder is responsible for creating starting board layouts. 3 | 4 | It can create a variety of boards by supplying various options. 5 | - Options: [terrain, numbers, ports, pieces, players] 6 | - Option values: [Opt.empty, Opt.random, Opt.preset, Opt.debug] 7 | 8 | The default options are defined in #get_opts. 9 | 10 | Use #get_opts to convert a dictionary mapping str->str to a dictionary 11 | mapping str->Opts. #get_opts will also apply the default option values 12 | for each option not supplied. 13 | 14 | Use #build to build a new board with the passed options. 15 | 16 | Use #modify to modify an existing board instead of building a new one. 17 | This will reset the board. #reset is an alias. 18 | """ 19 | from enum import Enum 20 | import logging 21 | import pprint 22 | import random 23 | import hexgrid 24 | import catan.game 25 | import catan.states 26 | import catan.board 27 | import catan.pieces 28 | 29 | 30 | class Opt(Enum): 31 | empty = 'empty' 32 | random = 'random' 33 | preset = 'preset' 34 | debug = 'debug' 35 | 36 | def __repr__(self): 37 | return 'opt:{}'.format(self.value) 38 | 39 | 40 | def get_opts(opts): 41 | """ 42 | Validate options and apply defaults for options not supplied. 43 | 44 | :param opts: dictionary mapping str->str. 45 | :return: dictionary mapping str->Opt. All possible keys are present. 46 | """ 47 | defaults = { 48 | 'board': None, 49 | 'terrain': Opt.random, 50 | 'numbers': Opt.preset, 51 | 'ports': Opt.preset, 52 | 'pieces': Opt.preset, 53 | 'players': Opt.preset, 54 | } 55 | _opts = defaults.copy() 56 | if opts is None: 57 | opts = dict() 58 | try: 59 | for key, val in opts.copy().items(): 60 | if key == 'board': 61 | # board is a string, not a regular opt, and gets special handling 62 | # in _read_tiles_from_string 63 | continue 64 | opts[key] = Opt(val) 65 | _opts.update(opts) 66 | except Exception: 67 | raise ValueError('Invalid options={}'.format(opts)) 68 | logging.debug('used defaults=\n{}\n on opts=\n{}\nreturned total opts=\n{}'.format( 69 | pprint.pformat(defaults), 70 | pprint.pformat(opts), 71 | pprint.pformat(_opts))) 72 | return _opts 73 | 74 | 75 | def build(opts=None): 76 | """ 77 | Build a new board using the given options. 78 | :param opts: dictionary mapping str->Opt 79 | :return: the new board, Board 80 | """ 81 | board = catan.board.Board() 82 | modify(board, opts) 83 | return board 84 | 85 | 86 | def reset(board, opts=None): 87 | """ 88 | Alias for #modify. Resets an existing board. 89 | """ 90 | modify(board, opts) 91 | return None 92 | 93 | 94 | def modify(board, opts=None): 95 | """ 96 | Reset an existing board using the given options. 97 | :param board: the board to reset 98 | :param opts: dictionary mapping str->Opt 99 | :return: None 100 | """ 101 | opts = get_opts(opts) 102 | if opts['board'] is not None: 103 | board.tiles = _read_tiles_from_string(opts['board']) 104 | else: 105 | board.tiles = _generate_tiles(opts['terrain'], opts['numbers']) 106 | board.ports = _get_ports(opts['ports']) 107 | board.state = catan.states.BoardStateModifiable(board) 108 | board.pieces = _get_pieces(board.tiles, board.ports, opts['players'], opts['pieces']) 109 | return None 110 | 111 | 112 | def _get_tiles(board=None, terrain=None, numbers=None): 113 | """ 114 | Generate a list of tiles using the given terrain and numbers options. 115 | 116 | terrain options supported: 117 | - Opt.empty -> all tiles are desert 118 | - Opt.random -> tiles are randomized 119 | - Opt.preset -> 120 | - Opt.debug -> alias for Opt.random 121 | 122 | numbers options supported: 123 | - Opt.empty -> no tiles have numbers 124 | - Opt.random -> numbers are randomized 125 | - Opt.preset -> 126 | - Opt.debug -> alias for Opt.random 127 | 128 | :param terrain_opts: Opt 129 | :param numbers_opts: Opt 130 | :return: list(Tile) 131 | """ 132 | if board is not None: 133 | # we have a board given, ignore the terrain and numbers opts and log warnings 134 | # if they were supplied 135 | tiles = _read_tiles_from_string(board) 136 | else: 137 | # we are being asked to generate a board 138 | tiles = _generate_tiles(terrain, numbers) 139 | 140 | return tiles 141 | 142 | 143 | def _read_tiles_from_string(board_str): 144 | terrain = [catan.board.Terrain.from_short_form(char) for char in board_str.split(' ') 145 | if char in ('w', 'b', 'h', 's', 'o', 'd')] 146 | numbers = [catan.board.HexNumber.from_digit_or_none(num) for num in board_str.split(' ') 147 | if num in ('2','3','4','5','6','8','9','10','11','12','None')] 148 | logging.info('terrain:{}, numbers:{}'.format(terrain, numbers)) 149 | tile_data = list(zip(terrain, numbers)) 150 | tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)] 151 | 152 | return tiles 153 | 154 | 155 | def _generate_tiles(terrain_opts, numbers_opts): 156 | terrain = None 157 | numbers = None 158 | 159 | if terrain_opts == Opt.empty: 160 | terrain = ([catan.board.Terrain.desert] * catan.board.NUM_TILES) 161 | elif terrain_opts in (Opt.random, Opt.debug): 162 | terrain = ([catan.board.Terrain.desert] + 163 | [catan.board.Terrain.brick] * 3 + 164 | [catan.board.Terrain.ore] * 3 + 165 | [catan.board.Terrain.wood] * 4 + 166 | [catan.board.Terrain.sheep] * 4 + 167 | [catan.board.Terrain.wheat] * 4) 168 | random.shuffle(terrain) 169 | elif terrain_opts == Opt.preset: 170 | terrain = ([catan.board.Terrain.wood, 171 | catan.board.Terrain.wheat, 172 | catan.board.Terrain.ore, 173 | catan.board.Terrain.wheat, 174 | catan.board.Terrain.sheep, 175 | catan.board.Terrain.brick, 176 | catan.board.Terrain.sheep, 177 | catan.board.Terrain.wheat, 178 | catan.board.Terrain.wood, 179 | catan.board.Terrain.ore, 180 | catan.board.Terrain.brick, 181 | catan.board.Terrain.desert, 182 | catan.board.Terrain.wheat, 183 | catan.board.Terrain.sheep, 184 | catan.board.Terrain.wood, 185 | catan.board.Terrain.ore, 186 | catan.board.Terrain.sheep, 187 | catan.board.Terrain.wood, 188 | catan.board.Terrain.brick]) 189 | 190 | if numbers_opts == Opt.empty: 191 | numbers = ([catan.board.HexNumber.none] * catan.board.NUM_TILES) 192 | elif numbers_opts in (Opt.random, Opt.debug): 193 | numbers = ([catan.board.HexNumber.two] + 194 | [catan.board.HexNumber.three]*2 + [catan.board.HexNumber.four]*2 + 195 | [catan.board.HexNumber.five]*2 + [catan.board.HexNumber.six]*2 + 196 | [catan.board.HexNumber.eight]*2 + [catan.board.HexNumber.nine]*2 + 197 | [catan.board.HexNumber.ten]*2 + [catan.board.HexNumber.eleven]*2 + 198 | [catan.board.HexNumber.twelve]) 199 | random.shuffle(numbers) 200 | numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none) 201 | elif numbers_opts == Opt.preset: 202 | numbers = ([catan.board.HexNumber.five, 203 | catan.board.HexNumber.two, 204 | catan.board.HexNumber.six, 205 | catan.board.HexNumber.three, 206 | catan.board.HexNumber.eight, 207 | catan.board.HexNumber.ten, 208 | catan.board.HexNumber.nine, 209 | catan.board.HexNumber.twelve, 210 | catan.board.HexNumber.eleven, 211 | catan.board.HexNumber.four, 212 | catan.board.HexNumber.eight, 213 | catan.board.HexNumber.ten, 214 | catan.board.HexNumber.nine, 215 | catan.board.HexNumber.four, 216 | catan.board.HexNumber.five, 217 | catan.board.HexNumber.six, 218 | catan.board.HexNumber.three, 219 | catan.board.HexNumber.eleven]) 220 | numbers.insert(terrain.index(catan.board.Terrain.desert), catan.board.HexNumber.none) 221 | 222 | assert len(numbers) == catan.board.NUM_TILES 223 | assert len(terrain) == catan.board.NUM_TILES 224 | 225 | tile_data = list(zip(terrain, numbers)) 226 | tiles = [catan.board.Tile(i, t, n) for i, (t, n) in enumerate(tile_data, 1)] 227 | 228 | return tiles 229 | 230 | 231 | def _get_ports(port_opts): 232 | """ 233 | Generate a list of ports using the given options. 234 | 235 | port options supported: 236 | - Opt.empty -> 237 | - Opt.random -> 238 | - Opt.preset -> ports are in default locations 239 | - Opt.debug -> alias for Opt.preset 240 | 241 | :param port_opts: Opt 242 | :return: list(Port) 243 | """ 244 | if port_opts in [Opt.preset, Opt.debug]: 245 | _preset_ports = [(1, 'NW', catan.board.PortType.any3), 246 | (2, 'W', catan.board.PortType.wood), 247 | (4, 'W', catan.board.PortType.brick), 248 | (5, 'SW', catan.board.PortType.any3), 249 | (6, 'SE', catan.board.PortType.any3), 250 | (8, 'SE', catan.board.PortType.sheep), 251 | (9, 'E', catan.board.PortType.any3), 252 | (10, 'NE', catan.board.PortType.ore), 253 | (12, 'NE', catan.board.PortType.wheat)] 254 | return [catan.board.Port(tile, dir, port_type) 255 | for tile, dir, port_type in _preset_ports] 256 | elif port_opts in [Opt.empty, Opt.random]: 257 | logging.warning('{} option not yet implemented'.format(port_opts)) 258 | return [] 259 | 260 | 261 | def _get_pieces(tiles, ports, players_opts, pieces_opts): 262 | """ 263 | Generate a dictionary of pieces using the given options. 264 | 265 | pieces options supported: 266 | - Opt.empty -> no locations have pieces 267 | - Opt.random -> 268 | - Opt.preset -> robber is placed on the first desert found 269 | - Opt.debug -> a variety of pieces are placed around the board 270 | 271 | :param tiles: list of tiles from _generate_tiles 272 | :param ports: list of ports from _generate_ports 273 | :param players_opts: Opt 274 | :param pieces_opts: Opt 275 | :return: dictionary mapping (hexgrid.TYPE, coord:int) -> Piece 276 | """ 277 | if pieces_opts == Opt.empty: 278 | return dict() 279 | elif pieces_opts == Opt.debug: 280 | players = catan.game.Game.get_debug_players() 281 | return { 282 | (hexgrid.NODE, 0x23): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[0]), 283 | (hexgrid.EDGE, 0x22): catan.pieces.Piece(catan.pieces.PieceType.road, players[0]), 284 | (hexgrid.NODE, 0x67): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[1]), 285 | (hexgrid.EDGE, 0x98): catan.pieces.Piece(catan.pieces.PieceType.road, players[1]), 286 | (hexgrid.NODE, 0x87): catan.pieces.Piece(catan.pieces.PieceType.settlement, players[2]), 287 | (hexgrid.EDGE, 0x89): catan.pieces.Piece(catan.pieces.PieceType.road, players[2]), 288 | (hexgrid.EDGE, 0xA9): catan.pieces.Piece(catan.pieces.PieceType.road, players[3]), 289 | (hexgrid.TILE, 0x77): catan.pieces.Piece(catan.pieces.PieceType.robber, None), 290 | } 291 | elif pieces_opts in (Opt.preset, ): 292 | deserts = filter(lambda tile: tile.terrain == catan.board.Terrain.desert, tiles) 293 | coord = hexgrid.tile_id_to_coord(list(deserts)[0].tile_id) 294 | return { 295 | (hexgrid.TILE, coord): catan.pieces.Piece(catan.pieces.PieceType.robber, None) 296 | } 297 | elif pieces_opts in (Opt.random, ): 298 | logging.warning('{} option not yet implemented'.format(pieces_opts)) 299 | 300 | 301 | def _check_red_placement(tiles): 302 | """ 303 | Returns True if no red numbers are on adjacent tiles. 304 | Returns False if any red numbers are on adjacent tiles. 305 | 306 | Not yet implemented. 307 | """ 308 | logging.warning('"Check red placement" not yet implemented') -------------------------------------------------------------------------------- /catan/board.py: -------------------------------------------------------------------------------- 1 | import copy 2 | from enum import Enum 3 | import logging 4 | import hexgrid 5 | from catan import boardbuilder, states 6 | from catan.pieces import PieceType, Piece 7 | 8 | 9 | class Board(object): 10 | """ 11 | class Board represents a catan board. It has tiles, ports, and pieces. 12 | 13 | A Board has pieces, which is a dictionary mapping (hexgrid.TYPE, coord) -> Piece. 14 | 15 | Use #place_piece, #move_piece, and #remove_piece to manage pieces on the board. 16 | 17 | Use #get_pieces to get all the pieces at a particular coordinate of the allowed types. 18 | """ 19 | def __init__(self, board=None, terrain=None, numbers=None, ports=None, pieces=None, players=None): 20 | """ 21 | Create a new board. Creation will be delegated to module boardbuilder. 22 | 23 | :param terrain: terrain option, boardbuilder.Opt 24 | :param numbers: numbers option, boardbuilder.Opt 25 | :param ports: ports option, boardbuilder.Opt 26 | :param pieces: pieces option, boardbuilder.Opt 27 | :param players: players option, boardbuilder.Opt 28 | """ 29 | self.tiles = list() 30 | self.ports = list() 31 | self.state = states.BoardState(self) 32 | self.pieces = dict() 33 | 34 | self.opts = dict() 35 | if board is not None: 36 | self.opts['board'] = board 37 | if terrain is not None: 38 | self.opts['terrain'] = terrain 39 | if numbers is not None: 40 | self.opts['numbers'] = numbers 41 | if ports is not None: 42 | self.opts['ports'] = ports 43 | if pieces is not None: 44 | self.opts['pieces'] = pieces 45 | if players is not None: 46 | self.opts['players'] = players 47 | 48 | self.reset() 49 | self.observers = set() 50 | 51 | def __deepcopy__(self, memo): 52 | cls = self.__class__ 53 | result = object.__new__(cls) 54 | memo[id(self)] = result 55 | for k, v in self.__dict__.items(): 56 | if k == 'observers': 57 | setattr(result, k, set(v)) 58 | else: 59 | setattr(result, k, copy.deepcopy(v, memo)) 60 | return result 61 | 62 | def restore(self, board): 63 | """ 64 | Restore this Board object to match the properties and state of the given Board object 65 | :param board: properties to restore to the current (self) Board 66 | """ 67 | self.tiles = board.tiles 68 | self.ports = board.ports 69 | 70 | self.state = board.state 71 | self.state.board = self 72 | 73 | self.pieces = board.pieces 74 | self.opts = board.opts 75 | self.observers = board.observers 76 | 77 | self.notify_observers() 78 | 79 | def notify_observers(self): 80 | for obs in self.observers: 81 | obs.notify(self) 82 | 83 | def lock(self): 84 | self.state = states.BoardStateLocked(self) 85 | for port in self.ports.copy(): 86 | if port.type == PortType.none: 87 | self.ports.remove(port) 88 | self.notify_observers() 89 | 90 | def unlock(self): 91 | self.state = states.BoardStateModifiable(self) 92 | 93 | def reset(self, board=None, terrain=None, numbers=None, ports=None, pieces=None, players=None): 94 | opts = self.opts.copy() 95 | if board is not None: 96 | opts['board'] = board 97 | if terrain is not None: 98 | opts['terrain'] = terrain 99 | if numbers is not None: 100 | opts['numbers'] = numbers 101 | if ports is not None: 102 | opts['ports'] = ports 103 | if pieces is not None: 104 | opts['pieces'] = pieces 105 | if players is not None: 106 | opts['players'] = players 107 | boardbuilder.reset(self, opts=opts) 108 | 109 | def can_place_piece(self, piece, coord): 110 | if piece.type == PieceType.road: 111 | logging.warning('"Can place road" not yet implemented') 112 | return True 113 | elif piece.type == PieceType.settlement: 114 | logging.warning('"Can place settlement" not yet implemented') 115 | return True 116 | elif piece.type == PieceType.city: 117 | logging.warning('"Can place city" not yet implemented') 118 | return True 119 | elif piece.type == PieceType.robber: 120 | logging.warning('"Can place robber" not yet implemented') 121 | return True 122 | else: 123 | logging.debug('Can\'t place piece={} on coord={}'.format( 124 | piece.value, hex(coord) 125 | )) 126 | return self.pieces.get(coord) is None 127 | 128 | def place_piece(self, piece, coord): 129 | if not self.can_place_piece(piece, coord): 130 | logging.critical('ILLEGAL: Attempted to place piece={} on coord={}'.format( 131 | piece.value, hex(coord) 132 | )) 133 | logging.debug('Placed piece={} on coord={}'.format( 134 | piece, hex(coord) 135 | )) 136 | hex_type = self._piece_type_to_hex_type(piece.type) 137 | self.pieces[(hex_type, coord)] = piece 138 | 139 | def move_piece(self, piece, from_coord, to_coord): 140 | from_index = (self._piece_type_to_hex_type(piece.type), from_coord) 141 | if from_index not in self.pieces: 142 | logging.warning('Attempted to move piece={} which was NOT on the board'.format(from_index)) 143 | return 144 | self.place_piece(piece, to_coord) 145 | self.remove_piece(piece, from_coord) 146 | 147 | def remove_piece(self, piece, coord): 148 | index = (self._piece_type_to_hex_type(piece.type), coord) 149 | try: 150 | self.pieces.pop(index) 151 | logging.debug('Removed piece={}'.format(index)) 152 | except ValueError: 153 | logging.critical('Attempted to remove piece={} which was NOT on the board'.format(index)) 154 | 155 | def get_pieces(self, types=tuple(), coord=None): 156 | if coord is None: 157 | logging.critical('Attempted to get_piece with coord={}'.format(coord)) 158 | return Piece(None, None) 159 | indexes = set((self._piece_type_to_hex_type(t), coord) for t in types) 160 | pieces = [self.pieces[idx] for idx in indexes if idx in self.pieces] 161 | if len(pieces) == 0: 162 | #logging.warning('Found zero pieces at {}'.format(indexes)) 163 | pass 164 | elif len(pieces) == 1: 165 | logging.debug('Found one piece at {}: {}'.format(indexes, pieces[0])) 166 | elif len(pieces) > 1: 167 | logging.debug('Found {} pieces at {}: {}'.format(len(pieces), indexes, coord, pieces)) 168 | return pieces 169 | 170 | def get_port_at(self, tile_id, direction): 171 | """ 172 | If no port is found, a new none port is made and added to self.ports. 173 | 174 | Returns the port. 175 | 176 | :param tile_id: 177 | :param direction: 178 | :return: Port 179 | """ 180 | for port in self.ports: 181 | if port.tile_id == tile_id and port.direction == direction: 182 | return port 183 | port = Port(tile_id, direction, PortType.none) 184 | self.ports.append(port) 185 | return port 186 | 187 | def _piece_type_to_hex_type(self, piece_type): 188 | if piece_type in (PieceType.road, ): 189 | return hexgrid.EDGE 190 | elif piece_type in (PieceType.settlement, PieceType.city): 191 | return hexgrid.NODE 192 | elif piece_type in (PieceType.robber, ): 193 | return hexgrid.TILE 194 | else: 195 | logging.critical('piece type={} has no corresponding hex type. Returning None'.format(piece_type)) 196 | return None 197 | 198 | def cycle_hex_type(self, tile_id): 199 | if self.state.modifiable(): 200 | tile = self.tiles[tile_id - 1] 201 | next_idx = (list(Terrain).index(tile.terrain) + 1) % len(Terrain) 202 | next_terrain = list(Terrain)[next_idx] 203 | tile.terrain = next_terrain 204 | else: 205 | logging.debug('Attempted to cycle terrain on tile={} on a locked board'.format(tile_id)) 206 | self.notify_observers() 207 | 208 | def cycle_hex_number(self, tile_id): 209 | if self.state.modifiable(): 210 | tile = self.tiles[tile_id - 1] 211 | next_idx = (list(HexNumber).index(tile.number) + 1) % len(HexNumber) 212 | next_hex_number = list(HexNumber)[next_idx] 213 | tile.number = next_hex_number 214 | else: 215 | logging.debug('Attempted to cycle number on tile={} on a locked board'.format(tile_id)) 216 | self.notify_observers() 217 | 218 | def cycle_port_type(self, tile_id, direction): 219 | if self.state.modifiable(): 220 | port = self.get_port_at(tile_id, direction) 221 | port.type = PortType.next_ui(port.type) 222 | else: 223 | logging.debug('Attempted to cycle port on coord=({},{}) on a locked board'.format(tile_id, direction)) 224 | self.notify_observers() 225 | 226 | def rotate_ports(self): 227 | """ 228 | Rotates the ports 90 degrees. Useful when using the default port setup but the spectator is watching 229 | at a "rotated" angle from "true north". 230 | """ 231 | for port in self.ports: 232 | port.tile_id = ((port.tile_id + 1) % len(hexgrid.coastal_tile_ids())) + 1 233 | port.direction = hexgrid.rotate_direction(hexgrid.EDGE, port.direction, ccw=True) 234 | self.notify_observers() 235 | 236 | def set_terrain(self, terrain): 237 | self.tiles = [Tile(tile.tile_id, t, tile.number) for t, tile in zip(terrain, self.tiles)] 238 | 239 | def set_numbers(self, numbers): 240 | self.tiles = [Tile(tile.tile_id, tile.terrain, n) for n, tile in zip(numbers, self.tiles)] 241 | 242 | def set_ports(self, ports): 243 | self.ports = ports 244 | 245 | 246 | class Tile(object): 247 | """ 248 | class Tile represents a hex tile on the catan board. 249 | 250 | It contains a tile identifier, a terrain type, and a number. 251 | """ 252 | def __init__(self, tile_id, terrain, number): 253 | """ 254 | :param tile_id: tile identifier, int, see module hexgrid 255 | :param terrain: Terrain 256 | :param number: HexNumber 257 | :return: 258 | """ 259 | self.tile_id = tile_id 260 | self.terrain = terrain 261 | self.number = number 262 | 263 | # Number of tiles on the catan board. This should probably be in module hexgrid. 264 | NUM_TILES = 3+4+5+4+3 265 | 266 | 267 | class Terrain(Enum): 268 | wood = 'wood' 269 | brick = 'brick' 270 | wheat = 'wheat' 271 | sheep = 'sheep' 272 | ore = 'ore' 273 | desert = 'desert' 274 | 275 | def __repr__(self): 276 | return self.value 277 | 278 | @staticmethod 279 | def from_short_form(char): 280 | if char == 'w': 281 | return Terrain.wood 282 | elif char == 'b': 283 | return Terrain.brick 284 | elif char == 'h': 285 | return Terrain.wheat 286 | elif char == 's': 287 | return Terrain.sheep 288 | elif char == 'o': 289 | return Terrain.ore 290 | elif char == 'd': 291 | return Terrain.desert 292 | else: 293 | raise ValueError('Illegal Terrain short form {}'.format(char)) 294 | 295 | 296 | class HexNumber(Enum): 297 | none = None 298 | two = 2 299 | three = 3 300 | four = 4 301 | five = 5 302 | six = 6 303 | eight = 8 304 | nine = 9 305 | ten = 10 306 | eleven = 11 307 | twelve = 12 308 | 309 | @staticmethod 310 | def from_digit_or_none(digit): 311 | if digit == 'None' or digit is None: 312 | return HexNumber.none 313 | else: 314 | return HexNumber(int(digit)) 315 | 316 | 317 | class PortType(Enum): 318 | any4 = '4:1' # not used in UI, only used in trading 319 | any3 = '3:1' 320 | wood = 'wood' 321 | brick = 'brick' 322 | wheat = 'wheat' 323 | sheep = 'sheep' 324 | ore = 'ore' 325 | none = 'none' # only used in UI, not used in trading 326 | 327 | @classmethod 328 | def list_ui(cls): 329 | return list(filter(lambda pt: pt != PortType.any4, PortType)) 330 | 331 | @classmethod 332 | def list_trading(cls): 333 | return list(filter(lambda pt: pt != PortType.none, PortType)) 334 | 335 | @classmethod 336 | def next_ui(cls, ptype): 337 | types = list(PortType) 338 | next_idx = (types.index(ptype) + 1) % len(types) 339 | next_port_type = types[next_idx] 340 | if next_port_type == PortType.any4: 341 | next_port_type = PortType.next_ui(next_port_type) 342 | return next_port_type 343 | 344 | 345 | class Port(object): 346 | """ 347 | class Port represents a single port on the board. 348 | 349 | Allowed types are described in enum PortType. 350 | """ 351 | def __init__(self, tile_id, direction, type): 352 | self.tile_id = tile_id 353 | self.direction = direction 354 | self.type = type 355 | 356 | def __repr__(self): 357 | return '{}({},{})'.format(self.type.value, self.tile_id, self.direction) 358 | 359 | -------------------------------------------------------------------------------- /catan/game.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import logging 3 | 4 | import hexgrid 5 | import catanlog 6 | import undoredo 7 | 8 | import catan.states 9 | import catan.board 10 | import catan.pieces 11 | 12 | 13 | class Game(object): 14 | """ 15 | class Game represents a single game of catan. It has players, a board, and a log. 16 | 17 | A Game has observers. Observers register themselves by adding themselves to 18 | the Game's observers set. When the Game changes, it will notify all its observers, 19 | who can then poll the game state and make changes accordingly. 20 | 21 | e.g. self.game.observers.add(self) 22 | 23 | A Game has state. When changing state, remember to pass the current game to the 24 | state's constructor. This allows the state to modify the game as appropriate in 25 | the current state. 26 | 27 | e.g. self.set_state(states.GameStateNotInGame(self)) 28 | """ 29 | def __init__(self, players=None, board=None, logging='on', pregame='on', use_stdout=False): 30 | """ 31 | Create a Game with the given options. 32 | 33 | :param players: list(Player) 34 | :param board: Board 35 | :param logging: (on|off) 36 | :param pregame: (on|off) 37 | :param use_stdout: bool (log to stdout?) 38 | """ 39 | self.observers = set() 40 | self.undo_manager = undoredo.UndoManager() 41 | self.options = { 42 | 'pregame': pregame, 43 | } 44 | self.players = players or list() 45 | self.board = board or catan.board.Board() 46 | self.robber = catan.pieces.Piece(catan.pieces.PieceType.robber, None) 47 | 48 | # catanlog: writing, reading 49 | if logging == 'on': 50 | self.catanlog = catanlog.CatanLog(use_stdout=use_stdout) 51 | else: 52 | self.catanlog = catanlog.NoopCatanLog() 53 | # self.catanlog_reader = catanlog.Reader() 54 | 55 | self.state = None # set in #set_state 56 | self.dev_card_state = None # set in #set_dev_card_state 57 | self._cur_player = None # set in #set_players 58 | self.last_roll = None # set in #roll 59 | self.last_player_to_roll = None # set in #roll 60 | self._cur_turn = 0 # incremented in #end_turn 61 | self.robber_tile = None # set in #move_robber 62 | 63 | self.board.observers.add(self) 64 | 65 | self.set_state(catan.states.GameStateNotInGame(self)) 66 | self.set_dev_card_state(catan.states.DevCardNotPlayedState(self)) 67 | 68 | def __deepcopy__(self, memo): 69 | cls = self.__class__ 70 | result = cls.__new__(cls) 71 | memo[id(self)] = result 72 | for k, v in self.__dict__.items(): 73 | if k == 'observers': 74 | setattr(result, k, set(v)) 75 | elif k == 'state': 76 | setattr(result, k, v) 77 | elif k == 'undo_manager': 78 | setattr(result, k, v) 79 | else: 80 | setattr(result, k, copy.deepcopy(v, memo)) 81 | return result 82 | 83 | def do(self, command: undoredo.Command): 84 | """ 85 | Does the command using the undo_manager's stack 86 | :param command: Command 87 | """ 88 | self.undo_manager.do(command) 89 | self.notify_observers() 90 | 91 | def undo(self): 92 | """ 93 | Rewind the game to the previous state. 94 | """ 95 | self.undo_manager.undo() 96 | self.notify_observers() 97 | logging.debug('undo_manager undo stack={}'.format(self.undo_manager._undo_stack)) 98 | 99 | def redo(self): 100 | """ 101 | Redo the latest undone command. 102 | """ 103 | self.undo_manager.redo() 104 | self.notify_observers() 105 | logging.debug('undo_manager redo stack={}'.format(self.undo_manager._redo_stack)) 106 | 107 | def copy(self): 108 | """ 109 | Return a deep copy of this Game object. See Game.__deepcopy__ for the copy implementation. 110 | :return: Game 111 | """ 112 | return copy.deepcopy(self) 113 | 114 | def restore(self, game): 115 | """ 116 | Restore this Game object to match the properties and state of the given Game object 117 | :param game: properties to restore to the current (self) Game 118 | """ 119 | self.observers = game.observers 120 | # self.undo_manager = game.undo_manager 121 | self.options = game.options 122 | self.players = game.players 123 | self.board.restore(game.board) 124 | self.robber = game.robber 125 | self.catanlog = game.catanlog 126 | 127 | self.state = game.state 128 | self.state.game = self 129 | 130 | self.dev_card_state = game.dev_card_state 131 | 132 | self._cur_player = game._cur_player 133 | self.last_roll = game.last_roll 134 | self.last_player_to_roll = game.last_player_to_roll 135 | self._cur_turn = game._cur_turn 136 | self.robber_tile = game.robber_tile 137 | 138 | self.notify_observers() 139 | 140 | # def read_from_file(self, file): 141 | # self.catanlog_reader.use_file(file) 142 | 143 | def notify(self, observable): 144 | self.notify_observers() 145 | 146 | def notify_observers(self): 147 | for obs in self.observers.copy(): 148 | obs.notify(self) 149 | 150 | def set_state(self, game_state): 151 | _old_state = self.state 152 | _old_board_state = self.board.state 153 | self.state = game_state 154 | if game_state.is_in_game(): 155 | self.board.lock() 156 | else: 157 | self.board.unlock() 158 | logging.info('Game now={}, was={}. Board now={}, was={}'.format( 159 | type(self.state).__name__, 160 | type(_old_state).__name__, 161 | type(self.board.state).__name__, 162 | type(_old_board_state).__name__ 163 | )) 164 | self.notify_observers() 165 | 166 | def set_dev_card_state(self, dev_state): 167 | self.dev_card_state = dev_state 168 | self.notify_observers() 169 | 170 | @undoredo.undoable 171 | def start(self, players): 172 | """ 173 | Start the game. 174 | 175 | The value of option 'pregame' determines whether the pregame will occur or not. 176 | 177 | - Resets the board 178 | - Sets the players 179 | - Sets the game state to the appropriate first turn of the game 180 | - Finds the robber on the board, sets the robber_tile appropriately 181 | - Logs the catanlog header 182 | 183 | :param players: players to start the game with 184 | """ 185 | from .boardbuilder import Opt 186 | self.reset() 187 | if self.board.opts.get('players') == Opt.debug: 188 | players = Game.get_debug_players() 189 | self.set_players(players) 190 | if self.options.get('pregame') is None or self.options.get('pregame') == 'on': 191 | logging.debug('Entering pregame, game options={}'.format(self.options)) 192 | self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.settlement)) 193 | elif self.options.get('pregame') == 'off': 194 | logging.debug('Skipping pregame, game options={}'.format(self.options)) 195 | self.set_state(catan.states.GameStateBeginTurn(self)) 196 | 197 | terrain = list() 198 | numbers = list() 199 | for tile in self.board.tiles: 200 | terrain.append(tile.terrain) 201 | numbers.append(tile.number) 202 | 203 | for (_, coord), piece in self.board.pieces.items(): 204 | if piece.type == catan.pieces.PieceType.robber: 205 | self.robber_tile = hexgrid.tile_id_from_coord(coord) 206 | logging.debug('Found robber at coord={}, set robber_tile={}'.format(coord, self.robber_tile)) 207 | 208 | self.catanlog.log_game_start(self.players, terrain, numbers, self.board.ports) 209 | self.notify_observers() 210 | 211 | def end(self): 212 | self.catanlog.log_player_wins(self.get_cur_player()) 213 | self.set_state(catan.states.GameStateNotInGame(self)) 214 | 215 | def reset(self): 216 | self.players = list() 217 | self.state = catan.states.GameStateNotInGame(self) 218 | 219 | self.last_roll = None 220 | self.last_player_to_roll = None 221 | self._cur_player = None 222 | self._cur_turn = 0 223 | 224 | self.notify_observers() 225 | 226 | def get_cur_player(self): 227 | if self._cur_player is None: 228 | return Player(1, 'nobody', 'nobody') 229 | else: 230 | return Player(self._cur_player.seat, self._cur_player.name, self._cur_player.color) 231 | 232 | def set_cur_player(self, player): 233 | self._cur_player = Player(player.seat, player.name, player.color) 234 | 235 | def set_players(self, players): 236 | self.players = list(players) 237 | self.set_cur_player(self.players[0]) 238 | self.notify_observers() 239 | 240 | def cur_player_has_port_type(self, port_type): 241 | return self.player_has_port_type(self.get_cur_player(), port_type) 242 | 243 | def player_has_port_type(self, player, port_type): 244 | for port in self.board.ports: 245 | if port.type == port_type and self._player_has_port(player, port): 246 | return True 247 | return False 248 | 249 | def _player_has_port(self, player, port): 250 | edge_coord = hexgrid.edge_coord_in_direction(port.tile_id, port.direction) 251 | for node in hexgrid.nodes_touching_edge(edge_coord): 252 | pieces = self.board.get_pieces((catan.pieces.PieceType.settlement, catan.pieces.PieceType.city), node) 253 | if len(pieces) < 1: 254 | continue 255 | elif len(pieces) > 1: 256 | raise Exception('Probably a bug, num={} pieces found on node={}'.format( 257 | len(pieces), node 258 | )) 259 | assert len(pieces) == 1 # will be asserted by previous if/elif combo 260 | piece = pieces[0] 261 | if piece.owner == player: 262 | return True 263 | return False 264 | 265 | @undoredo.undoable 266 | def roll(self, roll): 267 | self.catanlog.log_roll(self.get_cur_player(), roll) 268 | self.last_roll = roll 269 | self.last_player_to_roll = self.get_cur_player() 270 | if int(roll) == 7: 271 | self.set_state(catan.states.GameStateMoveRobber(self)) 272 | else: 273 | self.set_state(catan.states.GameStateDuringTurnAfterRoll(self)) 274 | 275 | @undoredo.undoable 276 | def move_robber(self, tile): 277 | self.state.move_robber(tile) 278 | 279 | @undoredo.undoable 280 | def steal(self, victim): 281 | if victim is None: 282 | victim = Player(1, 'nobody', 'nobody') 283 | self.state.steal(victim) 284 | 285 | def stealable_players(self): 286 | if self.robber_tile is None: 287 | return list() 288 | stealable = set() 289 | for node in hexgrid.nodes_touching_tile(self.robber_tile): 290 | pieces = self.board.get_pieces(types=(catan.pieces.PieceType.settlement, catan.pieces.PieceType.city), coord=node) 291 | if pieces: 292 | logging.debug('found stealable player={}, cur={}'.format(pieces[0].owner, self.get_cur_player())) 293 | stealable.add(pieces[0].owner) 294 | if self.get_cur_player() in stealable: 295 | stealable.remove(self.get_cur_player()) 296 | logging.debug('stealable players={} at robber tile={}'.format(stealable, self.robber_tile)) 297 | return stealable 298 | 299 | @undoredo.undoable 300 | def begin_placing(self, piece_type): 301 | if self.state.is_in_pregame(): 302 | self.set_state(catan.states.GameStatePreGamePlacingPiece(self, piece_type)) 303 | else: 304 | self.set_state(catan.states.GameStatePlacingPiece(self, piece_type)) 305 | 306 | # @undoredo.undoable # state.place_road calls this, place_road is undoable 307 | def buy_road(self, edge): 308 | #self.assert_legal_road(edge) 309 | piece = catan.pieces.Piece(catan.pieces.PieceType.road, self.get_cur_player()) 310 | self.board.place_piece(piece, edge) 311 | self.catanlog.log_buys_road(self.get_cur_player(), hexgrid.location(hexgrid.EDGE, edge)) 312 | if self.state.is_in_pregame(): 313 | self.end_turn() 314 | else: 315 | self.set_state(catan.states.GameStateDuringTurnAfterRoll(self)) 316 | 317 | # @undoredo.undoable # state.place_settlement calls this, place_settlement is undoable 318 | def buy_settlement(self, node): 319 | #self.assert_legal_settlement(node) 320 | piece = catan.pieces.Piece(catan.pieces.PieceType.settlement, self.get_cur_player()) 321 | self.board.place_piece(piece, node) 322 | self.catanlog.log_buys_settlement(self.get_cur_player(), hexgrid.location(hexgrid.NODE, node)) 323 | if self.state.is_in_pregame(): 324 | self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.road)) 325 | else: 326 | self.set_state(catan.states.GameStateDuringTurnAfterRoll(self)) 327 | 328 | # @undoredo.undoable # state.place_city calls this, place_city is undoable 329 | def buy_city(self, node): 330 | #self.assert_legal_city(node) 331 | piece = catan.pieces.Piece(catan.pieces.PieceType.city, self.get_cur_player()) 332 | self.board.place_piece(piece, node) 333 | self.catanlog.log_buys_city(self.get_cur_player(), hexgrid.location(hexgrid.NODE, node)) 334 | self.set_state(catan.states.GameStateDuringTurnAfterRoll(self)) 335 | 336 | @undoredo.undoable 337 | def buy_dev_card(self): 338 | self.catanlog.log_buys_dev_card(self.get_cur_player()) 339 | self.notify_observers() 340 | 341 | @undoredo.undoable 342 | def place_road(self, edge_coord): 343 | self.state.place_road(edge_coord) 344 | 345 | @undoredo.undoable 346 | def place_settlement(self, node_coord): 347 | self.state.place_settlement(node_coord) 348 | 349 | @undoredo.undoable 350 | def place_city(self, node_coord): 351 | self.state.place_city(node_coord) 352 | 353 | @undoredo.undoable 354 | def trade(self, trade): 355 | giver = trade.giver() 356 | giving = trade.giving() 357 | getting = trade.getting() 358 | if hasattr(trade.getter(), 'type') and trade.getter().type in catan.board.PortType: 359 | getter = trade.getter() 360 | self.catanlog.log_trades_with_port(giver, giving, getter, getting) 361 | logging.debug('trading {} to port={} to get={}'.format(giving, getter, getting)) 362 | else: 363 | getter = trade.getter() 364 | self.catanlog.log_trades_with_player(giver, giving, getter, getting) 365 | logging.debug('trading {} to player={} to get={}'.format(giving, getter, getting)) 366 | self.notify_observers() 367 | 368 | @undoredo.undoable 369 | def play_knight(self): 370 | self.set_dev_card_state(catan.states.DevCardPlayedState(self)) 371 | self.set_state(catan.states.GameStateMoveRobberUsingKnight(self)) 372 | 373 | @undoredo.undoable 374 | def play_monopoly(self, resource): 375 | self.catanlog.log_plays_monopoly(self.get_cur_player(), resource) 376 | self.set_dev_card_state(catan.states.DevCardPlayedState(self)) 377 | 378 | @undoredo.undoable 379 | def play_year_of_plenty(self, resource1, resource2): 380 | self.catanlog.log_plays_year_of_plenty(self.get_cur_player(), resource1, resource2) 381 | self.set_dev_card_state(catan.states.DevCardPlayedState(self)) 382 | 383 | @undoredo.undoable 384 | def play_road_builder(self, edge1, edge2): 385 | self.catanlog.log_plays_road_builder(self.get_cur_player(), 386 | hexgrid.location(hexgrid.EDGE, edge1), 387 | hexgrid.location(hexgrid.EDGE, edge2)) 388 | self.set_dev_card_state(catan.states.DevCardPlayedState(self)) 389 | 390 | @undoredo.undoable 391 | def play_victory_point(self): 392 | self.catanlog.log_plays_victory_point(self.get_cur_player()) 393 | self.set_dev_card_state(catan.states.DevCardPlayedState(self)) 394 | 395 | @undoredo.undoable 396 | def end_turn(self): 397 | self.catanlog.log_ends_turn(self.get_cur_player()) 398 | self.set_cur_player(self.state.next_player()) 399 | self._cur_turn += 1 400 | 401 | self.set_dev_card_state(catan.states.DevCardNotPlayedState(self)) 402 | if self.state.is_in_pregame(): 403 | self.set_state(catan.states.GameStatePreGamePlacingPiece(self, catan.pieces.PieceType.settlement)) 404 | else: 405 | self.set_state(catan.states.GameStateBeginTurn(self)) 406 | 407 | @classmethod 408 | def get_debug_players(cls): 409 | return [Player(1, 'yurick', 'green'), 410 | Player(2, 'josh', 'blue'), 411 | Player(3, 'zach', 'orange'), 412 | Player(4, 'ross', 'red')] 413 | 414 | 415 | class Player(object): 416 | """class Player represents a single player on the game board. 417 | 418 | :param seat: integer, with 1 being top left, and increasing clockwise 419 | :param name: will be lowercased, spaces will be removed 420 | :param color: will be lowercased, spaces will be removed 421 | """ 422 | def __init__(self, seat, name, color): 423 | if not (1 <= seat <= 4): 424 | raise Exception("Seat must be on [1,4]") 425 | self.seat = seat 426 | 427 | self.name = name.lower().replace(' ', '') 428 | self.color = color.lower().replace(' ', '') 429 | 430 | def __eq__(self, other): 431 | if other is None: 432 | return False 433 | if other.__class__ != Player: 434 | return False 435 | return (self.color == other.color 436 | and self.name == other.name 437 | and self.seat == other.seat) 438 | 439 | def __repr__(self): 440 | return '{} ({})'.format(self.color, self.name) 441 | 442 | def __hash__(self): 443 | return sum(bytes(str(self), encoding='utf8')) 444 | 445 | -------------------------------------------------------------------------------- /catan/states.py: -------------------------------------------------------------------------------- 1 | """ 2 | module states provides catan state machines which semi-correctly implement the State Pattern 3 | 4 | State Pattern: https://en.wikipedia.org/wiki/State_pattern 5 | 6 | The Game has a state whose type is one of the GameState types defined in this module. 7 | The Game has a dev card state whose type is one of the DevCardPlayabilityState types defined in this module. 8 | The Board has a state whose type is one of the BoardState types defined in this module. 9 | 10 | Each state machine is described in base state's docstring. 11 | 12 | Actions 13 | ------- 14 | 15 | Callers should invoke action methods on the object directly, and the object will delegate 16 | actions to its state as necessary. 17 | 18 | e.g. 19 | # class Game 20 | def steal(self, victim): 21 | if victim is None: 22 | victim = Player(1, 'nobody', 'nobody') 23 | self.state.steal(victim) 24 | # class GameStateSteal 25 | def steal(self, victim): 26 | self.game.catanlog.log_robber( 27 | self.game.get_cur_player(), 28 | self.game.robber_tile, 29 | victim 30 | ) 31 | self.game.set_state(GameStateDuringTurnAfterRoll(self.game)) 32 | # class GameStateStealUsingKnight 33 | def steal(self, victim): 34 | self.game.catanlog.log_plays_dev_knight( 35 | self.game.get_cur_player(), 36 | self.game.robber_tile, 37 | victim 38 | ) 39 | self.game.set_state(GameStateDuringTurnAfterRoll(self.game)) 40 | 41 | State Capabilities 42 | ------------------ 43 | 44 | Callers should query state capabilities through the state. 45 | 46 | e.g. 47 | if game.state.can_trade(): 48 | tradingUI.show() 49 | else: 50 | tradingUI.hide() 51 | 52 | Any new state capabilities must be named like can_do_xyz() and must return True or False. 53 | When a GameState subclass doesn't implement can_do_xyz2(), the method call will be caught in 54 | GameState.__getattr__. The method call will be ignored and None will be returned instead. 55 | 56 | If the method does not look like can_do_xyz(), it will be logged. 57 | 58 | """ 59 | import logging 60 | import hexgrid 61 | import catan.pieces 62 | 63 | 64 | class GameState(object): 65 | """ 66 | class GameState is the base game state. All game states inherit from GameState. 67 | 68 | sub-states are always allowed to override provided methods. 69 | 70 | this state implements: 71 | None 72 | this state provides: 73 | None 74 | sub-states must implement: 75 | is_in_game() 76 | """ 77 | def __init__(self, game): 78 | self.game = game 79 | 80 | def __getattr__(self, name): 81 | """Return false for methods called on GameStates which don't have those methods. 82 | This should be ok, since __getattr__ is only called as a last resort 83 | i.e. if there are no attributes in the instance that match the name 84 | 85 | source: http://stackoverflow.com/a/2405617/1817465 86 | """ 87 | def method(*args): 88 | return None 89 | if 'can_' not in name: 90 | # can_do_xyz methods are ok to return None if not implemented 91 | logging.debug('Method {0} not found'.format(name)) 92 | return method 93 | 94 | def is_in_game(self): 95 | """ 96 | See GameStateInGame for details. 97 | 98 | :return Boolean 99 | """ 100 | pass 101 | 102 | 103 | class GameStateNotInGame(GameState): 104 | """ 105 | All NOT-IN-GAME states inherit from this state. 106 | 107 | See GameStateInGame for details. 108 | 109 | this state implements: 110 | is_in_game() 111 | this state provides: 112 | None 113 | sub-classes must implement: 114 | None 115 | """ 116 | def is_in_game(self): 117 | return False 118 | 119 | 120 | class GameStateNotInGameMoveRobber(GameStateNotInGame): 121 | """ 122 | Moving the robber while setting up the board. 123 | """ 124 | def can_move_robber(self): 125 | return True 126 | 127 | def move_robber(self, tile_id): 128 | robbers = self.game.board.get_pieces((catan.pieces.PieceType.robber, ), 129 | hexgrid.tile_id_to_coord(self.game.robber_tile)) 130 | to_coord = hexgrid.tile_id_to_coord(tile_id) 131 | if robbers: 132 | robber = robbers[0] 133 | from_coord = hexgrid.tile_id_to_coord(self.game.robber_tile) 134 | self.game.board.move_piece(robber, from_coord, to_coord) 135 | else: 136 | robber = catan.pieces.Piece(catan.pieces.PieceType.robber, None) 137 | self.game.board.place_piece(robber, to_coord) 138 | if len(robbers) != 1: 139 | logging.warning('{} robbers found in board.pieces'.format(len(robbers))) 140 | self.game.robber_tile = tile_id 141 | self.game.set_state(GameStateNotInGame(self.game)) 142 | 143 | 144 | class GameStateInGame(GameState): 145 | """ 146 | All IN-GAME states inherit from this state. 147 | 148 | In game is defined as taking turns, rolling dice, placing pieces, etc. 149 | In game starts on 'Start Game', and ends on 'End Game' 150 | 151 | this state implements: 152 | is_in_game() 153 | this state provides: 154 | is_in_pregame() 155 | next_player() 156 | begin_turn() 157 | has_rolled() 158 | can_roll() 159 | can_move_robber() 160 | can_steal() 161 | can_buy_road() 162 | can_buy_settlement() 163 | can_buy_city() 164 | can_buy_dev_card() 165 | can_trade() 166 | can_play_knight() 167 | can_play_monopoly() 168 | can_play_road_builder() 169 | can_play_victory_point() 170 | sub-states must implement: 171 | can_end_turn() 172 | """ 173 | def is_in_game(self): 174 | return True 175 | 176 | def is_in_pregame(self): 177 | """ 178 | See GameStatePreGame for details. 179 | 180 | :return: Boolean 181 | """ 182 | return False 183 | 184 | def next_player(self): 185 | """ 186 | Returns the player whose turn it will be next. 187 | 188 | Uses regular seat-wise clockwise rotation. 189 | 190 | Compare to GameStatePreGame's implementation, which uses snake draft. 191 | 192 | :return Player 193 | """ 194 | logging.warning('turn={}, players={}'.format( 195 | self.game._cur_turn, 196 | self.game.players 197 | )) 198 | return self.game.players[(self.game._cur_turn + 1) % len(self.game.players)] 199 | 200 | def begin_turn(self): 201 | """ 202 | Begins the turn for the current player. 203 | 204 | All that is required is to set the game's state. 205 | 206 | Compare to GameStatePreGame's implementation, which uses GameStatePreGamePlaceSettlement 207 | 208 | :return None 209 | """ 210 | self.game.set_state(GameStateBeginTurn(self.game)) 211 | 212 | def has_rolled(self): 213 | """ 214 | Whether the current player has rolled or not. 215 | 216 | :return Boolean 217 | """ 218 | return self.game.last_player_to_roll == self.game.get_cur_player() 219 | 220 | def can_roll(self): 221 | """ 222 | Whether the current player can roll or not. 223 | 224 | A player can roll only if they have not yet rolled. 225 | 226 | :return Boolean 227 | """ 228 | return not self.has_rolled() 229 | 230 | def can_move_robber(self): 231 | """ 232 | Whether the current player can move the robber or not. 233 | 234 | :return Boolean 235 | """ 236 | return False 237 | 238 | def can_steal(self): 239 | """ 240 | Whether the current player can steal or not. 241 | 242 | :return Boolean 243 | """ 244 | return False 245 | 246 | def can_buy_road(self): 247 | """ 248 | Whether the current player can buy a road or not. 249 | 250 | :return Boolean 251 | """ 252 | return self.has_rolled() 253 | 254 | def can_buy_settlement(self): 255 | """ 256 | Whether the current player can buy a settlement or not. 257 | 258 | :return Boolean 259 | """ 260 | return self.has_rolled() 261 | 262 | def can_buy_city(self): 263 | """ 264 | Whether the current player can buy a city or not. 265 | 266 | :return Boolean 267 | """ 268 | return self.has_rolled() 269 | 270 | def can_place_road(self): 271 | """ 272 | Whether the current player can place a road or not. 273 | 274 | :return Boolean 275 | """ 276 | return False 277 | 278 | def can_place_settlement(self): 279 | """ 280 | Whether the current player can place a settlement or not. 281 | 282 | :return Boolean 283 | """ 284 | return False 285 | 286 | def can_place_city(self): 287 | """ 288 | Whether the current player can place a city or not. 289 | 290 | :return Boolean 291 | """ 292 | return False 293 | 294 | def can_buy_dev_card(self): 295 | """ 296 | Whether the current player can buy a dev card or not. 297 | 298 | :return Boolean 299 | """ 300 | return self.has_rolled() 301 | 302 | def can_trade(self): 303 | """ 304 | Whether the current player can trade or not. 305 | 306 | :return Boolean 307 | """ 308 | return self.has_rolled() 309 | 310 | def can_play_knight(self): 311 | """ 312 | Whether the current player can play a knight dev card or not. 313 | 314 | :return Boolean 315 | """ 316 | return self.game.dev_card_state.can_play_dev_card() 317 | 318 | def can_play_monopoly(self): 319 | """ 320 | Whether the current player can play a monopoly dev card or not. 321 | 322 | :return Boolean 323 | """ 324 | return self.has_rolled() and self.game.dev_card_state.can_play_dev_card() 325 | 326 | def can_play_year_of_plenty(self): 327 | """ 328 | Whether the current player can play a year of plenty dev card or not. 329 | 330 | :return Boolean 331 | """ 332 | return self.has_rolled() and self.game.dev_card_state.can_play_dev_card() 333 | 334 | def can_play_road_builder(self): 335 | """ 336 | Whether the current player can play a road builder dev card or not. 337 | 338 | :return Boolean 339 | """ 340 | return self.has_rolled() and self.game.dev_card_state.can_play_dev_card() 341 | 342 | def can_play_victory_point(self): 343 | """ 344 | Whether the current player can play a victory point dev card or not. 345 | 346 | :return Boolean 347 | """ 348 | return True 349 | 350 | def can_end_turn(self): 351 | """ 352 | Whether the current player can end their turn or not. 353 | 354 | :return Boolean 355 | """ 356 | raise NotImplemented() 357 | 358 | 359 | class GameStatePreGame(GameStateInGame): 360 | """ 361 | The pregame is defined as 362 | - AFTER the board has been laid out 363 | - BEFORE the first dice roll 364 | 365 | In other words, it is the placing of the initial settlements and roads, in snake draft order. 366 | 367 | this state implements: 368 | can_end_turn() 369 | 370 | this state provides: 371 | None 372 | sub-classes must implement: 373 | None 374 | """ 375 | def can_end_turn(self): 376 | return False 377 | 378 | def is_in_pregame(self): 379 | return True 380 | 381 | def next_player(self): 382 | snake = self.game.players.copy() 383 | snake += list(reversed(snake)) 384 | try: 385 | return snake[self.game._cur_turn + 1] 386 | except IndexError: 387 | self.game.set_state(GameStateBeginTurn(self.game)) 388 | return self.game.state.next_player() 389 | 390 | def begin_turn(self): 391 | self.game.set_state(GameStatePreGamePlaceSettlement(self.game)) 392 | 393 | def can_play_knight(self): 394 | """No dev cards in the pregame""" 395 | return False 396 | 397 | def can_play_monopoly(self): 398 | """No dev cards in the pregame""" 399 | return False 400 | 401 | def can_play_road_builder(self): 402 | """No dev cards in the pregame""" 403 | return False 404 | 405 | def can_play_victory_point(self): 406 | """No dev cards in the pregame""" 407 | return False 408 | 409 | def can_roll(self): 410 | """No rolling in the pregame""" 411 | return False 412 | 413 | def can_buy_road(self): 414 | raise NotImplemented() 415 | 416 | def can_buy_settlement(self): 417 | raise NotImplemented() 418 | 419 | def can_buy_city(self): 420 | """No cities in the pregame""" 421 | return False 422 | 423 | def can_buy_dev_card(self): 424 | """No dev cards in the pregame""" 425 | return False 426 | 427 | def can_trade(self): 428 | """No trading in the pregame""" 429 | return False 430 | 431 | 432 | class GameStatePreGamePlaceSettlement(GameStatePreGame): 433 | """ 434 | - AFTER a player's turn has started 435 | - BEFORE the player has placed an initial settlement 436 | """ 437 | def can_buy_settlement(self): 438 | return True 439 | 440 | def can_buy_road(self): 441 | return False 442 | 443 | def can_end_turn(self): 444 | return False 445 | 446 | 447 | class GameStatePreGamePlaceRoad(GameStatePreGame): 448 | """ 449 | - AFTER a player has placed an initial settlement 450 | - BEFORE the player has placed an initial road 451 | """ 452 | def can_buy_settlement(self): 453 | return False 454 | 455 | def can_buy_road(self): 456 | return True 457 | 458 | def can_end_turn(self): 459 | return False 460 | 461 | 462 | class GameStatePreGamePlacingPiece(GameStatePreGame): 463 | """ 464 | - AFTER a player has selected to place a piece 465 | - WHILE the player is choosing where to place it 466 | - BEFORE the player has placed it 467 | """ 468 | def __init__(self, game, piece_type): 469 | super(GameStatePreGamePlacingPiece, self).__init__(game) 470 | self.piece_type = piece_type 471 | 472 | def can_buy_settlement(self): 473 | return False 474 | 475 | def can_buy_road(self): 476 | return False 477 | 478 | def can_end_turn(self): 479 | return False 480 | 481 | def can_place_road(self): 482 | return self.piece_type == catan.pieces.PieceType.road 483 | 484 | def can_place_settlement(self): 485 | return self.piece_type == catan.pieces.PieceType.settlement 486 | 487 | def can_place_city(self): 488 | return self.piece_type == catan.pieces.PieceType.city 489 | 490 | def place_road(self, edge): 491 | if not self.can_place_road(): 492 | logging.warning('Attempted to place road in illegal state={} with piece_type={}'.format( 493 | self.__class__.__name__, 494 | self.piece_type 495 | )) 496 | self.game.buy_road(edge) 497 | 498 | def place_settlement(self, node): 499 | if not self.can_place_settlement(): 500 | logging.warning('Attempted to place settlement in illegal state={} with piece_type={}'.format( 501 | self.__class__.__name__, 502 | self.piece_type 503 | )) 504 | self.game.buy_settlement(node) 505 | 506 | def place_city(self, node): 507 | if not self.can_place_city(): 508 | logging.warning('Attempted to place city in illegal state={} with piece_type={}'.format( 509 | self.__class__.__name__, 510 | self.piece_type 511 | )) 512 | self.game.buy_city(node) 513 | 514 | class GameStateBeginTurn(GameStateInGame): 515 | """ 516 | The start of the turn is defined as 517 | - AFTER the previous player ends their turn 518 | - BEFORE the next player's first action 519 | """ 520 | def can_end_turn(self): 521 | return False 522 | 523 | 524 | class GameStateMoveRobber(GameStateInGame): 525 | """ 526 | Defined as 527 | - AFTER the rolling of a 7 528 | - BEFORE the player has moved the robber 529 | """ 530 | def can_end_turn(self): 531 | return False 532 | 533 | def can_move_robber(self): 534 | return True 535 | 536 | def move_robber(self, tile_id): 537 | robbers = self.game.board.get_pieces((catan.pieces.PieceType.robber, ), 538 | hexgrid.tile_id_to_coord(self.game.robber_tile)) 539 | for robber in robbers: 540 | self.game.board.move_piece(robber, 541 | hexgrid.tile_id_to_coord(self.game.robber_tile), hexgrid.tile_id_to_coord(tile_id)) 542 | if len(robbers) != 1: 543 | logging.warning('{} robbers found in board.pieces'.format(len(robbers))) 544 | self.game.robber_tile = tile_id 545 | self.game.set_state(GameStateSteal(self.game)) 546 | 547 | def can_roll(self): 548 | return False 549 | 550 | def can_buy_road(self): 551 | return False 552 | 553 | def can_buy_settlement(self): 554 | return False 555 | 556 | def can_buy_city(self): 557 | return False 558 | 559 | def can_buy_dev_card(self): 560 | return False 561 | 562 | def can_trade(self): 563 | return False 564 | 565 | def can_play_knight(self): 566 | return False 567 | 568 | def can_play_monopoly(self): 569 | return False 570 | 571 | def can_play_road_builder(self): 572 | return False 573 | 574 | 575 | class GameStateMoveRobberUsingKnight(GameStateMoveRobber): 576 | """ 577 | Defined as 578 | - AFTER the playing of a knight 579 | - BEFORE the player has moved the robber 580 | """ 581 | def move_robber(self, tile_id): 582 | robbers = self.game.board.get_pieces((catan.pieces.PieceType.robber, ), 583 | hexgrid.tile_id_to_coord(self.game.robber_tile)) 584 | for robber in robbers: 585 | self.game.board.move_piece(robber, 586 | hexgrid.tile_id_to_coord(self.game.robber_tile), hexgrid.tile_id_to_coord(tile_id)) 587 | if len(robbers) > 1: 588 | logging.warning('More than one robber found in board.pieces') 589 | self.game.robber_tile = tile_id 590 | self.game.set_state(GameStateStealUsingKnight(self.game)) 591 | 592 | 593 | class GameStateSteal(GameStateInGame): 594 | """ 595 | Defined as 596 | - AFTER the player has moved the robber 597 | - BEFORE the player has stolen a card 598 | """ 599 | def can_end_turn(self): 600 | return False 601 | 602 | def can_steal(self): 603 | return True 604 | 605 | def steal(self, victim): 606 | self.game.catanlog.log_robber( 607 | self.game.get_cur_player(), 608 | hexgrid.location(hexgrid.TILE, self.game.robber_tile), 609 | victim 610 | ) 611 | self.game.set_state(GameStateDuringTurnAfterRoll(self.game)) 612 | 613 | def can_roll(self): 614 | return False 615 | 616 | def can_buy_road(self): 617 | return False 618 | 619 | def can_buy_settlement(self): 620 | return False 621 | 622 | def can_buy_city(self): 623 | return False 624 | 625 | def can_buy_dev_card(self): 626 | return False 627 | 628 | def can_trade(self): 629 | return False 630 | 631 | def can_play_knight(self): 632 | return False 633 | 634 | def can_play_monopoly(self): 635 | return False 636 | 637 | def can_play_road_builder(self): 638 | return False 639 | 640 | 641 | class GameStateStealUsingKnight(GameStateSteal): 642 | """ 643 | Defined as 644 | - AFTER the player has moved the robber using the knight 645 | - BEFORE the player has stolen a card using the knight 646 | """ 647 | def steal(self, victim): 648 | self.game.catanlog.log_plays_knight( 649 | self.game.get_cur_player(), 650 | hexgrid.location(hexgrid.TILE, self.game.robber_tile), 651 | victim 652 | ) 653 | self.game.set_state(GameStateDuringTurnAfterRoll(self.game)) 654 | 655 | 656 | class GameStateDuringTurnAfterRoll(GameStateInGame): 657 | """ 658 | The most common state. 659 | 660 | Defined as 661 | - AFTER the player's roll 662 | - BEFORE the player ends their turn 663 | """ 664 | def can_end_turn(self): 665 | return True 666 | 667 | 668 | class GameStatePlacingPiece(GameStateInGame): 669 | """ 670 | - AFTER a player has selected to place a piece 671 | - WHILE the player is choosing where to place it 672 | - BEFORE the player has placed it 673 | """ 674 | def __init__(self, game, piece_type): 675 | super(GameStatePlacingPiece, self).__init__(game) 676 | self.piece_type = piece_type 677 | 678 | def can_end_turn(self): 679 | return False 680 | 681 | def can_place_road(self): 682 | return self.piece_type == catan.pieces.PieceType.road 683 | 684 | def can_place_settlement(self): 685 | return self.piece_type == catan.pieces.PieceType.settlement 686 | 687 | def can_place_city(self): 688 | return self.piece_type == catan.pieces.PieceType.city 689 | 690 | def place_road(self, edge): 691 | if not self.can_place_road(): 692 | logging.warning('Attempted to place road in illegal state={} with piece_type={}'.format( 693 | self.__class__.__name__, 694 | self.piece_type 695 | )) 696 | self.game.buy_road(edge) 697 | 698 | def place_settlement(self, node): 699 | if not self.can_place_settlement(): 700 | logging.warning('Attempted to place settlement in illegal state={} with piece_type={}'.format( 701 | self.__class__.__name__, 702 | self.piece_type 703 | )) 704 | self.game.buy_settlement(node) 705 | 706 | def place_city(self, node): 707 | if not self.can_place_city(): 708 | logging.warning('Attempted to place city in illegal state={} with piece_type={}'.format( 709 | self.__class__.__name__, 710 | self.piece_type 711 | )) 712 | self.game.buy_city(node) 713 | 714 | ### 715 | 716 | def can_move_robber(self): 717 | return False 718 | 719 | def can_steal(self): 720 | return False 721 | 722 | def can_buy_road(self): 723 | return False 724 | 725 | def can_buy_settlement(self): 726 | return False 727 | 728 | def can_buy_city(self): 729 | return False 730 | 731 | def can_buy_dev_card(self): 732 | return False 733 | 734 | def can_trade(self): 735 | return False 736 | 737 | def can_play_knight(self): 738 | return False 739 | 740 | def can_play_monopoly(self): 741 | return False 742 | 743 | def can_play_road_builder(self): 744 | return False 745 | 746 | def can_play_victory_point(self): 747 | return True 748 | 749 | 750 | class GameStatePlacingRoadBuilderPieces(GameStatePlacingPiece): 751 | """ 752 | - AFTER a player has selected to build 2 road builder roads 753 | - WHILE the player is choosing where to place them 754 | - BEFORE the player has placed both of them 755 | """ 756 | def __init__(self, game): 757 | super(GameStatePlacingRoadBuilderPieces, self).__init__(game, catan.pieces.PieceType.road) 758 | self.edges = list() 759 | 760 | def place_road(self, edge): 761 | if not self.can_place_road(): 762 | logging.warning('Attempted to place road in illegal state={} with piece_type={}'.format( 763 | self.__class__.__name__, 764 | self.piece_type 765 | )) 766 | piece = catan.pieces.Piece(catan.pieces.PieceType.road, self.game.get_cur_player()) 767 | self.game.board.place_piece(piece, edge) 768 | self.edges.append(edge) 769 | if len(self.edges) == 2: 770 | self.game.play_road_builder(self.edges[0], self.edges[1]) 771 | self.game.set_state(GameStateDuringTurnAfterRoll(self.game)) 772 | 773 | 774 | class DevCardPlayabilityState(object): 775 | def __init__(self, game): 776 | self.game = game 777 | 778 | def can_play_dev_card(self): 779 | raise NotImplemented() 780 | 781 | 782 | class DevCardNotPlayedState(DevCardPlayabilityState): 783 | def can_play_dev_card(self): 784 | return True 785 | 786 | 787 | class DevCardPlayedState(DevCardPlayabilityState): 788 | def can_play_dev_card(self): 789 | return False 790 | 791 | 792 | class BoardState(object): 793 | def __init__(self, board): 794 | self.board = board 795 | 796 | def modifiable(self): 797 | raise NotImplemented() 798 | 799 | 800 | class BoardStateModifiable(BoardState): 801 | def modifiable(self): 802 | return True 803 | 804 | 805 | class BoardStateLocked(BoardState): 806 | def modifiable(self): 807 | return False 808 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------