Beispiel #1
0
def execute(server, iterator, source):
    charid = iterator.getString()
    x2 = iterator.getUint8()
    y2 = iterator.getUint8()
    z2 = iterator.getUint8()

    party = server.parties[server.sessions[source]['party']]

    orig = Character.Coords(party, charid)
    x1 = orig[0]
    y1 = orig[1]
    z1 = orig[2]

    path = Move.GetPath(party, charid, x1, y1, z1, x2, y2, z2)
    walkables = Move.GetWalkables(party, charid)

    del party['map']['tiles'][x1][y1][z1]['char']
    party['map']['tiles'][x2][y2][z2]['char'] = charid

    party['chars'][charid]['direction'] = Move.GetNewDirection(x1, y1, x2, y2)
    party['chars'][charid]['canmove'] = False

    server.send.MOVED(charid, x2, y2, z2, source)

    for playerid, playerlogin in enumerate(party['players']):
        if playerid != server.sessions[source]['player']:
            server.send.MOVED_PASSIVE(charid, walkables, path,
                                      server.players[playerlogin])
Beispiel #2
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])
        ]
 def getPossibleMoves(self):
     return [
         Move(0, 1, False),
         Move(1, 0, False),
         Move(0, -1, False),
         Move(-1, 0, False)
     ]
Beispiel #4
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
Beispiel #5
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
Beispiel #6
0
def driveRobot(area):
    if area < (threshold - .20*threshold):
        Move.forward(255, .02)
    elif area > (threshold + .20*threshold):
        Move.backward(255, .02)
    #Move.stop()
    return
Beispiel #7
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)
Beispiel #8
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
def move_list(data):
  move_list=[]
  curr_move=Move()
  curr_frame=Frame()

  last_frameid=None;

  for row in range(0, len(data)):
    if (data[row]):
      #Each row represents a finger in a frame
      curr_finger=Finger(data[row])
      #Handle the first entry
      if (row==0):
        curr_frame.id=curr_finger.frame
        curr_frame.Fingers.append(curr_finger)
        curr_frame.numFingers+=1
      else:
        #A new frame has begun
        if (curr_frame.id!=curr_finger.frame):
          #Check if the old frame was still or stopped (i.e. fingers lifted off)
          #and if so, end the last move and add it to the list of moves.
          if(curr_frame.is_still()) or (curr_frame.is_stopped()):
          #We don't care about collecting still-frame data so just disregard it
          #but end the move accordingly.
             
            #We know the current move has ended so added it to the list of moves
            #but only if there are frames in it, this is to mitigate the fact that
            #WHENEVER there is a still frame a new Move obj is created, but
            #we don't care about these.
            if (curr_move.Framelist):
              curr_move.endAngle=curr_frame.Fingers[0].angle #Only looks at one finger
              curr_move.endXVel=curr_frame.Fingers[0].xvel   #Only looks at one finger
              move_list.append(curr_move)
            curr_move=Move()
          #The last frame was neither still nor stopped, but we need to add it
          #to the current move.
          else:
            if (not curr_move.Framelist):
              curr_move.startAngle=curr_frame.Fingers[0].angle #Not actually accurate e.g. it only looks at one finger
              curr_move.startXVel=curr_frame.Fingers[0].xvel   #Not accurate, see above.
            curr_move.Framelist.append(curr_frame)
            if (curr_frame.numFingers > curr_move.maxFingers):
              curr_move.maxFingers=curr_frame.numFingers
            if (curr_frame.numFingers < curr_move.minFingers):
              curr_move.minFingers=curr_frame.numFingers             
          #Update the current frame
          curr_frame=Frame()
          curr_frame.id=curr_finger.frame
          curr_frame.Fingers.append(curr_finger)
          curr_frame.numFingers+=1
       #A new frame has not begun but there are more fingers to add to it. 
        else:          
          curr_frame.Fingers.append(curr_finger)
          curr_frame.numFingers+=1
  if (curr_move.Framelist):
    curr_move.endAngle=curr_frame.Fingers[0].angle #Only looks at one finger
    curr_move.endXVel=curr_frame.Fingers[0].xvel   #Only looks at one finger
    move_list.append(curr_move)        
  return move_list       
Beispiel #10
0
def check_rules(sender_username, command):
    if length_of_command(command) == 5:
        if correct_coordinates(command):
            start_pos = [int(command[1]), int(command[2])]
            if (find_board_full(sender_username)[1] == sender_username
                and Move.returnCheck(find_board(sender_username), start_pos) == 'x') \
                    or (find_board_full(sender_username)[2] == sender_username
                        and Move.returnCheck(find_board(sender_username), start_pos) == 'o'):
                return True
    return False
Beispiel #11
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
Beispiel #12
0
    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
Beispiel #13
0
def new_generate_agents(num_new_agent, agents):
    """
    new agents generate in Move section
    """
    #num_new_agent = rnd.randrange(num_new_generate)
    new_agents = [Agent_man() for new_agent_id in range(num_new_agent)]
    Move.state_task_for_new_agents(new_agents)
    Decision.initial_strategy(new_agents)
    for id, agent in enumerate(new_agents):
        print(
            f'new_agents No.{id}, state:{agent.state}, next_state:{agent.next_state}, strategy:{agent.strategy}, next_strategy:{agent.next_strategy}, task:{agent.task}'
        )
    agents.extend(new_agents)
Beispiel #14
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())
    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
Beispiel #16
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)
Beispiel #17
0
def updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel = None):
  if pComponent["componenttype"] == Cassette.componentType:
    return Cassette.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel)
  elif pComponent["componenttype"] == Add.componentType:
    return Add.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel)
  elif pComponent["componenttype"] == Evaporate.componentType:
    return Evaporate.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel)
  elif pComponent["componenttype"] == Transfer.componentType:
    return Transfer.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel)
  elif pComponent["componenttype"] == React.componentType:
    return React.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel)
  elif pComponent["componenttype"] == Prompt.componentType:
    return Prompt.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel)
  elif pComponent["componenttype"] == Install.componentType:
    return Install.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel)
  elif pComponent["componenttype"] == Comment.componentType:
    return Comment.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel)
  elif pComponent["componenttype"] == TrapF18.componentType:
    return TrapF18.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel)
  elif pComponent["componenttype"] == EluteF18.componentType:
    return EluteF18.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel)
  elif pComponent["componenttype"] == Initialize.componentType:
    return Initialize.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel)
  elif pComponent["componenttype"] == Mix.componentType:
    return Mix.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel)
  elif pComponent["componenttype"] == Move.componentType:
    return Move.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel)
  elif pComponent["componenttype"] == Summary.componentType:
    return Summary.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel)
  elif pComponent["componenttype"] == ExternalAdd.componentType:
    return ExternalAdd.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel)
  else:
    raise Exception("Unknown component type: " + pComponent["componenttype"])
Beispiel #18
0
def main():
    #Display ascii art
    info.show_art()

    #Display a menu
    display_menu()

    #Prompt the user for input and store it in a variable
    user_option = int(input("Enter your choice: "))

    #Evaluate input
    while user_option is not 3:
        if user_option is 1:
            #Print game board
            grid.printblankgrid()

            #Get and print users move
            print(move.get_move())
        elif user_option is 2:
            #Call the show rules menu from the Text module
            info.show_rules()
        else:
            print("Invalid option, try again!\n")

#Show the menu
        display_menu()

        #Ask for input again
        user_option = int(input("Enter your choice: "))

    #Display good bye
    print("Good bye!")
Beispiel #19
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
Beispiel #20
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)
Beispiel #21
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
Beispiel #22
0
def inputCommand(player, player2, ForS, command):  ##輸入指令
    while True:
        # command = input("請輸入指令\n")##讀取指令
        comList = command.split()  ##字串切割,切割成list
        comList[0] = comList[0].upper()
        if (comList[0] == "MOVE"):
            print("玩家要求移動")
            TorF = Move.move(player, comList[1], comList[2],
                             comList[3])  ##傳入player物件,player的army的ID,以及此軍隊的X和Y
            return TorF
        elif (comList[0] == "ATK"):
            print("玩家要求攻擊")
            TorF = ATK.atk(
                player, player2, comList[1],
                comList[2])  ##需要傳入自己player與對方player物件,並且傳入攻擊以及被攻擊軍隊的ID
            return TorF
        elif (comList[0] == "SET"):
            print("玩家要求設置軍隊")
            ##ForS first or second
            TorF = Set.set(player, ForS, comList[1], comList[2],
                           comList[3])  ##傳入要設定的玩家,極其要設定的該軍隊,即要設定的XY座標
            return TorF
        elif (comList[0] == "LEAVE"):
            print("玩家跳出輸入框")
            break
        else:
            print("指令輸入錯誤")
        # print(comList[0])


# inputCommand()
Beispiel #23
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
Beispiel #24
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))
Beispiel #25
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)
Beispiel #26
0
    def checkIfLegal(self, move: Move):
        if move.is_passing():
            return True  # assumes pass is only considered if no other moves were allowed

        x, y = move.figur
        if not (x, y) in self.posWhite:
            return False  #not a white pawn

        # gerade ziehen
        if move.richtung == 0:
            return (x, y + 1) not in (
                self.posWhite + self.posBlack
            )  #if y+1 was oob then the game would already have ended
        # "+1" schlagen (nach rechts schlagen)
        elif move.richtung == +1:
            if x + 1 >= self.size[0]:  # oob, again y+1 can be assumed in bounds
                return False

            if (x + 1, y + 1) in self.posWhite:  # can't take white
                return False

            return (x + 1, y + 1) in self.posBlack  # need take black
        # "-1" schlagen (nach links schlagen)
        elif move.richtung == -1:
            if x - 1 < 0:  #oob
                return False

            if (x - 1, y + 1) in self.posWhite:
                return False

            return (x - 1, y + 1) in self.posBlack
        else:
            return False  # illegal direction?
Beispiel #27
0
def startTwoPlayerGame(color):
    board = Board.Board(color)
    dice = Dice.Dice()

    board.printBoard()

    print 'Determining Starter...'
    starter = dice.determineStarter()

    if starter == 1:
        turn = Turn.Turn(color, color)
    else:
        if color == 'b':
            turn = Turn.Turn('w', color)
        else:
            turn = Turn.Turn('b', color)

    while True:
        print turn.getTurnPrint() + "'s turn."
        print turn.getTurnPrint() + "'s roll:"

        turn.setRolls(dice.roll())
        print turn.printRoll()

        # Get and validate move from the player
        move = Move.getPlayerMove(turn, board)

        # Make the move
        if move == 'undo':
            board.undoMove(turn)
            turn.undoMove()
        else:
            pass

        break
Beispiel #28
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
Beispiel #29
0
	def min_value_alphabeta(self, tablero, level):
		mejor_move=Move(-1,-1,1000)
		old_move=Move(-1,-1)
		old_move_anterior_buffer=Move(-1,-1)
		tablero_copy=tablero.get_copia()
		old_move_anterior_buffer=Move(-1,-1)
		if(not tablero.fin_del_juego()and level<=Minimax.MAX_LEVEL):
			for i in range(Tablero.MAX_DIM):
				for j in range(Tablero.MAX_DIM):
					old_move_buffer=Move(i,j)
					if tablero_copy.es_duenho(old_move_buffer):
						move_validos=tablero_copy.get_lista_move_validos(old_move_buffer,old_move_anterior_buffer)
						for move_valido in move_validos:
							#si es que puede come todas las fichas posibles
							lista=tablero_copy.comer_fichas(old_move_buffer,2,Ficha.USUARIO)
							#self.nodos=self.nodos+1
							if(len(lista)-1==0):
								#prueb una posicion
								tablero_copy.mover_ficha(old_move_buffer, move_valido)
							#expande al otro nodo
							old,move_result=self.max_value_alphabeta(tablero_copy, level+1)
							#Obtiene el puntaje obtenido 
							#move_valido.score=tablero_copy.evaluar_suma_peso() #+ move_result.score
							move_valido.score=move_result
							'''
							Selecciona mayor valor del move para la computadora
							Significa que en el peor de los casos el valor sera el del mejor_move.score
							Atender el signo, todavia me confunde
							'''
							if move_valido.score <= mejor_move.score:
								mejor_move=move_valido
								#mejor_move.score=move_result.score
								old_move=old_move_buffer
							
							if mejor_move.score < self.BETA:
								self.BETA = mejor_move.score
							
							if self.BETA <= self.ALPHA: return old_move,mejor_move
							
							#pone la ficha en su posicion inicial
							tablero_copy=tablero.get_copia()
						old_move_anterior_buffer=Move(i,j)
		else:
			#mejor_move.score=tablero.evaluar_suma_peso()
			mejor_move.score=tablero.evaluar()
		return old_move,mejor_move
Beispiel #30
0
def send_move(sender_username, client, command):
    is_bad = False
    message = ''
    if check_rules(sender_username, command):  # Bardzo dlugi if
        start_pos = [int(command[1]), int(command[2])]
        target_pos = [int(command[3]), int(command[4])]
        msg = Move.move(find_board(sender_username), start_pos, target_pos)
        message = Board.printBoard(find_board(sender_username))
        if WinCondition.isGameEnded(find_board(sender_username)):
            if WinCondition.checkWhoWin(find_board(sender_username)):
                #find_user(find_board_full(sender_username)[2]).sendall('wygrales o')
                send_to_client(find_user(find_board_full(sender_username)[2])[1],'wygrales', "\r\n\r\n")
                send_to_client(find_user(find_board_full(sender_username)[1])[1], 'przegrales', "\r\n\r\n")
                find_user(find_board_full(sender_username)[1])[2] = False
                find_user(find_board_full(sender_username)[2])[2] = False
                send_old_menu(find_board_full(sender_username)[1], find_user(find_board_full(sender_username)[1]))
                send_old_menu(find_board_full(sender_username)[2], find_user(find_board_full(sender_username)[2]))
                list_of_boards.remove(find_board_full(sender_username))
            else:
                #find_user(find_board_full(sender_username)[1]).sendall('wygrales x')
                send_to_client(find_user(find_board_full(sender_username)[1])[1],'wygrales', "\r\n\r\n")
                send_to_client(find_user(find_board_full(sender_username)[2])[1], 'przegrales', "\r\n\r\n")
                find_user(find_board_full(sender_username)[1])[2] = False
                find_user(find_board_full(sender_username)[2])[2] = False
                send_old_menu(find_board_full(sender_username)[1], find_user(find_board_full(sender_username)[1]))
                send_old_menu(find_board_full(sender_username)[2], find_user(find_board_full(sender_username)[2]))
                list_of_boards.remove(find_board_full(sender_username))
    else:
        is_bad = True

    receiver = find_user(sender_username)[3]

    receiver_is_logged_in = False
    for user_tuple in logged_in_users:
        if user_tuple[0] == receiver or user_tuple[0] == sender_username:
            #user_tuple[1].sendall(message)
            send_to_client(user_tuple[1], str(message), "\r\n\r\n")
            #send_to_client(user_tuple[1], str(msg), "\r\n\r\n")
            receiver_is_logged_in = True

    if not receiver_is_logged_in:
        #client.sendall(receiver + ' gracz skonczyl gre. ')
        send_to_client(client, str(receiver) + ' gracz skonczyl gre. ', "\r\n\r\n")

    if not is_bad and msg == 'Ruch wykonany!':
        find_user(sender_username)[4] = False
        find_user(find_user(sender_username)[3])[4] = True
        send_new_menu(sender_username, client)
        send_wait_communicate(find_user(sender_username)[3], find_user(find_user(sender_username)[3])[1])
    else:
        for user in logged_in_users:
            if user[0] == sender_username:
                #user[1].sendall(Board.printBoard(find_board(sender_username)))
                send_to_client(user[1], str(Board.printBoard(find_board(sender_username))), "\r\n\r\n")
                #user[1].sendall('Podano zle dane\n')
                send_to_client(user[1], 'Niepoprawny ruch!!! Sprobuj jeszcze raz.', "\r\n\r\n")
        send_new_menu(find_user(sender_username)[3], client)
    return is_bad
Beispiel #31
0
def moveturn(currentboard, turncount):
    #START OF TURN
    """This displays the board in a better format"""
    Board.display(currentboard)
    turncount, playerturn, playernumber = Move.checkturn(
        nameofplayers, turncount)
    print("Turn: " + str(turncount))
    print("It is " + str(playerturn) + "'s turn now!")
    """This prompts guy to select the tile to remove"""
    tiletoremove = Move.picktile()  #tile position
    """This checks if the tile that the guy selects is a valid move and returns true or false"""
    verticalvalue, horizontalvalue, validtile, playtile = Move.checktile(
        tiletoremove, playernumber, currentboard)  #True/False
    """tile is removed, value changed to '-'"""
    currentboard = Move.removetile(validtile, verticalvalue, horizontalvalue,
                                   currentboard)
    """Displays board after tile is removed."""
    Board.display(currentboard)
    """Check direction chosen by player to see if valid or not. """
    insertdirection = Move.checkdirection(verticalvalue, horizontalvalue,
                                          currentboard)
    """if placecheck is true, start placing tiles onto the board"""
    currentboard = Move.placetile(verticalvalue, horizontalvalue, currentboard,
                                  insertdirection, playernumber, playtile)
    """Display the new board"""
    Board.display(currentboard)
    """Check for win condition"""
    win = Move.checkwin(currentboard)
    #END OF TURN
    return win, currentboard, turncount
 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
Beispiel #33
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
Beispiel #34
0
	def max_value(self, tablero, level):
		range_list=[7,6,5,4,3,2,1,0]
		mejor_move=Move(-1,-1,-1000)
		old_move=Move(-1,-1)
		old_move_anterior_buffer=Move(-1,-1)
		tablero_copy=tablero.get_copia()
		if(not tablero.fin_del_juego() and level<=Minimax.MAX_LEVEL):
			for i in range_list:
				for j in range_list:
					old_move_buffer=Move(i,j)
					#Genera los movimientos validos para la computadora
					if (tablero_copy.es_duenho(old_move_buffer, Ficha.COMPUTADORA)):
						move_validos=tablero_copy.get_lista_move_validos(old_move_buffer,old_move_anterior_buffer,-1,Ficha.COMPUTADORA)
						for move_valido in move_validos:
							#self.nodos=self.nodos+1
							#si es que puede come todas las fichas posibles
							lista=tablero_copy.comer_fichas(old_move_buffer)
							if(len(lista)-1==0):
								#prueba una posicion
								tablero_copy.mover_ficha(old_move_buffer, move_valido)
							#expande el siguiente nodo
							old, move_result=self.min_value(tablero_copy, level+1)
							#evalua el movimiento actual
							#move_valido.score=tablero_copy.evaluar_suma_peso(-1) +move_result.score
							#se le suma el puntaje obtenido al realizar dicho movimiento
							move_valido.score=move_result.score
							'''
							Selecciona el move de menor riesgo para la computadora
							Atender el signo, todavia me confunde
							'''
							if move_valido.score >= mejor_move.score:
								mejor_move=move_valido
								old_move=old_move_buffer
							#pone el tablero en su posicion inicial
							tablero_copy=tablero.get_copia()
					old_move_anterior_buffer=Move(i,j)
		else:
			#mejor_move.score=tablero.evaluar_suma_peso(-1)
			mejor_move.score=tablero.evaluar(-1)
			
		return old_move,mejor_move
Beispiel #35
0
    def es_valido_move_dama2(self, old_move, new_move, inc=1, duenho=Ficha.USUARIO):
        delta_i = new_move.i - old_move.i
        delta_j = new_move.j - old_move.j
        i, j = old_move.i, old_move.j
        if not (abs(delta_i) == abs(delta_j)) or delta_i == 0 or delta_j == 0:
            return False

        signo_j = delta_j / abs(delta_j)
        signo_i = delta_i / abs(delta_i)
        move_buffer = Move(i, j)
        for di in range(1, abs(delta_i) + 1):
            # se obtiene el siguiente movimiento
            actual_move = Move(i + di * signo_i, j + di * signo_j)
            # se verifica que este no este fuera del rango 0-8 y que no este ocupado por alguna ficha
            if (
                not self.sobrepasa_limites(actual_move)
                and not (self.es_vacio(actual_move.i, actual_move.j))
                and self.es_duenho(actual_move, duenho)
            ):
                return False
                # se verifica que no se sobrepase el rango 0-8 y que no este vacio para verificar si se puede comer alguna ficha
            elif (
                not self.sobrepasa_limites(actual_move)
                and not self.es_duenho(actual_move, duenho)
                and not (self.es_vacio(actual_move.i, actual_move.j))
            ):
                di = di + 1
                # Se obtiene el siguiente movimiento y se verifica
                actual_move = Move(i + (di) * signo_i, j + (di) * signo_j)
                if self.sobrepasa_limites(actual_move) or not (actual_move.igual(new_move)):
                    return False
                    # Se mueve la ficha a la posicion anterior a la casilla ocupada
                comer_move = self.comer_ficha(old_move, actual_move, signo_i, duenho)
                if comer_move == None:
                    return False
                return True

            move_buffer = actual_move
        return True
Beispiel #36
0
    def allMovesHelp(self, piece):
        '''Gets all moves that the given piece can make as a list of Move objects'''
        dims = self.getDims(piece)
        moves = []

        for direction in [Move.UP, Move.DOWN, Move.LEFT, Move.RIGHT]:
            newDims = Move.getNewDimensions(dims, direction)
            free = True
            for r in xrange(dims[2]):
                for c in xrange(dims[3]):
                    if not self.canMove(piece, newDims[0]+r, newDims[1]+c):
                        free = False
                        break
            if free:
                moves.append(Move.Move(piece, dims, direction))

        return moves
Beispiel #37
0
    def goodAggPlay(self,game):
        move = Move(CHECK)
        curAmt = game.lastBet
        potAmt = game.pot + game.rightOpp.pip + game.leftOpp.pip + game.me.pip

        canBet = False
        canRaise = False
        for la in game.legalActions:
            if la[0] == "BET":
                canBet = True
            if la[0] == "RAISE":
                canRaise = True

        if game.street == PREFLOP:
            move = Move(CALL)
            if random.randint(1,100) <= 50 and canRaise:
                move = Move(RAISE, random.randint(1,5)*potAmt)
        elif game.street == FLOP:
            move = Move(CALL)
            if canRaise:
                if random.randint(1,100) <= 50:
                    move = Move(RAISE, random.randint(20,25)/10.0*game.lastBet)
            elif canBet:
                move = Move(CHECK)
                if random.randint(1,100) <= 50:
                    move = Move(BET, random.randint(66,75)/100.0*potAmt)
        elif game.street == TURN:
            move = Move(CALL)
            if canRaise:
                if random.randint(1,100) <= 45:
                    move = Move(RAISE, random.randint(20,25)/10.0*game.lastBet)
            elif canBet:
                move = Move(CHECK)
                if random.randint(1,100) <= 75:
                    move = Move(BET, random.randint(66,75)/100.0*potAmt)
        elif game.street == RIVER:
            move = Move(CALL)
            if canRaise:
                amt = round(min([2.5*game.lastBet, game.me.getAllIn()]))
                move = Move(RAISE, random.randint(amt, round(game.me.getAllIn())))
            elif canBet:
                move = Move(BET, random.randint(50,150)/100.0*potAmt)
        move.amount = min([move.amount, game.me.getAllIn()])
        return move
Beispiel #38
0
    def okAggPlay(self,game):
        move = Move(CHECK)
        curAmt = game.lastBet
        potAmt = game.pot + game.rightOpp.pip + game.leftOpp.pip + game.me.pip
        street = game.street

        canBet = False
        canRaise = False
        for la in game.legalActions:
            if la[0] == "BET":
                canBet = True
            if la[0] == "RAISE":
                canRaise = True

        if game.street == PREFLOP:
            if curAmt>50:
                return move
            move = Move(CALL)
            if random.randint(1,100) <= 10 and canRaise:
                move = Move(RAISE, random.randint(1,3)*potAmt)
        elif game.street == FLOP:
            if canRaise:
                move = Move(CALL)
                if random.randint(1,100) <= 75:
                    move = Move(RAISE, random.randint(20,25)/10.0*game.lastBet)
            elif canBet:
                move = Move(CHECK)
                if random.randint(1,100) <= 35:
                    move = Move(BET, random.randint(33,66)/100.0*potAmt)
        elif game.street == TURN:
            if canRaise:
                move = Move(CHECK)
                if random.randint(1,100) <= 45:
                    move = Move(RAISE, random.randint(20,25)/10.0*game.lastBet)
            elif canBet:
                move = Move(CHECK)
                if random.randint(1,100) <= 25:
                    move = Move(BET, random.randint(33,66)/100.0*potAmt)
        elif game.street == RIVER:
            if canRaise:
                move = Move(CHECK)
                if random.randint(1,100) <= 15:
                    move = Move(RAISE, random.randint(20,25)/10.0*game.lastBet)
            elif canBet:
                move = Move(CHECK)
                if random.randint(1,100) <= 15:
                    move = Move(BET, random.randint(33,66)/100.0*potAmt)
        else:
            print "Error! You reached a state not 0-3! in blindEVplay"

        if move.type == CHECK and curAmt < .33 * potAmt and canRaise:
            move = Move(CALL)
            if random.randint(1,100) <= 50:
                move = Move(RAISE, random.randint(20,25)/10.0*game.lastBet)
        move.amount = min([move.amount, game.me.getAllIn()])
        return move
Beispiel #39
0
    def getMove(self, game):
        OppEvs = self.getOppEvs(game)
        ev = self.evalHand(game, OppEvs)
        scores = {}
        nump = game.activePlayers

        if ev>blindEVs[nump-2][game.street][2]:
            myBlindEV = GOOD
        elif ev>blindEVs[nump-2][game.street][1]:
            myBlindEV = OK
        elif ev>blindEVs[nump-2][game.street][0]:
            myBlindEV = BAD
        else:
            myBlindEV = AWFUL

        for pname,p in OppEvs.items():
            if p[0] == -1:
                scores[pname] = UNKNOWN
            elif ev>p[0]+p[1]:
                scores[pname] = GOOD
            elif ev>p[0]:
                scores[pname] = OK
            elif ev>p[0]-p[1]:
                scores[pname] = BAD
            else:
                scores[pname] = AWFUL

        maxLeftEV = max([myBlindEV,scores[game.leftOpp.name]])
        if OppEvs[game.leftOpp.name][1]<100:
            maxLeftEV = scores[game.leftOpp.name]
        maxRightEV = max([myBlindEV,scores[game.rightOpp.name]])
        if OppEvs[game.rightOpp.name][1]<100:
            maxLeftEV = scores[game.rightOpp.name]

        print "EV:", ev, "myBlindEV:",myBlindEV, "LEFT EV:", OppEvs[game.leftOpp.name],"-",scores[game.leftOpp.name],"=",scores[game.leftOpp.name], "RIGHT EV:", OppEvs[game.rightOpp.name],"=",scores[game.rightOpp.name], "activePlayers:", game.activePlayers
        if nump == 3:
            score = min([maxLeftEV, maxRightEV])
        else:
            score = maxRightEV
            if not game.rightOpp.active:
                score = maxLeftEV


        tagPlaying = ((not game.leftOpp.isLAP(game) and game.leftOpp.active)
                      or (not game.rightOpp.isLAP(game) and game.rightOpp.active))
        comment = ""
        if score == AWFUL:
            move = Move(CHECK)
        else:
            move = self.decide(game, not tagPlaying, score)
            comment += move.comment
        comment += " score: " + str(score)

        if move.amount is not None:
            move.amount = min([move.amount, game.me.getAllIn()])

        if ACTION_TYPES[move.type] not in [la[0] for la in game.legalActions]:
            print "returned illegal action",move.toString()[:-1],"! in",game.legalActions
            if move.type in [BET,RAISE]:
                move = Move(CALL)
            else:
                move = Move(CHECK)

        move.rightEV = OppEvs[game.rightOpp.name]
        move.leftEV = OppEvs[game.leftOpp.name]
        move.myEV = ev
        move.comment = comment
        return move
Beispiel #40
0
    def decide(self, game, isLAP, score):
        firstToAct = False
        facingBet = False
        facingRaise = False
        canBet = False
        canRaise = False
        comment = "isLap=" + str(isLAP) + ", "

        for la in game.legalActions:
            if la[0] == "BET":
                canBet = True
            if la[0] == "RAISE":
                canRaise = True

        lastAction = game.lastActor.lastActions[-1]
        if game.street == PREFLOP:
            firstToAct = lastAction.type == POST
        else:
            firstToAct = game.me.pip + game.leftOpp.pip + game.rightOpp.pip == 0

        if not firstToAct:
            facingBet = lastAction.type == BET
        facingRaise = not firstToAct and not facingBet

        if firstToAct: comment += "first to act "
        if facingBet: comment += "facing a bet of " + str(game.lastBet) + " "
        if facingRaise: comment += "facing a raise to " + str(game.lastBet) + " "

        prob = random.randint(1,100)
        totalPot = game.pot + game.me.pip + game.leftOpp.pip + game.rightOpp.pip
        if game.street == PREFLOP:
            if firstToAct:
                check = firstToActCutoffs[isLAP][PREFLOP][score-1]
                if prob <= check:
                    move = Move(CALL)
                else:
                    move = Move(RAISE, 6)
            else:
                bin = self.getRaiseBin(game.street, game.lastActor.lastActions[-1])
                if bin == BIN1:
                    if isLAP:
                        raiseAmt = int(3.5*totalPot)
                    else:
                        raiseAmt = int(2.75* totalPot)
                elif bin == BIN2:
                    if isLAP:
                        raiseAmt = int(2.5*totalPot)
                    else:
                        raiseAmt = int(3*totalPot)
                elif bin == BIN3:
                    raiseAmt = int(2.5*totalPot)
                else:
                    raiseAmt = game.me.getAllIn()

                comment += " bin="+str(bin) + " raiseamnt=" + str(raiseAmt)
                r,c = raiseCutoffs[isLAP][game.street][bin][score-1]
                if prob <= r:
                    move = Move(RAISE, raiseAmt)
                elif prob <= c:
                    move = Move(CALL)
                else:
                    move = Move(FOLD)
        else:
            if isLAP:
                betAmt = .8*totalPot
                raiseAmt = max([3*game.lastBet, int(.75*totalPot)])
            else:
                betAmt = .5*totalPot
                raiseAmt = 3*game.lastBet

            if firstToAct:
                check = firstToActCutoffs[isLAP][game.street][score-1]
                if prob <= check:
                    move = Move(CHECK)
                else:
                    move = Move(BET, betAmt)
            elif facingBet:
                bin = self.getBetBin(game.lastActor.lastActions[-1].potAmount)
                comment += " bin="+str(bin) + " betamnt=" + str(betAmt)
                r,c = betCutoffs[isLAP][game.street][bin][score-1]
                if prob <= r:
                    move = Move(RAISE, raiseAmt)
                elif prob <= c:
                    move = Move(CALL)
                else:
                    move = Move(FOLD)
            else:
                bin = self.getRaiseBin(game.street, game.lastActor.lastActions[-1])
                comment += " bin="+str(bin) + " raiseamnt=" + str(raiseAmt)
                r,c = raiseCutoffs[isLAP][game.street][bin][score-1]
                if prob <= r:
                    move = Move(RAISE, raiseAmt)
                elif prob <= c:
                    move = Move(CALL)
                else:
                    move = Move(FOLD)
        move.comment = comment
        return move
Beispiel #41
0
    def badAggPlay(self, game):
        curAmt = game.lastBet
        potAmt = game.pot + game.rightOpp.pip + game.leftOpp.pip + game.me.pip
        street = game.street

        move = Move(CHECK)

        canBet = False
        canRaise = False
        for la in game.legalActions:
            if la[0] == "BET":
                canBet = True
            if la[0] == "RAISE":
                canRaise = True

        if canRaise and curAmt > 2*potAmt: #don't call super aggressive bets
            #with bad ev
            return move
        if canRaise: #don't re-raise with bad ev
            if game.rightOpp.active and self.matchLastAction(game, game.rightOpp,[RAISE]):
                return move
            elif game.leftOpp.active and self.matchLastAction(game, game.leftOpp,[RAISE]):
                return move

        if street == PREFLOP:
            move = Move(CHECK)
            #Raise 10% of the time
            if random.randint(1,100) <= 10 and canRaise:
                move = Move(RAISE, random.randint(1,2)*potAmt)
        elif street == FLOP:
            if canRaise:
                move = Move(CHECK)
                if random.randint(1,100) <= 60:
                    move = Move(RAISE, random.randint(20,25)/10.0*game.lastBet)
            elif canBet:
                move = Move(CHECK)
                if random.randint(1,100) <= 35:
                    move = Move(BET, random.randint(33,50)/100.0*potAmt)
        elif street == TURN:
            if canRaise:
                move = Move(CHECK)
                if random.randint(1,100) <= 15:
                    move = Move(RAISE, random.randint(20,25)/10.0*game.lastBet)
            elif canBet:
                move = Move(CHECK)
                if random.randint(1,100) <= 7:
                    move = Move(BET, random.randint(33,50)/100.0*potAmt)

        if move.type == CHECK and curAmt < .33 * potAmt and canRaise:
            move = Move(CALL)
            if random.randint(1,100) <= 50:
                move = Move(RAISE, random.randint(20,25)/10.0*game.lastBet)
        move.amount = min([move.amount, game.me.getAllIn()])
        return move