Example #1
0
 def __init__(self, client_1, client_2):
     super(GameThread, self).__init__()
     self.client_1 = client_1
     self.client_2 = client_2
     self.nick_1 = ""
     self.nick_2 = ""
     self.board = Board()
Example #2
0
    def winning_message(self):
        """
        This function is printing centred WINNER text
        :return: None
        """
        winning_str_formating = f"And the winner is: {self.name_of_next_player(False)}"
        # ^taking name without changing player^
        len_of_text = len(
            winning_str_formating)  # variable taking lenght of "winner" text
        if len_of_text > self.len_of_message_after_game:  # if "winner" text is longer than base 40
            self.len_of_message_after_game = len_of_text
        len_text = (
            (self.len_of_message_after_game - len_of_text) // 2 + len_of_text
        )  # variable that calculate center

        self.adding_message_border(self.len_of_message_after_game)
        print(winning_str_formating.rjust(
            len_text, " "))  # printing out "winning" text in middle of lanes
        self.adding_message_border(self.len_of_message_after_game)

        Board.showing_vitory_lane_on_board(self.board_rows_2D_list,
                                           self.winning_type,
                                           self.winning_pos)  # drawing lane
        Board.print_board(
            self.board_rows_2D_list
        )  # Calling Board to print itself changed in game to show it last time
Example #3
0
    def test__toElements__initialboard(self):
        b = Board()
        b.reset()

        elements = b.toElements()

        expected = {
            'board':
            'RNBQKBNRPPPPPPPP________________________________pppppppprnbqkbnr',
            'castleable': 'KLSkls',
            'taken': ''
        }

        self.assertDictEqual(elements, expected)
Example #4
0
    def drawing_message(self):
        """
        This function is printing centered TIE text.
        :return: None
        """
        tie_str_text = 'Tie'
        len_of_text = len(tie_str_text)
        len_text = (
            (self.len_of_message_after_game - len_of_text) // 2 + len_of_text
        )  # centering Tie text

        self.adding_message_border(self.len_of_message_after_game)
        print(tie_str_text.rjust(len_text, ' '))  # printing "drawing" text
        self.adding_message_border(self.len_of_message_after_game)

        Board.print_board(
            self.board_rows_2D_list)  # printing Board to show last move
Example #5
0
    def __init__(self, colors):
        self._state = ''

        self._players = tuple([Player(c) for c in colors])

        self._board = None

        self._message = ''

        self._states = {
            ('*', 'error'): 'error',
            ('', 'init'): 'income',
            ('income', 'incomed'): 'building',
            ('income', 'some_ship'): 'change_ship',
            ('change_ship', 'changed'): 'building',
            ('change_ship', 'red_ship'): 'pirate',
            ('pirate', 'pirated'): 'building',
            ('building', 'build'): 'building2',
            ('building2', 'build'): 'claim',
            ('building', 'firstChurch'): 'firstChurch',
            ('building2', 'firstChurch'): 'firstChurch2',
            ('firstChurch', 'build'): 'building2',
            ('firstChurch2', 'build'): 'claim',
            ('building', 'skip'): 'claim',
            ('building2', 'skip'): 'claim',
            ('claim', 'claimed'): 'adding',
            ('claim', 'skip'): 'adding',
            ('adding', 'add'): 'income',
            ('adding', 'skip'): 'income',
            ('*', 'win'): 'winner',
        }

        self._colors = ['red', 'blue', 'green', 'yellow']

        self._sumDice = SumDice(2, 6)

        # TODO check double colors
        if (len(colors) < 2 or len(colors) > 4):
            self._setError('Count of players must be 2, 3 or 4')
            self._players = ()
            return

        self._currentPlayerIndex = random.randrange(len(self._players))
        self._board = Board(self._colors, self._players)
        self._changeState('init')
Example #6
0
    def test__updateFromElements__board(self):
        b = Board()
        b.reset()

        expected = b.toString()

        b.updateFromElements(**self.fakeElements())

        startStrUpdated = b.toString()

        self.assertEqual(startStrUpdated, expected)
Example #7
0
    def __init__(self):
        self.board_rows_2D_list = Board.board_from_file(
            Board())  # Taking an empty board from Board class
        """p_circe/ p_cross - listing moves of Player subclasses
        player_win_logs - listing logs of winners in rounds
        """
        self.p_circle_moves, self.p_cross_moves, self.player_win_logs = [], [], []
        # actual_player - after coin flip, I have to pass information, which player is moving... 0- Circle, 1 - Cross
        self.actual_player = -1
        """winning_type/ winning_pos - Helps to pass informations about lane to create - is it diagonal from left top,
                                    or left bottom or at 1/2/3 or a/b/c
        winning_type 1- \\ 2- / 3- - 4- |         winning_pos taking just 2/6/10 - which are ids` in-Board 
        """
        self.winning_type, self.winning_pos = [], []
        self.are_logs_loaded = ""  # Taking var from input (yes/no) - ask about contiunue/ start from scratch logs
        # Taking names from players
        self.name_of_player_one = " "  # empty placeholder
        self.player_circle = PlayerCircle(self.name_of_player_one)
        self.name_of_player_two = " "
        self.player_cross = PlayerCross(self.name_of_player_two)

        self.game_loop(True)  # Starting game and (take names plz)
Example #8
0
 def toBoard(self):
     board = Board()
     board.reset()
     enpassantColumn = self.enpassantColumn()
     enpassant = chr(enpassantColumn +
                     ord('a')) if enpassantColumn is not None else None
     winner = None  # TODO better way to get for unit testing self.game.winner
     board.updateFromElements(self.board, self.taken, self.castleable,
                              enpassant, winner)
     return board
Example #9
0
    def test__toElements__someboard(self):
        b = Board()
        b.reset()
        b.castleable = sorted(['kb', 'kw', 'rkb'])
        b.taken = ['bb', 'rb', 'rw', 'pw']

        elements = b.toElements()

        expected = {
            'board':
            'RNBQKBNRPPPPPPPP________________________________pppppppprnbqkbnr',
            'castleable': 'KSk',
            'taken': 'BRrp'
        }

        self.assertDictEqual(elements, expected)
Example #10
0
    def test__Board__move(self):

        self.maxDiff=None
        board = Board()
        board.reset()
        status, accepted_move_list, msg = board.move(6,4,4,4)
        print(f"new board {status} - {accepted_move_list} - {msg}")
        print(board.toString())
        self.assertTrue(status)
        self.assertListEqual(accepted_move_list, [6,4,4,4])
        self.assertEqual(board.toString(), (
            "rb_nb_bb_qb_kb_bb_nb_rb_"
            "pb_pb_pb_pb_pb_pb_pb_pb_"
            "________"
            "________"
            "____pw____"
            "________"
            "pw_pw_pw_pw__pw_pw_pw_"
            "rw_nw_bw_qw_kw_bw_nw_rw"
            "##kb_kw_rkb_rkw_rqb_rqw#4#n"
            )
        )
Example #11
0
    def test__toElements__anotherboard(self):
        b = Board()
        b.reset()
        b.board[0][2] = ''
        b.board[0][5] = ''
        b.board[0][7] = ''
        b.board[1][3] = 'pw'
        b.board[1][4] = ''
        b.board[5][7] = 'bb'
        b.board[6][3] = ''
        b.board[6][5] = ''
        b.board[7][0] = ''
        b.castleable = sorted(['kb', 'kw', 'rkb'])
        b.taken = ['bb', 'rb', 'rw', 'pw', 'pb']

        elements = b.toElements()

        expected = {
            'board':
            'RN_QK_N_PPPp_PPP_______________________________Bppp_p_pp_nbqkbnr',
            'castleable': 'KSk',
            'taken': 'BRrpP'
        }

        self.assertDictEqual(elements, expected)
Example #12
0
class GameThread(threading.Thread):
    def __init__(self, client_1, client_2):
        super(GameThread, self).__init__()
        self.client_1 = client_1
        self.client_2 = client_2
        self.nick_1 = ""
        self.nick_2 = ""
        self.board = Board()

    def run(self):
        self.nick_1 = waitForMessage(self.client_1, 'NICK')
        self.nick_2 = waitForMessage(self.client_2, 'NICK')
        filename = time.strftime("games/%Y_%m_%d_%H_%M_%S")
        filename += "_" + self.nick_1 + "_Vs_" + self.nick_2 + ".txt"
        log = open(filename, "w")
        log.write(self.nick_1 + ' Vs. ' + self.nick_2 + '\n')

        sendData(self.client_1, 'URLR',
                 "http://git.sxbn.org/battleChess/" + filename)
        sendData(self.client_2, 'URLR',
                 "http://git.sxbn.org/battleChess/" + filename)

        sendData(self.client_1, 'NICK', self.nick_2)
        sendData(self.client_2, 'NICK', self.nick_1)

        loop = True
        try:
            while loop:
                valid = False
                while not valid:
                    head, move = recvData(self.client_1)
                    if head == "OVER":
                        loop = False
                        raise ValueError()  # jump to finaly
                    elif head == 'MOVE':
                        i, j, ii, jj = move
                        valid, pos, msg = self.board.move(i, j, ii, jj, 'w')
                        # print "got move from", [i,j], "to", [ii,jj], "from white", valid
                        sendData(self.client_1, 'VALD', valid)
                    else:
                        print('error : server was expecting MOVE, not', head)
                        raise ValueError()

                log.write("%d %d %d %d\n" % (i, j, ii, jj))
                if self.board.winner:  # if we have a winner, send the whole board
                    endBoard = self.board.toString()
                    sendData(self.client_1, 'BORD', endBoard)
                    sendData(self.client_2, 'BORD', endBoard)
                    break  # game is over
                else:
                    sendData(self.client_1, 'BORD', self.board.toString('w'))
                    sendData(self.client_2, 'BORD', self.board.toString('b'))

                valid = False
                while not valid:
                    head, move = recvData(self.client_2)
                    if head == "OVER":
                        loop = False
                        raise ValueError()  # jump to finaly
                    elif head == 'MOVE':
                        i, j, ii, jj = move
                        valid, pos, msg = self.board.move(i, j, ii, jj, 'b')
                        # print "got move from", [i,j], "to", [ii,jj], "from black", valid
                        sendData(self.client_2, 'VALD', valid)
                    else:
                        print('error : server was expecting MOVE, not', head)
                        raise ValueError()

                log.write("%d %d %d %d\n" % (i, j, ii, jj))
                if self.board.winner:  # if we have awinner, send the whole board
                    endBoard = self.board.toString()
                    sendData(self.client_1, 'BORD', endBoard)
                    sendData(self.client_2, 'BORD', endBoard)
                    break  # game is over
                else:
                    sendData(self.client_1, 'BORD', self.board.toString('w'))
                    sendData(self.client_2, 'BORD', self.board.toString('b'))
        except Exception as e:
            print(e)
            traceback.print_exc(file=sys.stdout)
            pass
        finally:  # Always close the game
            # print "finishing the game"
            log.flush()
            log.close()
            sendData(self.client_1, 'OVER', None)
            sendData(self.client_2, 'OVER', None)
            self.client_1.close()
            self.client_2.close()
Example #13
0
class Elasund():

    def __init__(self, colors):
        self._state = ''

        self._players = tuple([Player(c) for c in colors])

        self._board = None

        self._message = ''

        self._states = {
            ('*', 'error'): 'error',
            ('', 'init'): 'income',
            ('income', 'incomed'): 'building',
            ('income', 'some_ship'): 'change_ship',
            ('change_ship', 'changed'): 'building',
            ('change_ship', 'red_ship'): 'pirate',
            ('pirate', 'pirated'): 'building',
            ('building', 'build'): 'building2',
            ('building2', 'build'): 'claim',
            ('building', 'firstChurch'): 'firstChurch',
            ('building2', 'firstChurch'): 'firstChurch2',
            ('firstChurch', 'build'): 'building2',
            ('firstChurch2', 'build'): 'claim',
            ('building', 'skip'): 'claim',
            ('building2', 'skip'): 'claim',
            ('claim', 'claimed'): 'adding',
            ('claim', 'skip'): 'adding',
            ('adding', 'add'): 'income',
            ('adding', 'skip'): 'income',
            ('*', 'win'): 'winner',
        }

        self._colors = ['red', 'blue', 'green', 'yellow']

        self._sumDice = SumDice(2, 6)

        # TODO check double colors
        if (len(colors) < 2 or len(colors) > 4):
            self._setError('Count of players must be 2, 3 or 4')
            self._players = ()
            return

        self._currentPlayerIndex = random.randrange(len(self._players))
        self._board = Board(self._colors, self._players)
        self._changeState('init')

    def getPlayers(self):
        return self._players

    def getCurrentPlayer(self):
        return self._players[self._currentPlayerIndex]

    def getState(self):
        return self._state

    def getTiles(self):
        return self._board.tiles

    def getBuildings(self):
        return self._board.buildings

    @checkStateDecorator(('income',), 'Error: current state is not income')
    @returnOkIfNotError
    def income(self):
        dice = self._sumDice.next()

        self._board.shipIsRed = dice == 7
        if dice == self._board.shipPosition or self._board.shipIsRed:
            self._changeState('some_ship')
            return 'change_ship'

        ''' Income '''
        self._board.shipPosition = dice
        self._calcIncome()
        self._changeState('incomed')

    @checkStateDecorator(('change_ship',), 'Error: current state is not change_ship')
    @returnOkIfNotError
    def change_ship(self, row):
        if row < 2 or row > 12 or row == 7:
            return 'Error: incorrect row value'
        if row == self._board.shipPosition:
            return 'Error: no choise some ship position'

        if self._board.shipIsRed:
            self._board.shipPosition = row
            self._changeState('red_ship')
            return {'success': 'pirate_ship', 'cards': self._board.getCountCubeByRow(), 'current_player_count_on_walls': self._board.getCountCubeOnWallByPlayer(self.getCurrentPlayer().getColor())}
        else:
            correct_pos = {
                2: (4, ),
                3: (5, ),
                4: (2, 6, ),
                5: (3, 8, ),
                6: (4, 9, ),
                8: (5, 10, ),
                9: (6, 11, ),
                10: (8, 12, ),
                11: (9, ),
                12: (10, ),
            }
            if row in correct_pos[self._board.shipPosition]:
                self._board.shipPosition = row
                self._calcIncome()
                self._changeState('changed')
            else:
                return 'Error: next position must be diff 2'

    @checkStateDecorator(('pirate',), 'Error: current state is not pirate')
    @returnOkIfNotError
    @changeStateOnSuccessful('pirated')
    def pirate(self, cards, needCurentPlayer):
        needCards = self._board.getCountCubeByRow()
        for color, count in needCards:
            player = None
            for p in self._players:
                if p.getColor() == color:
                    player = p
                    break
            gold = cards.get(color, {}).get('gold', 0)
            if player.gold < gold:
                return 'Error: %s player need %s gold' % (color, gold)

            red = cards.get(color, {}).get('red', 0)
            if player.votes['red'] < red:
                return 'Error: %s player need %s red vote card' % (color, red)

            green = cards.get(color, {}).get('green', 0)
            if player.votes['green'] < green:
                return 'Error: %s player need %s green vote card' % (color, green)

            blue = cards.get(color, {}).get('blue', 0)
            if player.votes['blue'] < blue:
                return 'Error: %s player need %s blue vote card' % (color, blue)

            if (gold + red + blue + green) != count:
                return 'Error: %s player must give %s cards' % (color, count)

        countCubesOnWalls = self._board.getCountCubeOnWallByPlayer(self.getCurrentPlayer().getColor())
        gold = needCurentPlayer.get(color, {}).get('gold', 0)
        red = needCurentPlayer.get(color, {}).get('red', 0)
        green = needCurentPlayer.get(color, {}).get('green', 0)
        blue = needCurentPlayer.get(color, {}).get('blue', 0)
        if (gold + red + blue + green) != countCubesOnWalls:
            return 'Error: current player must take %s cards' % countCubesOnWalls

        for color, count in needCards:
            player = None
            for p in self._players:
                if p.getColor() == color:
                    player = p
                    break
            player.gold -= cards.get(color, {}).get('gold', 0)
            player.votes['red'] -= cards.get(color, {}).get('red', 0)
            player.votes['green'] -= cards.get(color, {}).get('green', 0)
            player.votes['blue'] -= cards.get(color, {}).get('blue', 0)

        currentPlayer = self.getCurrentPlayer()
        currentPlayer.gold += needCurentPlayer.get(color, {}).get('gold', 0)
        currentPlayer.votes['red'] += needCurentPlayer.get(color, {}).get('red', 0)
        currentPlayer.votes['green'] += needCurentPlayer.get(color, {}).get('green', 0)
        currentPlayer.votes['blue'] += needCurentPlayer.get(color, {}).get('blue', 0)

    @checkStateDecorator(('building', 'building2', ), 'Error: current state is not building')
    @returnOkIfNotError
    @changeStateOnSuccessful('build')
    def build(self, position, building, **addition):
        if building.getType() == 'church':
            return 'Error: use buildChurch'
        size = building.getSize()
        square = size[0] * size[1]

        player = self.getCurrentPlayer()

        if building.getType() in ['house', 'small_totem', 'totem', 'workshop']:
            if building.getColor() != player.getColor():
                return 'Error: this building to another player'

        buildings = []
        claims = {c: 0 for c in self._colors}
        count_claims = 0
        for x in range(size[0]):
            for y in range(size[1]):
                pos = (position[0] + x, position[1] + y,)
                cell = self._board.cells.get(pos, None)
                if cell is not None:
                    if cell['type'] == 'ref':
                        cell = self._board.cells[cell['position']]

                    if cell['type'] == 'claim':
                        claims[cell['claim']['color']] += cell['claim']['value']
                        count_claims += 1
                    elif cell['type'] == 'building':
                        buildings.append(cell['building'])

        for b in buildings:
            if b.getType() in ['church']:
                return 'Church cannot destroy'
            b_size = b.getSize()
            b_square = b_size[0] * b_size[1]
            if square <= b_square:
                return 'Building in (%s, %s) more or equal then current' % pos

        other_gold = 0
        for color, value in claims.items():
            if color != self.getCurrentPlayer().getColor():
                other_gold += value

        if player.gold < building.getCost() + other_gold:
            return 'Need more gold'

        my_claimValue = claims[self.getCurrentPlayer().getColor()]
        for color, value in claims.items():
            if color != self.getCurrentPlayer().getColor() and my_claimValue <= value:
                return 'Current player is not greater claims'

        if count_claims < building.getNeedCountClaims():
            return 'Need more claims'

        # end checked - build building
        player.gold -= building.getCost()
        player.gold -= other_gold

        for color, value in claims.items():
            if color != self.getCurrentPlayer().getColor():
                for p in self._players:
                    if p.getColor() == color:
                        p.gold += value
                        break

        for x in range(size[0]):
            for y in range(size[1]):
                pos = (position[0] + x, position[1] + y,)
                cell = self._board.cells.get(pos, None)
                if cell is not None:
                    if cell['type'] == 'ref':
                        cell = self._board.cells[cell['position']]

                    if cell['type'] == 'claim':
                        self._board.removeClaim(pos)
                    elif cell['type'] == 'building':
                        self._preDestroy(cell['building'], pos)

        self._preBuild(building, position)

    @checkStateDecorator(('building', 'building2', ), 'Error: current state is not building')
    @returnOkIfNotError
    @changeStateOnSuccessful('build')
    def buildWall(self, position):
        player = self.getCurrentPlayer()
        wall = player.getNextWall()
        if wall['type'] == 'none':
            return 'Error: player build max walls'

        wall_cost = self._board.getWallCost(position)
        if wall_cost <= 0:
            return 'Error: cell is not for wall'
        if player.gold < wall_cost:
            return 'Error: player need more gold'

        if wall['type'] == 'point':
            self._removeVictoryPoint(player, 1)
        elif wall['type'] == 'vote':
            for i in range(wall['count']):
                player.votes[self._board.getRandomVote()] += 1

        msg = self._board.buildWall(position, wall['value'], player.getColor())
        if msg is not None:
            return msg

    @checkStateDecorator(('building', 'building2', ), 'Error: current state is not building')
    @returnOkIfNotError
    @changeStateOnSuccessful('build')
    def buildChurch(self):
        if len(self._board.buildings['church']) == 9:
            return 'Error: first time use buildFirstChurch()'

        first_church_on_map = self._board.cells[(2, 5,)]
        first_index = first_church_on_map.getIndex()
        next_church = self._board.buildings['church'][0]
        next_index = next_church.getIndex()
        pos = (2 + ((next_index - 1) % 3) - ((first_index - 1) % 3),
               5 + ((next_index + 1) // 3) - ((first_index + 1) // 3)
               )

        self._board.destroyBuilding(pos)
        self._board.buildBuilding(next_church, pos)

    @checkStateDecorator(('building', 'building2', ), 'Error: current state is not building')
    def buildFirstChurch(self):
        if len(self._board.buildings['church']) != 9:
            return 'Error: use buildChurch()'

        result = [self._board.buildings['church'][i]._index for i in range(2)]

        self._changeState('firstChurch')
        return {'success': 'ok', 'values': result}

    @checkStateDecorator(('firstChurch', 'firstChurch2', ), 'Error: current state is not firstChurch')
    @returnOkIfNotError
    @changeStateOnSuccessful('build')
    def selectFirstChurch(self, index):
        if len(self._board.buildings['church']) != 9:
            return 'Error: use buildChurch()'
        if index != 0 and index != 1:
            return 'Error: index must be 0 or 1'
        self._board.destroyBuilding((2, 5,))
        self._board.buildBuilding(self._board.buildings['church'][i], (2, 5,))

    @checkStateDecorator(('claim',), 'Error: current state is not claim')
    @returnOkIfNotError
    @changeStateOnSuccessful('claimed')
    def claim(self, position, value, **addition):
        return self._board.putClaim(self.getCurrentPlayer().getColor(), value, position)

    @checkStateDecorator(('claim',), 'Error: current state is not claim')
    @returnOkIfNotError
    @changeStateOnSuccessful('claimed')
    def takeTwoGold(self):
        self.getCurrentPlayer().gold += 2

    @checkStateDecorator(('adding',), 'Error: current state is not adding')
    @returnOkIfNotError
    @changeStateOnSuccessful('add')
    def adding(self, action):
        # TODO release adding
        pass

    @checkStateDecorator(('building', 'building2', 'claim', 'adding'), 'Error: current state is not correct')
    @returnOkIfNotError
    @changeStateOnSuccessful('skip')
    def skip(self):
        pass

    def victory(self, player):
        self._changeState('win')
        self._message = '%s player is win' % player.getColor()

    def _calcIncome(self):
        ''' Income '''
        y = self._board.getRowByDice(self._board.shipPosition)
        for x in range(0, self._board.getMaxWidthBoard() + 1):
            pos = (x, y,)
            cell = self._board.cells.get(pos, None)
            if cell is None:
                break

            if cell['type'] == 'ref':
                cell = self._board.cells[cell['position']]

            if cell['type'] != 'building':
                break

            building = cell['building']
            incomeType = building.getIncomeType()
            if incomeType is None:
                break

                for p in self._players:
                    if p.getColor() == building.getColor():
                        if incomeType == 'gold':
                            p.gold += 1
                        elif incomeType == 'vote':
                            p.votes[self._board.getRandomVote()] += 1
                        break

    def _preBuild(self, building, position):
        building.setColor(self.getCurrentPlayer().getColor())
        self.getCurrentPlayer().mills += self._board.getCountMills(position)
        self._removeVictoryPoint(self.getCurrentPlayer(), building.getCubes())
        self._board.buildBuilding(building, position)

    def _preDestroy(self, building, position):
        for p in self.getPlayers():
            if p == building.getColor():
                p.mills -= self._board.getCountMills(position)
                self._addVictoryPoint(p, building.getCubes())
                break
        self._board.destroyBuilding(position)

    def _setError(self, msg):
        self._changeState('error')
        self._message = msg

    def _changeState(self, cmd):
        if (self._state, cmd) in self._states:
            self._state = self._states.get((self._state, cmd), self._state)
        elif ('*', cmd) in self._states:
            self._state = self._states.get(('*', cmd), self._state)

    def _addVictoryPoint(self, player, value):
        player.victoryPoint += value

    def _removeVictoryPoint(self, player, value):
        player.victoryPoint -= value
        if player.victoryPoint <= 0:
            count_check = 0
            for pos, cell in self._board.cells.items():
                if cell['type'] == 'building':
                    if cell['building'].getColor() == player.getColor():
                        count_check += cell['building'].getCubes()

            count_check += self._board.getCubesByMills(player.mills)

            count_check += (player._wall - 1) / 3

            if count_check >= 10:
                self.victory(player)
            else:
                self.error = 'Check count cubes on %s player' % player.getColor()

    def _nextPlayer(self):
        self._currentPlayerIndex = (self._currentPlayerIndex + 1) % len(self.getPlayers())
Example #14
0
 def initialize_board(self):
     colors = ['red', 'blue', 'green', 'yellow']
     players = tuple(Player(c) for c in colors)
     return Board(colors, players)
Example #15
0
    def game_loop(self, is_game_taking_names_logs_info):
        """
        Making a game loop that call other functions and count moves (Only one time in sesion You can give names)
        If players want rematch set every variable/ attribute to starting values.
        :param is_game_taking_names_logs_info: If game have 1st initialization I need to get names.
        In every next games in same session they use same names, so don't need for asking about names.
        :return: None
        """
        while is_game_taking_names_logs_info:  # if game have fresh start it need names and info what to to with logs
            print("Hello in my TicTacToe game")
            self.taking_logs_input()
            self.taking_names_input()
            is_game_taking_names_logs_info = False  # and in every game loop this shouldn't be asked
        are_we_still_playing = True  # if not exited, drawed or won
        does_player_said_exit = False  # does player said "exit" or not
        while are_we_still_playing:  # if there is no win/draw
            are_we_still_playing = not (
                self.is_victory())  # if there is no win, we're still playing
            if not are_we_still_playing:  # if we don't play, exit loop
                break
            count_moves = (
                (-1) * len(self.allowed_moves)
            ) + 9  # getting number of moves i.e: when there are 3 moves -3+9=6
            if count_moves == 9:  # if there was 9 moves and was no winner -  round is draw and end loop of playing
                self.player_win_logs.append('d')  # "remembering" this is draw
                self.drawing_message()
                break
            else:
                Board.print_board(self.board_rows_2D_list)
                if self.taking_a_player_move(
                ):  # making move, and when player said "exit" there is no more playing
                    does_player_said_exit = True
                    break
        if does_player_said_exit:  # if there was "exit"... game should be stopped
            print("\nGame has no winners or tie."
                  )  # print in new row and end game
            if self.are_logs_loaded == 'yes':  # from player answer about logs
                Logs.logs_with_load(
                    Logs(self.name_of_player_one, self.name_of_player_two,
                         self.player_win_logs))
            else:  # if they end any round I paste logs to .txt, coz I will overwrite it everytime
                Logs.logs_without_load(
                    Logs(self.name_of_player_one, self.name_of_player_two,
                         self.player_win_logs))
            return
        if self.player_win_logs[
                -1] != 'd':  # if in while we got "there is win", now I show text about it
            self.winning_message()
        are_you_want_rematch = input(
            "Are you want to play agine? (yes/whatever) ").lower(
            )  # asking about rematch
        if self.are_logs_loaded == 'yes':  # from player answer about logs
            if are_you_want_rematch != 'yes':  # if they stop playing, I'm pasting logs to .txt
                Logs.logs_with_load(
                    Logs(self.name_of_player_one, self.name_of_player_two,
                         self.player_win_logs))
        else:  # if they end any round I paste logs to .txt, coz I will overwrite it everytime
            Logs.logs_without_load(
                Logs(self.name_of_player_one, self.name_of_player_two,
                     self.player_win_logs))

        if are_you_want_rematch == 'yes':  # When there is rematch, I want to reset every value to starting values
            self.board_rows_2D_list = Board.board_making(Board())
            self.allowed_moves = {
                'a1': (2, 2),
                'b1': (2, 6),
                'c1': (2, 10),
                'a2': (6, 2),
                'b2': (6, 6),
                'c2': (6, 10),
                'a3': (10, 2),
                'b3': (10, 6),
                'c3': (10, 10)
            }
            self.p_circle_moves, self.p_cross_moves = [], []
            self.winning_type, self.winning_pos = [], []
            # self.coinflip = rr(0, 2)  # if starter player should be more randomized, than only at begining
            self.len_of_message_after_game = 40
            self.game_loop(
                False
            )  # Starting game agine, but now don't ask about names agine
Example #16
0
 def snapOptionsFromBoard(self, board: Board, accepted_move):
     snapOptions = board.toElements()
     snapOptions["move"] = accepted_move
     return snapOptions