Exemple #1
0
    def setState(self, state):

        self.cHP = state[0]
        self.moves = [
            Move.Move(c.PM[self.index][0], state[1]),
            Move.Move(c.PM[self.index][1], state[2])
        ]
Exemple #2
0
 def getBishopMoves(self, row, col, moves):
     piecePinned = False
     pinDirection = ()
     for i in range(len(self.pins) - 1, -1, -1):
         if (self.pins[i][0] == row and self.pins[i][1] == col):
             piecePinned = True
             pinDirection = (self.pins[i][2], self.pins[i][3])
             if self.board[row][col][
                     1] != 'Q':  #can't remove queen from pin on rook moves, only remove it on bishop moves, b/c getQueenMoves calls getRookMoves
                 self.pins.remove(self.pins[i])
             break
     directions = (
         (-1, -1), (-1, 1), (1, -1), (1, 1))  #up, left, down, right
     enemyColor = 'b' if self.whiteToMove else 'w'
     for d in directions:
         for i in range(1, 8):
             endRow = row + d[0] * i
             endCol = col + d[1] * i
             if 0 <= endRow < 8 and 0 <= endCol < 8:  #on board
                 if not piecePinned or pinDirection == d or pinDirection == (
                         -d[0], -d[1]):  #see rook explanation
                     endPiece = self.board[endRow][endCol]
                     if endPiece == "--":  #empty space valid
                         moves.append(
                             Move((row, col), (endRow, endCol), self.board))
                     elif endPiece[0] == enemyColor:  #enemy piece valid
                         moves.append(
                             Move((row, col), (endRow, endCol), self.board))
                         break
                     else:  #friendly place invalid
                         break
             else:  #off brand
                 break
Exemple #3
0
 def g_min(self, board, depth):
     if board.terminal_state() or depth == self.max_depth:
         last_move = Move.Move(board.get_last_move().get_row(),
                               board.get_last_move().get_col())
         return last_move
     children = board.get_children(-1)
     min_move = Move.Move(1000)
     min_score = board.victor()
     # temp_board = Board.Board()
     for child in children:
         move = self.g_max(child, depth + 1)
         temp_board = copy.deepcopy(child)
         temp_board.make_move(move.get_row(), move.get_col(),
                              move.get_val())
         if temp_board.victor() <= min_score:
             if temp_board.victor() == min_score:
                 if random.randint(0, 1) == 0:
                     min_move.set_row(child.get_last_move().get_row())
                     min_move.set_col(child.get_last_move().get_col())
                     min_move.set_val(move.get_val())
                     min_score = child.victor()
             else:
                 min_move.set_row(child.get_last_move().get_row())
                 min_move.set_col(child.get_last_move().get_col())
                 min_move.set_val(move.get_val())
                 min_score = child.victor()
     return min_move
Exemple #4
0
    def parseProperty(self, node, isroot):
        '''
        parse contents in one node
        '''
        name = self.m_tokenizer.sval

        done = False
        while not done:
            ttype = self.m_tokenizer.nextToken()
            if ttype != '[':
                done = True
            self.m_tokenizer.pushBack()
            if done: break
            
            if name == 'C':
                val = self.parseComment()
            else:
                val = self.parseValue()
            # print(name + '[' + val + ']')

            if name == 'W':
                point = HexPoint.get(val)
                node.setMove(Move.Move(point, HexColor.WHITE))
            elif name == 'B':
                point = HexPoint.get(val)
                node.setMove(Move.Move(point, HexColor.BLACK))
            elif name == 'AB':
                node.addSetup(HexColor.BLACK, HexPoint.get(val))
            elif name == 'AW':
                node.addSetup(HexColor.WHITE, HexPoint.get(val))
            elif name == 'AE':
                node.addSetup(HexColor.EMPTY, HexPoint.get(val))
            elif name == 'LB':
                node.addLabel(val)
            elif name == 'FF':
                node.setSgfProperty(name, val)
                x = self.parseInt(val)
                if x < 1 or x > 4:
                    raise self.SgfError("Invalid SGF Version! (" + x + ")")
            elif name == 'GM':
                node.setSgfProperty(name, val)
                if not isroot:
                    self.sgfWarning("GM property in non-root node!")
                if self.parseInt(val) != self.__GM_HEXGAME:
                    raise self.SgfError("Not a Hex game!")
            elif name == 'SZ':
                node.setSgfProperty(name, val)
                if not isroot: self.sgfWarning("GM property in non-root node!")
                sp = val.split(':')
                if len(sp) == 1:
                    x = self.parseInt(sp[0])
                    self.m_gameinfo.setBoardSize(x,x)
                elif len(sp) == 2:
                    x = self.parseInt(sp[0])
                    y = self.parseInt(sp[1])
                    self.m_gameinfo.setBoardSize(x,y)
                else:
                    raise self.SgfError("Malformed boardsize!")
            else:
                node.setSgfProperty(name, val)
Exemple #5
0
    def getMove(self, currentState):
        coords = self.coordList
        chosenMove = None

        #check if no move has been submitted first
        if self.moveType == None:
            return None

        #callbacks have made sure coord list
        #wasn't empty if we got to this point

        #create the appropriate move
        if self.moveType == MOVE_ANT:
            chosenMove = Move(MOVE_ANT, coords, None)
        elif self.moveType == BUILD:
            if self.buildType == None:
                return None
            #callbacks have checked to make sure coord list is length 1
            loc = currentState.board[coords[0][0]][coords[0][1]]

            #we also know from callback that loc contains ant OR hill, not both
            chosenMove = Move(BUILD, coords, self.buildType)

        elif self.moveType == END:
            chosenMove = Move(END, None, None)
        else:
            #bad move type
            pass

        #clear out move type and coord list
        self.moveType = None
        self.buildType = None
        self.coordList = []

        return chosenMove
 def getPossibleMoves(self):
     return [
         Move(0, 1, False),
         Move(1, 0, False),
         Move(0, -1, False),
         Move(-1, 0, False)
     ]
Exemple #7
0
    def get_moves(self):
        moves = []
        direction = self.active_player.direction

        pieces = self.get_pieces(self.active_player)
        for piece in pieces:
            #print(str(piece.row) + ',' + str(piece.col))
            # Straight
            if piece.row + direction >= 0 and piece.row + direction < self.board.rows:
                if self.board.board[piece.row +
                                    direction][piece.col].value == '-':
                    moves.append(
                        Move.Move((piece.row, piece.col),
                                  (piece.row + direction, piece.col)))
            # Left
            if piece.row + direction >= 0 and piece.row + direction < self.board.rows:
                if piece.col + direction >= 0 and piece.col + direction < self.board.cols:
                    if self.board.board[piece.row + direction][
                            piece.col +
                            direction].value != self.active_player.symbol:
                        moves.append(
                            Move.Move((piece.row, piece.col),
                                      (piece.row + direction,
                                       piece.col + direction)))
            # Right
            if piece.row + direction >= 0 and piece.row + direction < self.board.rows:
                if piece.col - direction >= 0 and piece.col - direction < self.board.cols:
                    if self.board.board[piece.row + direction][
                            piece.col -
                            direction].value != self.active_player.symbol:
                        moves.append(
                            Move.Move((piece.row, piece.col),
                                      (piece.row + direction,
                                       piece.col - direction)))

        sorted_moves = []
        for move in moves:
            if self.board.board[move.newPosition[0]][
                    move.newPosition[1]].value != '-':
                sorted_moves.insert(0, move)
            elif self.active_player.symbol == 'o' and move.newPosition[
                    0] < self.active_player.shortest_distance:
                sorted_moves.insert(0, move)
            elif self.active_player.symbol == 'x' and (
                    7 - move.newPosition[0]
            ) < self.active_player.shortest_distance:
                sorted_moves.insert(0, move)
            else:
                sorted_moves.append(move)

        #for move in moves:
        #print(str(move.currentPosition[0]) + ',' + str(move.currentPosition[1]) + " to " + str(move.newPosition[0]) + ',' + str(move.newPosition[1]))

        return sorted_moves
    def list_all_legal_moves(self):
        retVal = []
        for richtung in [-1, +1, 0]:
            for bauer in self.posWhite:
                move = Move(bauer, richtung)
                if self.checkIfLegal(move):
                    retVal.append(move)

        if len(retVal) == 0:
            move = Move(None, None, True)  # Pass
            retVal.append(move)

        return retVal
Exemple #9
0
    def _extendRight(self, partialWord, node, row, col, firstAnchor, score):
        """Place right portion of word"""
        if row > 14:
            return
        if col == 15:
            if node.endsWord and not firstAnchor:
                # found legal move
                foundMove = Move.Move(partialWord, row, col - 1, score)
                self.moveList.append(foundMove)
            return
        if self.boardState[row][col].isEmpty():
            if node.endsWord and not firstAnchor:
                # found legal move
                foundMove = Move.Move(partialWord, row, col - 1, score)
                self.moveList.append(foundMove)
            for e in node.neighbors:
                workingScore = score.cheapishCopy()
                if e in self.robotRack and self._crossCheckContains(
                        e, row, col):
                    self.robotRack.remove(e)

                    # calculate score additions
                    letterS = (self._letterMultiplier(
                        self.boardState[row][col].special) *
                               self._wordToScore(e))
                    sidePartScore = self.boardState[row][col].sideScore
                    wordMult = self._wordMultiplier(
                        self.boardState[row][col].special)

                    workingScore.word += letterS
                    # if a side word is made, add value for the whole word
                    if sidePartScore > 0:
                        workingScore.sideParts += sidePartScore + self._wordToScore(
                            e)
                    workingScore.wordMultiplier *= wordMult

                    workingScore.tilesUsed += 1

                    self._extendRight(partialWord + e, node.neighbors[e], row,
                                      col + 1, False,
                                      workingScore.cheapishCopy())
                    self.robotRack.append(e)
        else:
            if self.boardState[row][col].get() in node.neighbors:
                score.word += self._wordToScore(
                    self.boardState[row][col].get())
                self._extendRight(
                    partialWord + self.boardState[row][col].get(),
                    node.neighbors[self.boardState[row][col].get()], row,
                    col + 1, False, score.cheapishCopy())
Exemple #10
0
 def __init__(self, num):
     """
     Constructor
     :param num: player number
     """
     self.player = Player.Player(num)
     if num == 1:
         self.opponent = Player.Player(2)
         self.board = Board.Board(ROWS, COLS, self.player, self.opponent)
         self.move = Move.Move(self.board, self.player, self.opponent)
     else:
         self.opponent = Player.Player(1)
         self.board = Board.Board(ROWS, COLS, self.opponent, self.player)
         self.move = Move.Move(self.board, self.opponent, self.player)
    def getPossibleMoves(self):
        board = self._board
        pos = board.getChessmanPosition(self)
        getCellValue = Tools.secureFunc(board.getCellValue,
                                        error_message="error")

        def isAlienChessmanInCell(x, y):
            value = getCellValue(x, y)
            if value == "error":
                return False
            return value.getColor() != self.getColor() if value else False

        def searchEmptyCellsLine(vector, i):
            result = []
            if not getCellValue(pos["x"] + i * vector["x"],
                                pos["y"] + i * vector["y"]):
                result = [
                    Move(i * vector["x"], i * vector["y"], can_kill=False)
                ]
                result = result + searchEmptyCellsLine(vector, i + 1)
            return result

        moves = []
        if pos:
            for vec in [{
                    "x": 1,
                    "y": 1
            }, {
                    "x": 1,
                    "y": -1
            }, {
                    "x": -1,
                    "y": -1
            }, {
                    "x": -1,
                    "y": 1
            }]:
                barrier_distance = len(searchEmptyCellsLine(vec, 1)) + 1
                if isAlienChessmanInCell(
                        pos["x"] + vec["x"] * barrier_distance,
                        pos["y"] + vec["y"] * barrier_distance):
                    moves = moves + searchEmptyCellsLine(
                        vec, barrier_distance + 1)
            # если есть ходы, которыми можем срубить, тогда нет смысла добавлять обычные ходы, т.к. рубить обязательно
            if len(moves) == 0:
                moves.append(Move(-1, 1, limit=False, can_kill=False))
                moves.append(Move(1, 1, limit=False, can_kill=False))
                moves.append(Move(-1, -1, limit=False, can_kill=False))
                moves.append(Move(1, -1, limit=False, can_kill=False))
        return moves
Exemple #12
0
 def getKingMoves(self, row, col, moves):
     rowMoves = (-1, -1, -1, 0, 0, 1, 1, 1
                 )  #split to put into KingLocation variables
     colMoves = (-1, 0, 1, -1, 1, -1, 0, 1)
     #read those ^^ vertically, to get each of the directions
     allyColor = 'w' if self.whiteToMove else 'b'
     for i in range(8):
         endRow = row + rowMoves[i]
         endCol = col + colMoves[i]
         if 0 <= endRow < 8 and 0 <= endCol < 8:  #on board
             endPiece = self.board[endRow][endCol]
             if endPiece[
                     0] != allyColor:  #when not ally piece, can move there
                 #place king on end square and check for checks
                 if (allyColor == 'w'):
                     self.whiteKingLocation = (endRow, endCol)
                 else:
                     self.blackKingLocation = (endRow, endCol)
                 inCheck, pins, checks = self.checkForPinsAndChecks()
                 if not inCheck:
                     moves.append(
                         Move((row, col), (endRow, endCol), self.board))
                 #place king back on original location
                 if allyColor == 'w':
                     self.whiteKingLocation = (row, col)
                 else:
                     self.blackKingLocation = (row, col)
Exemple #13
0
    def __init__(self, name, moves, level, nature, exp, HP, db):
        # Base stats
        self.db = db

        self.base_HP = db.get_base_stats(name, "HP")
        self.base_attack = db.get_base_stats(name, "attack")
        self.base_defense = db.get_base_stats(name, "defense")
        self.base_sp_attack = db.get_base_stats(name, "sp_attack")
        self.base_sp_defense = db.get_base_stats(name, "sp_defense")
        self.base_speed = db.get_base_stats(name, "speed")

        self.HP = HP
        self.moves = dict(((move, Move(move, db)) for move in moves))
        self.level = level
        self.nature = nature  # nature
        self.exp = exp
        self.IV_EV_4 = math.floor((self.HP - self.level - 10) *
                                  (100 / self.level) - 2 * self.base_HP)

        self.TEST = self.calculate_HP()

        self.attack_stat = self.calculate_other_stat(self.base_attack,
                                                     "Attack")
        self.defense_stat = self.calculate_other_stat(self.base_defense,
                                                      "Defense")
        self.sp_attack_stat = self.calculate_other_stat(
            self.base_sp_attack, "Sp. Attack")
        self.sp_defense_stat = self.calculate_other_stat(
            self.base_sp_defense, "Sp. Defense")
        self.speed_stat = self.calculate_other_stat(self.base_speed, "Speed")

        self.item = None
Exemple #14
0
 def get_moves(self, state: HEX) -> [Move]:
     out = []
     for e in state.get_all_legal_moves():
         copy: HEX = state.__copy__()
         copy.do_move_from_cell(e)
         out.append(Move(state, e, copy, state.player))
     return out
Exemple #15
0
    def __init__(self, index, state=None):

        # Constants
        self.index = index
        self.name = c.PN[index]
        self.level = 5
        self.baseSpeed = c.PBS[index][4]
        self.attack = c.PS[index][1]
        self.defense = c.PS[index][2]
        self.speed = c.PS[index][4]

        # State
        self.cHP = c.PS[index][0]
        self.moves = [Move.Move(c.PM[index][0]), Move.Move(c.PM[index][1])]
        if state is not None:
            self.setState(state)
Exemple #16
0
 def get_moves_white(self):
     for i in range(self.rows):
         for j in range(self.columns):
             if self.matrix[i][j] == 0:
                 # adds down move if legal
                 if i < self.rows - 1 and self.matrix[i + 1][j] == 1:
                     self.moveset.append(Move(i, j, i + 1, j))
                 # adds up move if legal
                 if i > 0 and self.matrix[i - 1][j] == 1:
                     self.moveset.append(Move(i, j, i - 1, j))
                 # adds left move if legal
                 if j > 0 and self.matrix[i][j - 1] == 1:
                     self.moveset.append(Move(i, j, i, j - 1))
                 # adds right move if legal
                 if j < self.columns - 1 and self.matrix[i][j + 1] == 1:
                     self.moveset.append(Move(i, j, i, j + 1))
Exemple #17
0
def listAllMovementMoves(currentState):
    result = []

    # first get all MOVE_ANT moves for each ant in the inventory
    myInv = getCurrPlayerInventory(currentState)
    for ant in myInv.ants:
        # skip ants that have already moved
        if (ant.hasMoved): continue

        # create a Move object for each valid movement path
        allPaths = listAllMovementPaths(currentState, ant.coords,
                                        UNIT_STATS[ant.type][MOVEMENT])

        # remove moves that take the queen out of her territory
        if (ant.type == QUEEN):
            tmpList = []
            for path in allPaths:
                if (isPathOkForQueen(path)):
                    tmpList.append(path)
            allPaths = tmpList

        # construct the list of moves using the paths
        for path in allPaths:
            result.append(Move(MOVE_ANT, path, None))

    return result
Exemple #18
0
def set_valid_moves(board, move_list, cell, neighbors):
    x_src = cell.x
    y_src = cell.y
    for cell_dest in neighbors:
        x_dest = cell_dest.x
        y_dest = cell_dest.y
        move_list.append(Move(x_src, y_src, x_dest, y_dest, None, None, None))
    return move_list  #list of moves
Exemple #19
0
    def get_moves_in_direction(self, piece: Piece, dx: int, dy: int):
        moves = []
        curr_x = piece.x + dx
        curr_y = piece.y + dy
        if dx == 0 and dy == 0:
            return moves

        while 0 <= curr_x < BOARD_SIZE_X_MAX and 0 <= curr_y < BOARD_SIZE_Y_MAX:
            possible_piece = self.get_piece(curr_x, curr_y)
            if possible_piece is not None:
                if possible_piece.owner is not piece.owner:
                    moves.append(Move(curr_x, curr_y))
                break
            else:
                moves.append(Move(curr_x, curr_y))
            curr_x += dx
            curr_y += dy
        return moves
 def searchEmptyCellsLine(vector, i):
     result = []
     if not getCellValue(pos["x"] + i * vector["x"],
                         pos["y"] + i * vector["y"]):
         result = [
             Move(i * vector["x"], i * vector["y"], can_kill=False)
         ]
         result = result + searchEmptyCellsLine(vector, i + 1)
     return result
Exemple #21
0
def approachGate(surge, sway, yaw, timeout):
    ApproachGate = smach.StateMachine(outcomes=['success', 'abort', 'failure'],
                                      output_keys=['angle'])
    ApproachGate.userdata.angle = 0
    ApproachGate.userdata.speed = 0.2
    ApproachGate.userdata.moveTime = 5
    ApproachGate.userdata.timeout = timeout
    ApproachGate.userdata.div = False
    ApproachGate.userdata.latch = False
    with ApproachGate:
        smach.StateMachine.add(
            'Move',
            Move(surge, sway),
            transitions={
                'success': 'Relocate',
            },  #Kyle: changed existence to success or failure
            remapping={
                'angle': 'angle',
                'speed': 'speed',
                'moveTime': 'moveTime'
            })
        smach.StateMachine.add('Relocate',
                               Locate(),
                               transitions={
                                   'success': 'RotateToSection',
                                   'failure': 'Latch'
                               },
                               remapping={
                                   'timeout': 'timeout',
                                   'angle': 'angle',
                                   'div': 'div'
                               })
        smach.StateMachine.add('Latch',
                               Latch(),
                               transitions={
                                   'dedReckon': 'success',
                                   'continue': 'Move',
                                   'search': 'failure'
                               },
                               remapping={
                                   'latchIn': 'latch',
                                   'latchOut': 'latch',
                                   'angle': 'angle',
                                   'div': 'div'
                               })
        smach.StateMachine.add('RotateToSection',
                               RotateTo(yaw, increment=True),
                               transitions={
                                   'success': 'Latch',
                                   'abort': 'abort'
                               },
                               remapping={
                                   'timeout': 'timeout',
                                   'angle': 'angle'
                               })

    return ApproachGate
Exemple #22
0
 def getQueenSideCastleMoves(self, row, col, moves, allyColor):
     if self.board[row][col - 1] == '--' and self.board[row][
             col - 2] == '--' and self.board[row][col - 3] == '--':
         if not self.squareUnderAttack(
                 row, col - 1) and not self.squareUnderAttack(row, col - 2):
             moves.append(
                 Move((row, col), (row, col - 2),
                      self.board,
                      isCastleMove=True))
 def getPossibleMoves(self):
     return [
         Move(1, 2),
         Move(2, 1),
         Move(2, -1),
         Move(1, -2),
         Move(-1, -2),
         Move(-2, -1),
         Move(-2, 1),
         Move(-1, 2)
     ]
 def getPossibleMoves(self):
     return [
         Move(0, 1),
         Move(1, 0),
         Move(0, -1),
         Move(-1, 0),
         Move(1, 1),
         Move(1, -1),
         Move(-1, -1),
         Move(-1, 1)
     ]
Exemple #25
0
    def returnValidMoves(self, color, playingField):
        allValidMoves = []

        #allValidMoves = [[0 for i in range(len(playingField))] for j in range(len(playingField))]
        for i in range(len(playingField)):
            for j in range(len(playingField)):
                tilesToFlip = []
                if playingField[i][j] == 0:

                    nw = self.isValid(color, -1, -1, i, j, playingField)
                    if nw:
                        for count in range(nw + 1):
                            tilesToFlip.append([i - count, j - count])

                    nn = self.isValid(color, -1, 0, i, j, playingField)
                    if nn:
                        for count in range(nn + 1):
                            tilesToFlip.append([i - count, j])

                    ne = self.isValid(color, -1, 1, i, j, playingField)
                    if ne:
                        for count in range(ne + 1):
                            tilesToFlip.append([i - count, j + count])

                    ee = self.isValid(color, 0, 1, i, j, playingField)
                    if ee:
                        for count in range(ee + 1):
                            tilesToFlip.append([i, j + count])

                    se = self.isValid(color, 1, 1, i, j, playingField)
                    if se:
                        for count in range(se + 1):
                            tilesToFlip.append([i + count, j + count])

                    ss = self.isValid(color, 1, 0, i, j, playingField)
                    if ss:
                        for count in range(ss + 1):
                            tilesToFlip.append([i + count, j])

                    sw = self.isValid(color, 1, -1, i, j, playingField)
                    if sw:
                        for count in range(sw + 1):
                            tilesToFlip.append([i + count, j - count])

                    ww = self.isValid(color, 0, -1, i, j, playingField)
                    if ww:
                        for count in range(ww + 1):
                            tilesToFlip.append([i, j - count])

                    points = nw + nn + ne + ee + se + ss + sw + ww

                    if (points > 0):
                        move = Move.Move([i, j], points, color, tilesToFlip)
                        allValidMoves.append(move)

        return allValidMoves
Exemple #26
0
 def getMoves(self, player):
     moves = []
     for i in range(self.hauteur):
         for j in range(self.largeur):
             if (self.board[i][j] == player):
                 for m in self.voisin((i, j), True):
                     if (type(m[0]) == tuple):
                         move = mv.Move((i, j), (m[0][0], m[0][1]), m[1])
                         moves.append(move)
     return moves
Exemple #27
0
 def __init__(self):
     """
     Constructor
     """
     self.player1 = Player.Player(1)
     self.player2 = Player.Player(2)
     self.board = Board.Board(ROWS, COLS, self.player1, self.player2)
     self.move = Move.Move(self.board, self.player1, self.player2)
     self.current_player = self.player1
     self.board.reset_board()
    def addMove(self, type):
        self.moveList.append(Move.Move(type))

        if self.firstMove == None:
            self.firstMove = self.moveList[0]
        else:
            self.moveList[-2].next = self.moveList[-1]
            self.moveList[-1].previous = self.moveList[-2]

        return self.calculatePosibilities()
Exemple #29
0
    def buildAnt(self, ant):
        food = self.handler.currentState.inventories[
            self.handler.currentState.whoseTurn].foodCount

        if food >= UNIT_STATS[ant][4]:
            self.handler.submitHumanMove(Move(BUILD, [self.hillCoords], ant))
        else:
            self.setInstructionText(
                "You need %d food to build that ant, try something else." %
                UNIT_STATS[ant][4])
Exemple #30
0
 def filter_valid_moves(self, piece: Piece, suggest_promote: bool = False):
     moveset = piece.get_current_move_set()
     valid: list[Move] = []
     for move in moveset:
         if self.is_move_in_board_and_not_on_ally(piece, move):
             valid.append(move)
             if suggest_promote and not move.promote and self.is_promote(
                     piece, move):
                 valid.append(Move(move.x, move.y, True))
     return valid