def test_hand_win_ties_uneven_split(self): p1 = Player('p1',100) p2 = Player('p2', 100) p3 = Player('p3', 100) p4 = Player('p4', 100) p5 = Player('p5', 100) p1.hand_value = 12 p2.hand_value = 11 p3.hand_value = 12 p4.hand_value = 11 p5.hand_value = 12 players = [p1,p2,p3,p4,p5] p1.bid = 31 p2.bid = 70 p3.bid = 50 p4.bid = 70 p5.bid = 60 test_board = Board(players, 10) test_board.pot = sum([player.bid for player in players]) test_board.assign_hand_win(players) self.assertEqual(test_board.pot, 0) for player in players: self.assertEqual(player.bid, 0) for player in players: print(player.money,player.name) self.assertEqual(p1.money, 100+21+31) self.assertEqual(p3.money, 100+21+19+50) self.assertEqual(p5.money, 100+20+19+20+60)
def run(): board = Board() for move in range(36): pos = board.add_a_random_piece() if board.has_move_won(pos): return ["order", move] return ["chaos", 36]
def create_board_from_str(board_str, empty_location_str='-'): """ :param board_str: str representing desired board configuration :return: Board """ # Remove spaces board_str = board_str.replace(' ', '') # Split by lines board_rows = board_str.split('\n') # Remove empty lines board_rows = [row for row in board_rows if row] board = Board(len(board_rows)) for r, row in enumerate(board_rows): for c, piece_color_str in enumerate(row): if piece_color_str == empty_location_str: continue color = piece_str_to_color(piece_color_str) board.add(color=color, position=(r,c)) return board
class Game: moves = 0 board = None def __init__(self, board_size): """ Let's create the game """ self.board = Board(board_size) def is_ended(self): """ Check if the game is ended """ total = sum([x for row in self.board.grid for x in row]) return total == 0 def won(self): """ Check if the first player won """ return self.is_ended() and self.moves % 2 == 1 def possible_moves(self): """ Collect all possible moves on the corrent game board """ x = 0 y = 0 moves = [] while(x > self.board.size): while(y > self.board.size): if self.board[x][y] == 0: continue moves = moves + self.spot_possible_moves(x, y) y = y + 1 x = x + 1 return moves def spot_possible_moves(self, x, y): width = 0 height = 0 x_increment = 1 moves = [] while(width < x): y_increment = 1 while(height < self.board.size - y): height = height + y_increment y_increment = y_increment + 1 moves = moves + [(x, y), width, height] width = math.pow(x_increment, 2) x_increment = x_increment + 1 return moves def valid_move(self, move): pass def move(self): self.board.flip((4, 1), 4, 2) self.move = self.move + 1
class FanoronaGame: """This class represents the game as is it.""" def __init__(self): """Ctor""" self.board = Board() def start(self): """Starts the game with GUI""" gui = GUI(self.board) gui.start_main_loop() def start_text(self): """Starts the game in text mode""" black = False # white begin the game while not self.board.game_is_finished(): self.board.print_board() if black: prompt = "black> " else: prompt = "white> " move = raw_input(prompt) self.board.move_piece(move, black) black = not black
def test_move_wrong_piece_to_dest(self): ''''Test requesting moving a wrong piece to a destination cell. ''' #Setup board with a two white pawns: board = Board() pawn1 = Pawn(board.white) pawn2 = Pawn(board.white) board[0, 4].piece = King(board.black) board[7, 4].piece = King(board.white) col1, col2, row = 1, 3, 5 board[col1, row].piece = pawn1 board[col2, row].piece = pawn2 #Simulate BoardController: selected_cell = board[col1, row] #board.on_cell_selected(selected_cell) #Preconditions: self.assertTrue(board.can_move_piece_in_cell_to(selected_cell, (col1, row-1))) #Try moving pawn2 to the destination for pawn1: self.assertFalse(board.can_move_piece_in_cell_to(board[col2,row], (col1, row-1))) self.assertRaises(MoveError, board.move_piece_in_cell_to, pawn2.owner, (col2,row), (col1, row-1))
def main(): parser = argparse.ArgumentParser(description='Print Trello.com JSON file') parser.add_argument('-f', '--format', choices=["text", "markdown", "html"], default="markdown") parser.add_argument('source', metavar="json_file") parser.add_argument('-v', '--version', action='version', version='TrelloPrint ' + RELEASE) args = parser.parse_args() filename = args.source with open(filename, "r") as f: data = json.load(f) b = Board(data) if (args.format == "text"): print(b) exit md_string = b.get_md() if (args.format == "markdown"): print(md_string) elif (args.format == "html"): with open(TEMP_FILE_NAME, "w") as temp_fd: temp_fd.write(md_string) os.system("markdown " + TEMP_FILE_NAME) os.remove(TEMP_FILE_NAME)
def testComputeAdvanceOnFirmTrackValue(self): b = Board() gc = gamecontroller.GameController(b) p0, p1, p2, p3 = gc.players ai0, ai1, ai2, ai3 = [gc.ais[i] for i in range(4)] firm = Resources.Red b.revenues[firm] = 21 # 11, 5, 3, 1 gc.advanceOnFirmTrack(p0, firm, 4) gc.advanceOnFirmTrack(p1, firm, 3) gc.advanceOnFirmTrack(p3, firm, 4) self.assertEqual(1, ai2.computeAdvanceOnFirmValue(gc, firm, 3)) self.assertEqual(3, ai2.computeAdvanceOnFirmValue(gc, firm, 4)) self.assertEqual(11, ai2.computeAdvanceOnFirmValue(gc, firm, 5)) gc.advanceOnFirmTrack(p2, firm, 1) self.assertEqual(0, ai2.computeAdvanceOnFirmValue(gc, firm, 2)) self.assertEqual(2, ai2.computeAdvanceOnFirmValue(gc, firm, 3)) self.assertEqual(10, ai2.computeAdvanceOnFirmValue(gc, firm, 4)) gc.advanceOnFirmTrack(p0, firm, 1) self.assertEqual(0, ai2.computeAdvanceOnFirmValue(gc, firm, 2)) self.assertEqual(2, ai2.computeAdvanceOnFirmValue(gc, firm, 3)) self.assertEqual(4, ai2.computeAdvanceOnFirmValue(gc, firm, 4)) self.assertEqual(10, ai2.computeAdvanceOnFirmValue(gc, firm, 5)) gc.advanceOnFirmTrack(p2, firm, 10) self.assertEqual(0, ai2.computeAdvanceOnFirmValue(gc, firm, 2)) self.assertEqual(0, ai2.computeAdvanceOnFirmValue(gc, firm, 3)) self.assertEqual(0, ai2.computeAdvanceOnFirmValue(gc, firm, 4)) self.assertEqual(0, ai2.computeAdvanceOnFirmValue(gc, firm, 5))
def test_king_is_checked(self): board = Board() board[0, 0].piece = King(board.black) board[1, 1].piece = Queen(board.white) board[7, 7].piece = King(board.white) self.assertTrue(board.king_is_checked(board.black)) self.assertFalse(board.king_is_checked(board.white))
def get_board(): try: current_board = pickle.load(open("current_board.pkl", "rb")) except: current_board = Board() pickle.dump(current_board, open("current_board.pkl", "wb")) return json.dumps(current_board.getArray())
def testComputeBuildValue(self): b = Board() gc = gamecontroller.GameController(b) gc.turnIndex = 2 p0, p1, p2, p3 = gc.players ai0, ai1, ai2, ai3 = [gc.ais[i] for i in range(4)] column = BuildingColumn(Resources.Red, [ BuildingCard(5, Resources.Red, Resources.Glass), BuildingCard(2, Resources.Red, Resources.Bank), BuildingCard(3, Resources.Red, Resources.Red), BuildingCard(3, Resources.Red, Resources.Red), ]) b.buildingColumn[Resources.Red] = column column.setRoof(RoofCard(4, 4)) b.buildingColumn[Resources.Green].setRoof(FinalRoofCard(10)) p0.amount = 100 p0.addCard(ShareCard(Resources.Red, 2)) p0.addCard(WorkforceCard(0, 1)) b.advanceShareScore(Resources.Red, 17) valueBefore = b.getShareValueForScore(maxShareScore[2][17]) valueAfter = b.getShareValueForScore(maxShareScore[2][21]) expected = 2 * (valueAfter - valueBefore) + 3 * valueAfter + 4 * 3 - 20 self.assertEqual(expected, ai0.computeBuildValue(gc, Resources.Red)) self.assertEqual(-1000, ai0.computeBuildValue(gc, Resources.Green)) p0.amount = 10 self.assertEqual(-1000, ai0.computeBuildValue(gc, Resources.Red))
class TestMaxShip(unittest.TestCase): """Test behaviour of max_ship function.""" def setUp(self): """Set up a board.""" self.board = Board(5, 5) def tearDown(self): """Clean up.""" self.board = None def testMaxPatrol(self): """Test the maximum of patrol a player can have.""" result = self.board.max_ship(2) self.assertEqual(result, 12) def testMaxDestroyer(self): """Test the maximum of destroyer a player can have.""" result = self.board.max_ship(3) self.assertEqual(result, 7) def testMaxSubmarine(self): """Test the maximum of submarine a player can have.""" result = self.board.max_ship(4) self.assertEqual(result, 6) def testMaxAircraft(self): """Test the maximum of aircraft a player can have.""" result = self.board.max_ship(5) self.assertEqual(result, 5)
class TestRandomPlacing(unittest.TestCase): """Test behaviour of random function.""" def setUp(self): """Set up a board.""" self.board = Board(5, 5) def tearDown(self): """Clean up.""" self.board = None def testRandomPlacingPatrol(self): """Test the case when random placing patrol.""" result = self.board.random_placing('p0', 2, k=0) self.assertEqual(result, "Done") def testRandomDestroyer(self): """Test the case when random placing destroyer.""" result = self.board.random_placing('d0', 3, k=0) self.assertEqual(result, "Done") def testRandomPlacingSubmarine(self): """Test the case when random placing submarine.""" result = self.board.random_placing('s0', 4, k=0) self.assertEqual(result, "Done") def testRandomPlacingAircraft(self): """Test the case when random placing aircraft.""" result = self.board.random_placing('a0', 5, k=0) self.assertEqual(result, "Done")
class LearnerTestCase(ut.TestCase): def setUp(self): self.board = Board() self.learner = Learner() def tearDown(self): self.board = None self.learner = None def testMinimax(self): # self.board= Board(new_grid = RED_EASY_LOOKAHEAD) # print(self.learner.getNextMove(self.board)) # self.board= Board(new_grid = START) self.board = Board(new_grid = RED_EASY_LOOKAHEAD_2) best = self.learner.getNextMove(self.board) def testNearestNeighbor(self): weights = [0] * len(self.board.getMoveList(AI_COLOR)) weights[0] = 1 self.learner = Learner(data_points = [(self.board.getArray().tolist(), weights)]) # self.board.getMoveList(AI_COLOR)[0][1].printMove() # self.learner.getNextMove(self.board).printBoard() self.assertEqual(self.learner.getNextMove(self.board), self.board.getMoveList(AI_COLOR)[0][1], \ 'predicted best move does not match') def testUpdateWeights(self): pass
def test_flagged_neighbours(self): board = Board(3, 3) board.flagged.add((0, 0)) board.flagged.add((1, 0)) self.assertEqual(board.flagged_neighbours((0, 1)), 2) self.assertEqual(board.flagged_neighbours((1, 1)), 2) self.assertEqual(board.flagged_neighbours((2, 0)), 1)
def test_gameplay_first_player_first_move(self): """ Test initial gameplay logic and/or AI when going first """ board = Board() first_move = board.find_next_move('X') self.assertIn(first_move, board.CORNERS)
def test_gameplay_second_player(self): """ Test that the AI picks the middle square as quickly as possible when playing second """ board = Board() board.add_mark(0, "O") self.assertEquals(4, board.find_next_move("X"))
def main(): app = QApplication(sys.argv) table = QTableWidget() tableItem = QTableWidgetItem() board = Board(10, 10) board.create_board() table.setWindowTitle("Set QTableWidget Header Alignment") table.setColumnCount(board.num_cols) table.setRowCount(board.num_rows) table.setHorizontalHeaderLabels(QString("HEADER 1;HEADER 2;HEADER 3;HEADER 4").split(";")) table.setItem(0,0, QTableWidgetItem("THIS IS LONG TEXT 1")) for row in range(board.num_rows): for col in range(board.num_cols): print board[row, col] table.setItem(row, col, QTableWidgetItem(str(board[row, col]))) table.horizontalHeaderItem(0).setTextAlignment(Qt.AlignLeft) table.horizontalHeaderItem(1).setTextAlignment(Qt.AlignHCenter) table.horizontalHeaderItem(2).setTextAlignment(Qt.AlignRight) table.resizeColumnsToContents(); table.show() return app.exec_()
def test_add_mark_already_selected(self): """ Test adding a mark to an already-selected position results in an error """ board = Board() board.add_mark(0, "X") self.assertRaises(TicTacToeError, board.add_mark, 0, "O")
def test_valid_moves_second_row_black(self): board = Board() board.set_config(flat=EMPTY*64) # it doesn't matter much pawn = Pawn(board, Square(6, 0), BLACK) expected = [Square(7, 0)] result = pawn.valid_moves() self.assertEqual(expected, result)
def load(filename): with open(filename, "r") as f: step = 0 tiles = [] stuff = TileFeatureDict() stuff_list = [] for line in f: if step == 0: # tiles if line[0] == "^": # player loc board_toR = Board(tiles) player_start = map(int, line[1:].split(",")) step = 1 continue tiles.append(map(int, line.rstrip())) if step == 1: # features # "2,3,2,1 # "2,3,4 splat = line.split(",") item_data = map(int, splat[:3]) item = TileFeature.id_to_item(item_data[2]) optional = splat[3:] if optional: # more than just the coordinates and type if optional[0] and optional[0][0] == '"': # pass as string optional = (','.join(optional))[1:].rstrip() item = item(board_toR, item_data[1::-1], optional) else: # these are currently the only options :| item = item(board_toR, item_data[1::-1], stuff_list[int(optional[0])]) stuff.add_to_nums(item) else: item = item(board_toR, item_data[1::-1]) stuff_list.append(item) stuff[(item_data[0], item_data[1])] = item board_toR.add_stuff(stuff) return player_start, board_toR
class ConnectFour(object): def __init__(self, cell_list=None, columns=7, column_size=6, human=False, level='easy'): self.adversaries = [HumanPlayer(), HumanPlayer(False, 'O')] if not human: self.adversaries[1] = ComputerPlayer(level=level) self.board = Board() def read_player_move(self, ): return self.current_player.move(self.board) def play(self, ): self.current_player = [player for player in self.adversaries if player.turn is True][0] while True: print self.board move = self.read_player_move() if move in ('q', 'Q'): sys.exit(0) self.board.set_cell(move, self.current_player.name) over = self.board.game_over() if over: break self.current_player = self.get_next_player()[0] print self.board print "Cat's Game!" if over == 'tie' else \ self.current_player.name + " won the game!" def get_next_player(self, ): for player in self.adversaries: player.turn = not player.turn return [player for player in self.adversaries if player.turn is True]
def computeRect(self): """also adjust the scale for maximum usage of space""" Board.computeRect(self) sideRect = self.player.front.boundingRect() boardRect = self.boundingRect() scale = (sideRect.width() + sideRect.height()) / (boardRect.width() - boardRect.height()) self.setScale(scale)
def get_successor_states(self, state, mark): successors = [] for move in state.get_valid_moves(): successor = Board(copy(state.board)) successor.move(mark, move) successors.append((move, successor)) return successors
class Ant(object): def __init__(self, n): self.board = Board(n) self.i = int(n) / 2 self.j = int(n) / 2 self.d = Direction() def step(self): if self.board[self.i, self.j]: # Square is black self.d.turn_right() else: # Square is white self.d.turn_left() self.board.flip(self.i, self.j) self._move_forward() def _move_forward(self): i, j = self.i, self.j board = self.board if self.d == 'up': self.i, self.j = board.move_up(i, j) elif self.d == 'right': self.i, self.j = board.move_right(i, j) elif self.d == 'down': self.i, self.j = board.move_down(i, j) else: self.i, self.j = board.move_left(i, j) def __repr__(self): s = 'Ant(i={}, j={})'.format(self.i, self.j) return s + '\n' + str(self.board)
def main(): board = Board(30,30) a = Entity( 20, 20, "A", board) b = Entity( 15, 15, "B", board) a() b() os.system('clear') board.display() print("[ w:up a:left s:down d:right q:quit ]") print("[ A:you .:travelled _:untravelled x:" + str(a.x) + " y:" + str(a.y) + " ]") while True: key = getch() if key == 'w': a.move_direction('north') if key == 'a': a.move_direction('west') if key == 's': a.move_direction('south') if key == 'd': a.move_direction('east') if key == 'q': break os.system('clear') board.display() print("[ w:up a:left s:down d:right q:quit ]") print("[ A:you .:travelled _:untravelled x:" + str(a.x) + " y:" + str(a.y) + " ]")
def test_infinite_dumped(self): b = Board((3, Infinity)) for x in range(3): for y in range(3): b[x, y] = x * y dumped = list(b.dumped()) self.assertEqual(len(dumped), 3 + 9)
def init_pooo(init_string): """Initialise le robot pour un match :param init_string: instruction du protocole de communication de Pooo (voire ci-dessous) :type init_string: chaîne de caractères (utf-8 string) INIT<matchid>TO<#players>[<me>];<speed>;\ <#cells>CELLS:<cellid>(<x>,<y>)'<radius>'<offsize>'<defsize>'<prod>,...;\ <#lines>LINES:<cellid>@<dist>OF<cellid>,... <me> et <owner> désignent des numéros de 'couleur' attribués aux joueurs. La couleur 0 est le neutre. le neutre n'est pas compté dans l'effectif de joueurs (<#players>). '...' signifie que l'on répète la séquence précédente autant de fois qu'il y a de cellules (ou d'arêtes). 0CELLS ou 0LINES sont des cas particuliers sans suffixe. <dist> est la distance qui sépare 2 cellules, exprimée en... millisecondes ! /!\ attention: un match à vitesse x2 réduit de moitié le temps effectif de trajet d'une cellule à l'autre par rapport à l'indication <dist>. De manière générale temps_de_trajet=<dist>/vitesse (division entière). :Example: "INIT20ac18ab-6d18-450e-94af-bee53fdc8fcaTO6[2];1;3CELLS:1(23,9)'2'30'8'I,2(41,55)'1'30'8'II,3(23,103)'1'20'5'I;2LINES:1@3433OF2,1@6502OF3" """ print("INIT DU MATCH"); global MATCH_AI ; (nbPlayers,playerId,l_n,l_e) = potocole.initStringToAI(init_string); print("NUMERO DU JOUEUR :",playerId); board = Board(nbPlayers,l_n); print("EDGES :" ,l_e); board.addEdges(l_e); MATCH_AI = AI(board,playerId) ;
def testActionBuild(self): b = Board() gc = GameController(b) p0, p1, p2, p3 = gc.players # Doctor the board for resource in FirmsOrGoods: b.revenues[resource] = 0 column = BuildingColumn(Resources.Red, [ BuildingCard(5, Resources.Red, Resources.Glass), BuildingCard(6, Resources.Red, Resources.Iron), BuildingCard(5, Resources.Red, Resources.Glass), BuildingCard(2, Resources.Red, Resources.Bank), BuildingCard(3, Resources.Red, Resources.Red), BuildingCard(3, Resources.Red, Resources.Red), ]) b.buildingColumn[Resources.Red] = column b.roofStack = [RoofCard(5, 7, 4)] column.setRoof(RoofCard(4, 4, 2)) p2.amount = 20 gc.actionBuild(p2, Resources.Red) self.assertEqual(0, p2.amount) self.assertEqual(4, p2.getLevel()) self.assertIn(ShareCard(Resources.Red, 3), p2.cards) self.assertEqual(10, b.revenues[Resources.Red]) self.assertEqual(5, b.revenues[Resources.Glass]) self.assertEqual(7, b.shareScore[Resources.Red]) self.assertEqual(5, column.length()) self.assertEqual(6, column.getLevel())
def test_valid_moves_seventh_row_white(self): board = Board() board.set_config(flat=EMPTY*64) # it doesn't matter much pawn = Pawn(board, Square(1, 0), WHITE) expected = [Square(0, 0)] result = pawn.valid_moves() self.assertEqual(expected, result)
def __init__(self): self.init_parse() self.board = Board(self.height, self.width, self.n_mines)
from board import Board import text_view as view import text_controller as ctrl from pygame_control import window_display # available to change but it will also affect the size of the window and difficulty level! # difficulty levels - "EASY", "NORMAL", "HARD" board = Board(15, 15, "EASY") view = view.TextView(board) # ctrl.play(board) # view.display() window_display(board)
def setUp(self): self.board = Board() self.player = Player() pass
screen.addstr(player_message) valid = False # keep asking until we get valid input while not valid: try: player_count = int(screen.getstr(0, len(player_message), 1)) if player_count in range(1, 3): valid = True else: screen.addstr("Please enter either 1 or 2.") except ValueError: screen.addstr("Please enter either 1 or 2.") board = Board() # set the ai player if needed if player_count == 1: board.ai_player = Board.PLAYER_X screen.erase() # continue while there is no winner and there are moves available while board.get_winner() == -1 and board.is_available_move(): # clear the screen on every turn so the new board can be drawn screen.erase() # play the ai turn if board.is_ai_player(): board.ai_move() # play the users turn
from board import Board from graphicalBoard import GraphicalBoard def switchTurn(turn): if turn == 'W': return 'B' return 'W' def play(white, black, board): graphicalBoard = GraphicalBoard(board) turn = 'W' while not board.finishedGame(): if turn == 'W': from_cell, to_cell = white.move(board) elif turn == 'B': from_cell, to_cell = black.move(board) else: raise Exception board.changePieceLocation(turn, from_cell, to_cell) turn = switchTurn(turn) graphicalBoard.showBoard() if __name__ == '__main__': board = Board(6, 6, 2) white = RandomMinimaxAgent('W', 'B') you = RandomMinimaxAgent('B', 'W') # use your agent play(white, you, board)
if self.reprint_board: # Print board and moves self.print_game_info() # If the player won, print the board and print a win message if self.board.cell_content(target) is not None: print(self.board) print(self.WIN_MESSAGE) if __name__ == "__main__": # Get json file from sys argv json_file = sys.argv[1] # Create a board b = Board() # Get legal locations on board board_locations = b.cell_list() # Add cars from json file to board car_dict = helper.load_json(json_file) # For each car in the json file for car_name in car_dict.keys(): # Get values of the car val = car_dict[car_name] # Check if car values are valid if val[0] > 0: location = tuple(val[1]) if location in board_locations: # Create car and add to board
def base_case(board: Board, player_char: str, depth: int) -> (int, int): """Base case for minmax algorithm if board is full""" char_won = board.get_winner() if char_won == '': return 0 return 10 - depth if (char_won == player_char) else depth - 10
def __init__(self): self.move = (0, 0) self.board = Board() self.parent = None
def test_dfs(self): vals = [1, 2, 3, 4, 5, 6, 7, 0, 9, 10, 11, 8] board = Board(vals) self.assertEqual(True, depth_first_search(board))
def debug(): global processed reset() position = board.find_position('r') for idx, p in enumerate(processed): move_icon(position, p.position, hasattr(p, 'has_box') and p.has_box) position = p.position time.sleep(0.2) # main program # rows = 20 # broj redova table cols = 20 # broj kolona table cell_size = 40 # velicina celije board = Board(rows=rows, cols=cols) grid_elem_ids = [[[]] * cols for _ in range(rows)] grid_text_ids = [[[]] * cols for _ in range(rows)] # mapiranje sadrzaja table na boju celije board_to_colors = {'.': 'white', 'w': 'gray', 'g': 'orangered'} # mapiranje sadrzaja table na ikonicu board_to_icons = {'r': 'robot.png'} root = tk.Tk() root.title('ORI - Pretrage') make_menu(root) # make window menu ui = tk.Frame(root, bg='white') # main UI ui2 = tk.Frame(root, bg='white')
import os import urllib.request import time import socket import selectors import sys import subprocess import libclient from board import Board import gameSquare import pygame import playerClass from guiConfigAndFuncs import * #Global variables gameBoard = Board.createBoard(8, 8) player = None #get player before game starts from server requestedSquare = None isBackup = False global time_diff time_diff = 0 backupClient = None # should get host and port from the command line HOST = '142.58.15.181' ### THIS SECTION WILL BE REMOVED WHEN IP ADDRESS IS PASSED AS ARGUMENT WHEN RUNNING # addrArg = input("input IP address of game Host: ") # if (addrArg == ""): # if no input, connect to self. applies to the client that is hosting # HOST = urllib.request.urlopen('https://ident.me').read().decode('utf8') #get own external IP addr # else:
class State(object): def __init__(self): self.move = (0, 0) self.board = Board() self.parent = None def createNewState(self, move, player): ''' creates a new state by doing the given move in the state object ''' new = State() new.board = copy.deepcopy(self.board) new.move = new.board.makeMove(move, player) if new.move == (-1, -1): return None return new def getValidTransitions(self, player): ''' gets all the states possibly derrived from the current(self) state and all possible moves ''' validMoves = self.board.getCloseMoves() transitionBoardStates = [] for move in validMoves: new_state = self.createNewState(move, player) transitionBoardStates.append((move, new_state)) return transitionBoardStates def isWinner(self, player, chain,lastMove): ''' checks if the last player ho moved won a.k.a. made a chain of length 'chain' ''' count = 0 # North for row in reversed(range(self.move[0])): if self.board.board[(row, self.move[1])] == player.piece: count += 1 else: break # South for row in range(self.move[0], self.board.dimension): if self.board.board[(row, self.move[1])] == player.piece: count += 1 else: break if count == chain: return True count = 0 # East for column in range(self.move[1], self.board.dimension): if self.board.board[(self.move[0], column)] == player.piece: count += 1 else: break # West for column in reversed(range(self.move[1])): if self.board.board[(self.move[0], column)] == player.piece: count += 1 else: break if count == chain: return True count = 0 # North West for row, column in zip(reversed(range(self.move[0])), reversed(range(self.move[1]))): if self.board.board[(row, column)] == player.piece: count += 1 else: break # South East for row, column in zip(range(self.move[0], self.board.dimension), range(self.move[1], self.board.dimension)): if self.board.board[(row, column)] == player.piece: count += 1 else: break if count == chain: return True count = 0 # North East for row, column in zip(reversed(range(self.move[0])), range(self.move[1] + 1, self.board.dimension)): if self.board.board[(row, column)] == player.piece: count += 1 else: break # South West for row, column in zip(range(self.move[0], self.board.dimension), reversed(range(self.move[1] + 1))): if self.board.board[(row, column)] == player.piece: count += 1 else: break if count == chain: return True return False def heuristic(self, chain, player, opponent): ''' checks the current state of the board and computes a value which represents the favorability of the player 'player' ''' current_chain_count = self.countChains(player) oponent_chain_count =self.countChains(opponent) if current_chain_count >= 10000: return 100000 elif oponent_chain_count >= 10000: return -100000 else: return current_chain_count-oponent_chain_count def counter(self, player, row, column, dir_x, dir_y): ''' counts the number of player pieces that are consecutive in a certain direction ''' count = 0 while row >= 0 and row < self.board.dimension and column >= 0 and column < self.board.dimension: if self.board.board[(row, column)] == player.piece: count += 1 row += dir_x column += dir_y else: break return count def countChains(self, player): ''' gets the state of chains made by th current player chainScore = 0 ''' chainScore = 0 #horizontal for row in range(self.board.dimension - 1): currentChain=0 for column in range(self.board.dimension - 1): if self.board.board[(row,column)] == player.piece: currentChain+=1 elif currentChain >1: chainScore += 10**(currentChain-1) currentChain = 0 else: currentChain = 0 if currentChain >1: chainScore += 10**(currentChain-1) currentChain = 0 #vertical for column in range(self.board.dimension - 1): currentChain=0 for row in range(self.board.dimension - 1): if self.board.board[(row,column)] == player.piece: currentChain+=1 elif currentChain >1: chainScore += 10**(currentChain-1) currentChain = 0 else: currentChain = 0 if currentChain >1: chainScore += 10**(currentChain-1) currentChain = 0 #main diagonal currentChain1=0 currentChain2=0 row = 0 copyRow = row for column in range(self.board.dimension-1): if self.board.board[(column,column)] == player.piece: currentChain1+=1 elif currentChain1 >1: chainScore += 10**(currentChain1-1) # print(chainScore) currentChain1 = 0 else: currentChain1 = 0 if currentChain1 >1: chainScore += 10**(currentChain1-1) currentChain1 = 0 currentChain1=0 for row in range(1,self.board.dimension - 1): currentChain1=0 currentChain2=0 copyRow = row for column in range(self.board.dimension - copyRow-1): if self.board.board[(row,column)] == player.piece: currentChain1+=1 elif currentChain1 >1: chainScore += 10**(currentChain1-1) currentChain1 = 0 else: currentChain1 = 0 if self.board.board[(column,row)] == player.piece: currentChain2+=1 elif currentChain2 >1: chainScore += 10**(currentChain2-1) currentChain2 = 0 else: currentChain2 = 0 row+=1 if currentChain1 >1: chainScore += 10**(currentChain1-1) currentChain1 = 0 if currentChain2 >1: chainScore += 10**(currentChain2-1) currentChain2 = 0 row = copyRow #secondary diagonal currentChain1=0 currentChain2=0 row = 0 copyRow = row for column in range(self.board.dimension-1,0,-1): if self.board.board[(row,column)] == player.piece: currentChain1+=1 elif currentChain1 >1: chainScore += 10**(currentChain1-1) currentChain1 = 0 else: currentChain1 = 0 row+=1 if currentChain1 >1: chainScore += 10**(currentChain1-1) currentChain1 = 0 currentChain1=0 currentChain2=0 for row in range(self.board.dimension - 1): currentChain1=0 currentChain2=0 copyRow = row for column in range(self.board.dimension-1,copyRow,-1): if self.board.board[(row,column)] == player.piece: currentChain1+=1 elif currentChain1 >1: chainScore += 10**(currentChain1-1) currentChain1 = 0 else: currentChain1 = 0 if self.board.board[(14-column,14-row)] == player.piece: currentChain2+=1 elif currentChain2 >1: chainScore += 10**(currentChain2-1) currentChain2 = 0 else: currentChain2 = 0 row+=1 if currentChain1 >1: chainScore += 10**(currentChain1-1) currentChain1 = 0 if currentChain2 >1: chainScore += 10**(currentChain2-1) currentChain2 = 0 row = copyRow return chainScore
def evalThread(genomes): """ Finds the fitnesses of a small collection of genomes Arguments: args {array of (int, genome objects)} -- An array (or other iterable) of genomes to be evaluated Returns: dictionary -- A dictionary from genomeID to genome fitness """ fitnessDictionary = {} # Work over all the genomes for genomeID, genome in genomes: # Create a neural network based on the genome nn = neat.nn.FeedForwardNetwork.create(genome, config) # start a game for the nn to play b = Board() b.placeTile() b.placeTile() # Have the nn play the game while not b.isGameOver(): # TODO Find a good set of inputs for this ---v tilesUp, scoreUp = b.peek(Board.UP) tilesDown, scoreDown = b.peek(Board.DOWN) tilesLeft, scoreLeft = b.peek(Board.LEFT) tilesRight, scoreRight = b.peek(Board.RIGHT) inputs = list(map(tileActivationLevel, tilesUp.flatten())) inputs += list(map(tileActivationLevel, tilesDown.flatten())) inputs += list(map(tileActivationLevel, tilesLeft.flatten())) inputs += list(map(tileActivationLevel, tilesRight.flatten())) inputs.append(scoreUp) inputs.append(scoreDown) inputs.append(scoreLeft) inputs.append(scoreRight) inputs.append(1) output = nn.activate(inputs) # TODO Find a good set of inputs for this ---^ # Find what direction the AI wants to move the tiles maxActivation = -1000000000 for i in range(4): if output[i] > maxActivation and b.canMove(i): maxActivation = output[i] for i in range(4): if output[i] >= maxActivation and b.canMove(i): b.move(i) break # Prepare the next turn b.placeTile() # Mark down this genome's fitness fitnessDictionary[genomeID] = int(b.score) return fitnessDictionary
def replay(infile, pretty_print=False, show_options=False): B = Board() moves = [] i = 0 with open(infile) as f: print("Reading file...") for line in f: line = line.strip() if not line: continue if line[0] == '#': continue _,sr,_,sc,*_ = line r = int(sr) c = int(sc) moves.append( (r,c) ) print("Press Enter to continue") print("Press Control + C to go back") print("Press Control + D to quit") while True: if i == len(moves): print("Control + D to quit") else: r,c = moves[i] B.move(r,c, B.player) print("Player", B.player) if not pretty_print: print(B) else: B.pprint() if show_options: print(B.get_valid()) print("played ({},{})".format(r,c)) try: opt = input("\n>>> ").lower() except EOFError: break except KeyboardInterrupt: opt = 'b' print('\r>>> ') if opt == 'b': i = max(i-1, 0) B = Board() for move in moves[:i]: B.move(*move) else: i = min(i+1,len(moves)) for move in moves[i+1:]: B.move(*move) B.pprint() if B.winner: print("Winner: Player", B.winner) else: print("Game is a tie!") return B.winner
#!/usr/bin/python import torch from board import Board from gomoku_net import Net board = Board() net = Net() done = False while not done: # compute q-values board_state = torch.tensor(board.as_array()).unsqueeze(0) board_state = board_state.type(torch.FloatTensor) q_values = net(board_state) # choose top (valid) move valid_moves = board.valid_moves() top_moves = torch.topk(q_values, 361) top_moves = top_moves[1].squeeze(0) for i in range(361): top_move = top_moves[i].item() if top_move in valid_moves: break # play top (valid) move done = board.make_move(top_move)[1] print(board)
def setUp(self): self.first_board = Board([['+', '-', '-', '+'], ['+', '+', '+', '+'], ['-', '-', '+', '-'], ['+', '-', '-', '-']]) self.second_board = Board([['-', '-', '+', '-'], ['-', '+', '+', '+'], ['+', '-', '+', '-']])
def _clear_board(self, args, gnu_response): self.board = Board() self.move_history = [] self.server.send('=')
length = data[name][0] pos = data[name][1] orientation = data[name][2] return Car(name, length, pos, orientation) if __name__ == "__main__": # Get arguments from cmd args = sys.argv if len(args) != 2: print("Please add json file as a parameter.") exit(1) # Create board board = Board() # Load basic board information from file data = load_json(args[1]) # Load cars to board for name in data: car = get_car_from_json(data) board.add_car(car) # create game object and start game game = Game(board) game.play()
def test_h1_invalid_all(self): board = Board([5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4]) heuristic_val = heuristic_1(board) self.assertEqual(372, heuristic_val)
class ServerBridge(object): def __init__(self): self.model = keras.models.load_model('weights.h5') self.board = Board() self.move_history = [] self.commands = { 'name': self.name, 'version': self.version, 'boardsize': self.boardsize, 'clear_board': self.clear_board, 'list_commands': self.list_commands, 'play': self.play, 'genmove': self.genmove, 'kgs-genmove_cleanup': self.kgs_genmove_cleanup, 'final_status_list': self.send_gnu_response, 'komi': self.send_gnu_response, 'showboard': self.send_gnu_response, } self.gnugo = pexpect.spawn('gnugo --mode gtp') self.server = TCPConnection('127.0.0.1', 4901) def listen(self): message = self.server.listen() if message: parts = message.split(' ') command = parts[0] args = parts[1:] if len(parts) > 1 else [] if command in self.commands: self.commands[command](args, self.get_gnu_response(message)) else: self.server.send('? Unknown command') def get_gnu_response(self, message): self.gnugo.sendline(message) self.gnugo.expect('\n') self.gnugo.expect('\r\n\r\n') return self.gnugo.before.decode().strip() ################ # GTP Commands # ################ def boardsize(self, args, gnu_response): if args[0] == '19': self.server.send('=') else: self.server.send('? Invalid board size') def play(self, args, gnu_response): m = ''.join(args).lower() if 'pass' in m or 'resign' in m: self.server.send('=') return col = ord(args[1][0]) - ord('a') row = 19 - int(args[1][1:]) if col > 7: col -= 1 move = (row, col) self.move_history.append(move) player = 1 if args[0] == 'b' else -1 self.board.play(player, move) self.get_gnu_response('play {} {}'.format(args[0], args[1])) self.server.send('=') def name(self, args, gnu_response): self.server.send('= DaveBot') def version(self, args, gnu_response): self.server.send('= 1') def quit(self, args, gnu_response): sys.exit(0) def genmove(self, args, gnu_response): gnu_response = gnu_response.lower() if 'pass' in gnu_response: self.server.send('= pass') return if 'resign' in gnu_response: self.server.send('= resign') return # Undo genmove so that the board is consistent with GnuGo self.get_gnu_response('undo') player = 1 if args[0] == 'b' else -1 planes = feature_planes.generate(self.board, player, self.move_history) predictions = self.model.predict(np.array([planes])).tolist()[0] for i, prediction in enumerate(predictions): predictions[i] = (i, prediction) predictions = sorted(predictions, key=lambda p: p[1], reverse=True) for prediction in predictions: move = (prediction[0] // 19, prediction[0] % 19) if self.board.is_legal_move(player, move): row = 19 - move[0] col = 'abcdefghjklmnopqrst'[move[1]] self.board.play(player, move) self.move_history.append(move) self.server.send('= {}{}'.format(col.upper(), row)) self.get_gnu_response('play {} {}{}'.format( args[0], col.upper(), row)) return self.server.send('= pass') def _kgs_genmove_cleanup(self, args, gnu_response): self.genmove(args, gnu_response) def _genmove(self, args, gnu_response): self.genmove(args, gnu_response) def _list_commands(self, args, gnu_response): self.server.send('= {}'.format('\n'.join(self.commands.keys()))) def _clear_board(self, args, gnu_response): self.board = Board() self.move_history = [] self.server.send('=') def send_gnu_response(self, args, gnu_response): self.server.send(gnu_response)
def test_h1_invalid_column(self): board = Board([1, 2, 3, 4, 5, 6, 7, 0, 9, 10, 11, 8]) heuristic_val = heuristic_1(board) self.assertEqual(7, heuristic_val)
from __future__ import annotations from threading import Thread from board import Board from ki_controller import PredictController from pygame_connection import PygameConnection, BoardConnection from pygame_mainloop import PygameMainloop pycon = PygameConnection() loop = PygameMainloop([pycon], [pycon], (640, 400), 60) bdcon = BoardConnection(pycon) board = Board((4, 4)) loop.start_background() Thread(target=board.run, args=([bdcon], PredictController()), daemon=True).start() # board.run([bdcon], PredictController())
def test_h2_false_solution(self): board = Board([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) heuristic_val = heuristic_2(board) self.assertEqual(79, heuristic_val)
def test_h1_invalid_rows(self): board = Board([1, 2, 3, 7, 5, 6, 0, 4, 9, 10, 11, 8]) heuristic_val = heuristic_1(board) self.assertEqual(34, heuristic_val)
from board import Board if __name__ == '__main__': board = Board() while board.check_results() == Board.CONTINUE: try: cell = list( map( int, str(input("Input cell coordinates (separated by space): ") ).split())) except KeyboardInterrupt: print("Error: incorrect value") continue try: board.make_move(cell) print(board) except AssertionError as e: print(e) continue if board.check_results() != Board.CONTINUE: break board = board.computer_move() print(board) result = board.check_results() if result == Board.CROSS_WON: print("Player has won") elif result == Board.NOUGHT_WON: print("Computer has won")
def test_h1_complete_board(self): board = Board([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0]) heuristic_val = heuristic_1(board) self.assertEqual(0, heuristic_val)
sense.magnetometer_on() while True: print(sense.sense.compass) def get_temperature_demo(): tempc = Temperature( sense ) # theoretically this should return the temperature in celsius from the sensehat print(tempc.temperature_c()) # it is untested however. red = [255, 0, 0] green = [0, 255, 0] blue = [0, 0, 255] white = [255, 255, 255] black = [0, 0, 0] rpi = Board() sense = _SenseHat(rpi) pygame.init() pygame.display.set_mode((640, 480)) sense_led(white, black) compass() # sense_demo() # led_on_demo() # calls led_on_demo function in main.py to turn on LED # rgb_led_on_demo() # calls rgb_led_on_demo function in main.py to turn on red led then off and turn on white. # get_temperature_demo() # demo of temperature get from the Temperature class
def test_h2_row_swaps(self): board = Board([1, 3, 2, 4, 6, 5, 7, 8, 9, 10, 0, 11]) heuristic_val = heuristic_2(board) self.assertEqual(58, heuristic_val)
else: draw_menu(screen, font, title_font) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if not board: if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1 and ( (SCREEN_HEIGHT / 2) - (SCREEN_HEIGHT / 10) <= event.pos[0] < (SCREEN_HEIGHT / 2) + (SCREEN_HEIGHT / 10) and (SCREEN_WIDTH / 2) - (SCREEN_WIDTH / 6) <= event.pos[1] < (SCREEN_WIDTH / 2) + (SCREEN_WIDTH / 6)): board = Board(screen, font) client = Client(board) ship_index = 1 if board: if event.type == pygame.MOUSEBUTTONDOWN and board.get_phase( ) == "player turn": # Send guess if valid if event.button == 1: x, y = int(event.pos[0] / (SCREEN_WIDTH / 10)), int( event.pos[1] / (SCREEN_HEIGHT / 10)) if y > 0 and board.valid_guess((x, y)): client.send("MOVE,{},{}".format(x, y)) elif event.type == pygame.KEYDOWN and board.get_phase( ) == "placement": if event.key != pygame.K_RETURN: board.move_ship(str(ship_index), event.key)
class Monopoly: def __init__(self, num_players): self.board = Board() self.draw = Draw() self.blockchain = BlockChain() self.banker = Bank() self.num_players = num_players self.players = [] for player_index in range(num_players): name = input('Enter Player {}\'s Name: '.format(player_index + 1)) self.players.append(Player(name, player_index + 1)) # Initialize the accounts of all players with 1500 Monopoly Coin self.blockchain.initialize_accounts(self.players) # Initialize all properties. By default the owner of all properties is the bank self.blockchain.initialize_properties(self.board.get_all_properties()) @staticmethod def roll_dice(): return random.randint(1, 6), random.randint(1, 6) def play_game(self, automatic=True): if automatic: while not self.game_over(): for player in self.players: self.serve_turn(player, 0) else: game_ended = False while not game_ended: for player in self.players: cont = input('\nContinue? Y/N: ') if cont == 'Y' or cont == 'y': self.serve_turn(player, 0) else: winner = None highest_assets = 0 for player in self.players: if not player.state == PlayerState.DONE: assets = player.add_assets( self.blockchain, self.board) if highest_assets < assets: winner = player highest_assets = assets game_ended = True print('Winner is {}. Game Ended. Bye!'.format(winner)) # ---------- Serving Methods ------------ def serve_turn(self, player, num_doubles): if num_doubles == 0: print('\n{} is up! Starting balance: ${}'.format( str(player), player.get_balance(self.blockchain))) roll = self.roll_dice() print('{} rolled: {}'.format(str(player), roll)) if num_doubles == 2 and roll[0] == roll[1]: self.go_to_jail(player) elif player.in_jail: self.serve_jail(player, roll) else: trade = input('Would you like to make a trade? Y/N: ') if trade == 'Y' or trade == 'y': self.serve_trade(player) edit = input('Would you like to edit properties? Y/N: ') if edit == 'Y' or edit == 'y': self.serve_prop_edit(player) self.serve_normally(player, roll) if roll[0] == roll[1]: self.serve_turn(player, num_doubles + 1) if num_doubles == 0: print('{}\'s turn is over! Ending balance: ${}'.format( str(player), player.get_balance(self.blockchain))) def serve_normally(self, player, roll): position = (player.position + roll[0] + roll[1]) % 40 space = self.board.get_property_at_index(position) print('{} landed on: {}'.format(str(player), space.name)) self.move_player_to(player, position) if space.type == 'Draw': self.serve_draw(player, space) elif space.type == 'Special': self.serve_special_space(player, space) else: self.serve_property(player, space) def serve_jail(self, player, roll): player.jail_rolls += 1 if roll[0] == roll[1] or player.jail_rolls == 3: print('{} got out of Jail!'.format(str(player))) player.jail_rolls = 0 player.in_jail = False self.serve_normally(player, roll) else: print('{} is still in Jail!'.format(str(player))) def serve_draw(self, player, space): draw = self.draw.draw_card(space.draw_type) print('{} drew: {}'.format(str(player), draw.description)) if draw.type == 'Pay': player.pay(self.banker, draw.amount, self.blockchain) elif draw.type == 'Pay All': for player_ in self.players: if player_ != player: player.pay(player_, draw.amount, self.blockchain) elif draw.type == 'Receive': self.banker.pay(player, draw.amount, self.blockchain) elif draw.type == 'Receive All': for player_ in self.players: if player_ != player: player_.pay(player, draw.amount, self.blockchain) elif draw.type == 'Move': if draw.name != 'Go to Jail': move_space = self.board.get_property_at_index(draw.index) print('{} moved to: {}'.format(str(player), str(move_space))) self.move_player_to(player, move_space.index) if move_space.type != 'Draw' and move_space.type != 'Special': self.serve_property(player, move_space) else: self.go_to_jail(player) elif draw.type == 'Special': if draw.name == 'Street Repairs' or draw.name == 'Property Repairs': houses = 0 hotels = 0 for index in self.blockchain.get_all_properties(player): houses += self.blockchain.get_houses(index) hotels += self.blockchain.get_hotel(index) print( '{} has {} houses and {} hotels and must pay ${}.'.format( player, houses, hotels, houses * draw.house_amount + hotels * draw.hotel_amount)) player.pay( self.banker, houses * draw.house_amount + hotels * draw.hotel_amount, self.blockchain) elif draw.name == 'Advance to Utility': if abs(player.position - 12) >= abs(player.position - 28): index = 28 else: index = 12 self.move_player_to(player, index) print('{} moved to: {}'.format( player, self.board.get_property_at_index(index).name)) self.serve_property(player, self.board.get_property_at_index(index), draw.name) elif draw.name == 'Advance to Railroad 1' or draw.name == 'Advance to Railroad 2': if player.position == 7: index = 5 elif player.position == 22: index = 25 else: index = 35 self.move_player_to(player, index) print('{} moved to: {}'.format( player, self.board.get_property_at_index(index).name)) self.serve_property(player, self.board.get_property_at_index(index), draw.multiplier) def serve_special_space(self, player, space): if space.name == 'Income Tax': decision = input( 'Pay 10% of assets or $200: Y for 10%, N for $200: ') if decision == 'Y' or decision == 'y': player.pay( self.banker, player.add_assets(self.blockchain, self.board) // 10, self.blockchain) else: player.pay(self.banker, 200, self.blockchain) elif space.name == 'Luxury Tax': print('Pay $75 for Luxury Tax') player.pay(self.banker, 75, self.blockchain) def serve_property(self, player, space, multiplier=1): owner_address = self.blockchain.get_property_owner(space.index) if owner_address == self.blockchain.get_account(self.banker): self.serve_banker(owner_address, player, space) elif owner_address == self.blockchain.get_account(player): print('Welcome back home {}!'.format(player)) else: self.serve_other_owner(multiplier, owner_address, player, space) def serve_banker(self, owner_address, player, space): decision = input( '{} is unowned! It costs ${}. Want to see a description? Y/N: '. format(space, space.price)) if decision == 'Y' or decision == 'y': self.describe_property(space) decision = input( 'Current Balance: ${}. Would you like to buy it? Y/N: '.format( player.get_balance(self.blockchain))) if decision == 'Y' or decision == 'y': if self.blockchain.change_ownership(owner_address, player, space.index, space.price): print('Congrats! You bought {}!'.format(space)) else: print('Couldn\'t buy {}... :('.format(space)) def serve_other_owner(self, multiplier, owner_address, player, space): owner = None for player_ in self.players: if self.blockchain.get_account(player_) == owner_address: owner = player_ break if not self.blockchain.get_mortgage(space.index): if space.type == 'Utility': other_utility = 28 if space.index == 12 else 12 if owner_address == self.blockchain.get_property_owner( other_utility) or multiplier == 10: rent = sum(self.roll_dice()) * 10 else: rent = sum(self.roll_dice()) * 4 elif space.type == 'Station': rent = space.standard_rent other_stations = [ s for s in [5, 15, 25, 35] if s != space.index ] for station_index in other_stations: if owner_address == self.blockchain.get_property_owner( station_index): rent += space.standard_rent else: rent = space.standard_rent layout = (self.blockchain.get_houses(space.index), self.blockchain.get_hotel(space.index)) if layout[0]: if layout[0] == 1: rent = space.one_house_rent elif layout[0] == 2: rent = space.two_house_rent elif layout[0] == 3: rent = space.three_house_rent else: rent = space.four_house_rent elif layout[1]: rent = space.hotel_rent else: other_properties = [ s for s in self.board.monopolies[space.group] if s != space.index ] monopoly = True for index in other_properties: if self.blockchain.get_property_owner( index) != owner_address: monopoly = False break if monopoly: rent *= 2 print('Uh oh. You owe {} ${}.'.format(owner, rent * multiplier)) player.pay(owner, rent * multiplier, self.blockchain, critical=True, board=self.board) else: print('You lucky duck, {} is mortgaged. Enjoy your free stay!'. format(space)) def serve_trade(self, player): all_properties = player.describe_all_properties( self.blockchain, self.board) # Prints all properties as well keep_trading = True while keep_trading: trade_index = int(input('Index to trade: ')) if trade_index in all_properties: buyer = int(input('Enter player number to trade with: ')) if buyer - 1 < len(self.players) and buyer > 0: buyer = self.players[buyer - 1] sell_property = self.board.get_property_at_index( trade_index) price = int(input('Enter amount to offer: ')) buyer_decision = input( 'Would {} like to buy {} for ${}? Y/N: '.format( buyer, sell_property, price)) if buyer_decision == 'Y' or buyer_decision == 'y': player.sell_property(buyer, sell_property, price, self.blockchain) else: print('{} rejected the offer.'.format(buyer)) else: print('{} is not a valid player index, try again.'.format( buyer)) else: print('{} is not an index you can trade, try again tiger.'. format(trade_index)) decision = input('Continue trading? Y/N: ') if not decision == 'Y' and not decision == 'y': keep_trading = False def serve_prop_edit(self, player): all_properties = player.describe_all_properties( self.blockchain, self.board) # Prints all properties as well keep_editing = True while keep_editing: edit_index = int(input('Index to edit: ')) if edit_index in all_properties: player.edit_property(self.blockchain, self.board, edit_index) decision = input('Continue editing? Y/N: ') if not decision == 'Y' and not decision == 'y': keep_editing = False # Describes a property's rent and mortgage @staticmethod def describe_property(space): if space.type == 'Utility': print( ' If one utility is owned rent is 4 times amount shown on dice.\n' + ' If both utilities are owned rent is 10 times amount shown on dice.' ) elif space.type == 'Station': print(' Rent ${}\n'.format(space.standard_rent) + ' If 2 stations are owned ${}\n'.format( space.standard_rent * 2) + ' If 3 stations are owned ${}\n'.format( space.standard_rent * 3) + ' If 4 stations are owned ${}'.format( space.standard_rent * 4)) else: print(' Color Group: {}\n'.format(space.group) + ' Rent ${}\n'.format(space.standard_rent) + ' With 1 House ${}\n'.format(space.one_house_rent) + ' With 2 Houses ${}\n'.format(space.two_house_rent) + ' With 3 Houses ${}\n'.format(space.three_house_rent) + ' With 4 Houses ${}\n'.format(space.four_house_rent) + ' With Hotel ${}'.format(space.hotel_rent)) print(' Mortgage Value: ${}'.format(space.mortgage)) # Moves a player to the given index. If at 30, the player goes to jail def move_player_to(self, player, index): if index < player.position: print('{} passed Go!'.format(str(player))) self.banker.pay(player, 200, self.blockchain) if index == 30: self.go_to_jail(player) else: player.position = index @staticmethod def go_to_jail(player): print('{} went to Jail!'.format(player)) player.in_jail = True player.position = 10 def game_over(self): finished_players = 0 for player in self.players: if player.state == PlayerState.DONE: finished_players += 1 if finished_players - 1 == len(self.players): return True else: return False