Exemple #1
0
 def check_for_valid_movement(self):
     invalid = []
     valid = []
     for m in self.all_moves:
         c1 = m.cof.cm.have_cm  # has a counter movement
         c2 = m.target_reach  # target reach
         if c1 and c2:
             valid.append(m)
         else:
             print('INVALID --- ', 'c1:', c1, 'c2 ', c2)
             invalid.append(m)
     self.valid_moves = Moves(valid)
     self.invalid_moves = Moves(invalid)
Exemple #2
0
 def clicked(self, block, event):
     if event.button() == Qt.MouseButton.LeftButton:
             if block.getPosition() not in self.maxMoves:
                 if self.BLACK_TURN:
                     if "black" not in block.getKey():
                         self.showPopUp("It's black turn.")
                         return
                 else:
                     if "white" not in block.getKey():
                         self.showPopUp("It's white turn.")
                         return
                 self.maxMoves = []
                 if not block.haveActivated():
                     for value in self.blocks.values():
                         value.setActivated(False)
                     if block.haveOccupied():
                         block.setActivated(True)
                         self.readyToMove = block
                     self.maxMoves = Moves(block, self.blocks).canRoamTo()
                     if self.maxMoves is None:
                         self.maxMoves = []
                     self.removeMovable()
                     self.printMovable(self.maxMoves)
                 else:
                     block.setActivated(False)
             else:
                 self.maxMoves = []
                 self.setValues(block, block.getPosition(), self.readyToMove.getKey())
                 self.setValues(self.readyToMove, self.readyToMove.getPosition(), None)
                 self.readyToMove = None
                 self.removeMovable()
                 self.BLACK_TURN = not self.BLACK_TURN
Exemple #3
0
 def play_round(self, players):
     # moves: Nx(N-1) array
     # where moves[i, j] is action of player i for player j
     moves = Moves([p.play() for p in players])
     for i, player in enumerate(players):
         player.update_state(moves.opponent_moves(i))
     scores = self.score_moves(moves)
     return scores
Exemple #4
0
 def randomize(self, steps=15):
     backward = None
     while steps > 0:
         moves = self.get_allowed_moves()
         if backward is not None:
             moves.remove(Moves(backward.value * -1))
         self._move(random.choice(moves))
         steps = steps - 1
    def initGUI(self):
        self.whiteTurn = True
        self.maxDepth = 3
        self.moves = Moves()
        self.board = Board()
        self.principalVariation = PrincipalVariation(self.moves,
                                                     self.playerIsWhite,
                                                     self.maxDepth)
        self.board.initChess(self.moves, self.playerIsWhite, gui=True)
        self.x_axisMap = {
            0: "A",
            1: "B",
            2: "C",
            3: "D",
            4: "E",
            5: "F",
            6: "G",
            7: "H"
        }
        self.highlightedPosition = []

        #restore GUI data field to its initial state
        self.selectedPiece = None
        self.allLegalMoves = None
        self.canvas = None
        self.chessBoard = None
        #uncomment this
        # self.player_vs_player=False
        # self.player_vs_AI=False

        self.master.title("ChessAI")
        ##Initalise pieces' images
        #initialise white pieces' images
        self.pieceImage["whiteKing"] = ImageTk.PhotoImage(
            file="pieceImage/whiteKing.png", width=32, height=32)
        self.pieceImage["whiteQueen"] = ImageTk.PhotoImage(
            file="pieceImage/whiteQueen.png", width=32, height=32)
        self.pieceImage["whiteBishop"] = ImageTk.PhotoImage(
            file="pieceImage/whiteBishop.png", width=32, height=32)
        self.pieceImage["whiteKnight"] = ImageTk.PhotoImage(
            file="pieceImage/whiteKnight.png", width=32, height=32)
        self.pieceImage["whiteRook"] = ImageTk.PhotoImage(
            file="pieceImage/whiteRook.png", width=32, height=32)
        self.pieceImage["whitePawn"] = ImageTk.PhotoImage(
            file="pieceImage/whitePawn.png", width=32, height=32)
        #initialise black pieces' images
        self.pieceImage["blackKing"] = ImageTk.PhotoImage(
            file="pieceImage/blackKing.png", width=32, height=32)
        self.pieceImage["blackQueen"] = ImageTk.PhotoImage(
            file="pieceImage/blackQueen.png", width=32, height=32)
        self.pieceImage["blackBishop"] = ImageTk.PhotoImage(
            file="pieceImage/blackBishop.png", width=32, height=32)
        self.pieceImage["blackKnight"] = ImageTk.PhotoImage(
            file="pieceImage/blackKnight.png", width=32, height=32)
        self.pieceImage["blackRook"] = ImageTk.PhotoImage(
            file="pieceImage/blackRook.png", width=32, height=32)
        self.pieceImage["blackPawn"] = ImageTk.PhotoImage(
            file="pieceImage/blackPawn.png", width=32, height=32)
Exemple #6
0
    def __init__(self, repetition):
        from moves import Moves

        self.repetition = repetition
        Move.move_num = 0

        self.current_move = None
        self.moves = Moves([])
        self.index = None
 def init(self,n_iter,n_components):
     self.n_iter = n_iter
     self.n_components = n_components
     self.drawObj = Draw()
     self.moveObj = Moves()
     self.moveObj.init(n_components)
     self.jp =None
     self.jp_old =None
     self.parameters = self.drawObj.sample_params(n_components)
Exemple #8
0
 def test_showavailmoves(self):
     move = Moves()
     self.assertEqual(move.showAvailMoves(), {'topRow':['l','m','r'],
                                              'midRow':['l','m','r'],
                                              'botRow':['l','m','r']})
     move.acceptMove({'mid': 'm', 'player': 2})
     self.assertEqual(move.showAvailMoves()['midRow'], ['l','r'])
     move.acceptMove({'mid': 'l', 'player': 1})
     move.acceptMove({'mid': 'r', 'player': 2})
     self.assertEqual(move.showAvailMoves()['midRow'], [])
Exemple #9
0
    def play_two_groups(self, graphs1, graphs2, n_rounds=20):
        players1 = [Player(graph, len(graphs2)) for graph in graphs1]
        players2 = [Player(graph, len(graphs1)) for graph in graphs2]
        total_scores = None
        for r in range(n_rounds):
            moves1 = Moves([p.play() for p in players1])
            moves2 = Moves([p.play() for p in players2])
            for i, player in enumerate(players1):
                player.update_state(
                    moves2.opponent_moves(i, exclude_self=False))
            for i, player in enumerate(players2):
                player.update_state(
                    moves1.opponent_moves(i, exclude_self=False))

            scores = self.score_moves(moves1, moves2)
            if total_scores is None:
                total_scores = scores
            else:
                total_scores += scores
        return total_scores
Exemple #10
0
def collect():
    key_file = open('keys.json')
    key_data = json.load(key_file)

    m = Moves(client_id=key_data["client_id"],
              client_secret=key_data["client_secret"],
              redirect_url=key_data["redirect_url"])

    for (i, user) in enumerate(get_moves_db().find()):
        if i != 0 and i % 10 == 0:
            logging.info("Finished 10 users, sleeping for two minutes...")
            sleep(2 * 60)
        access_token = user['access_token']
        if access_token == "Ignore_me":
            logging.info("Found entry to ignore for user %s" % user)
            continue
        logging.info("%s: Getting data for user %s with token %s" %
                     (datetime.now(), user['our_uuid'], user['access_token']))
        user_uuid = user['our_uuid']
        # logging.debug(user_uuid)
        profile = m.get_profile(token=access_token)
        # logging.debug(profile)
        tzStr = getTimezone(profile)
        tz = pytz.timezone(tzStr)

        # So the documentation both here:
        # http://www.enricozini.org/2009/debian/using-python-datetime/
        # and here:
        # http://pytz.sourceforge.net/
        # says that we should use utcnow() because now() is not reliable.
        # unfortunately, using utcnow() on my desktop, where the timezone is set, causes the localized time to be wrong
        # now() works
        # testing with now() on the server as well
        # now() didn't work on the server either
        # in fact, pytz localize() (i.e. tz.localize(datetime.now()) seems broken
        # fortunately, astimezone() seems to work, so we are using it here

        dateFormat = "%Y-%m-%d"
        # endPoint = "user/storyline/daily/%s?trackPoints=true" % ('20140303')
        endPoint_today = "user/storyline/daily/%s?trackPoints=true" % (
            datetime.now(pytz.utc).astimezone(tz).strftime(dateFormat))
        endPoint_yesterday = "user/storyline/daily/%s?trackPoints=true" % (
            (datetime.now(pytz.utc).astimezone(tz) -
             timedelta(1)).strftime(dateFormat))
        result_today = m.get(token=access_token, endpoint=endPoint_today)
        result_yesterday = m.get(token=access_token,
                                 endpoint=endPoint_yesterday)
        logging.debug("result_today.type = %s, result_yesterday = %s" %
                      (type(result_today), type(result_yesterday)))
        # logging.debug(json.dumps(result_yesterday))

        # result=result_today+result_yesterday
        processResult(user_uuid, result_today)
        processResult(user_uuid, result_yesterday)
Exemple #11
0
 def test_acceptmove(self):
     move = Moves()
     move.acceptMove({'top': 'l', 'player': 1})
     self.assertEqual(move.state['top'], {'l': 1, 'm':0, 'r':0})
     self.assertRaises(InputError, move.acceptMove, {'top': 'l', 'player': 2})
     move.acceptMove({'mid': 'm', 'player': 2})
     self.assertEqual(move.state['mid'], {'l': 0, 'm':2, 'r':0})
     move.acceptMove({'bot': 'r', 'player': 2})
     self.assertEqual(move.state['bot'], {'l': 0, 'm':0, 'r':2})
     move.acceptMove({'bot': 'm', 'player': 1})
     self.assertEqual(move.state['bot'], {'l': 0, 'm':1, 'r':2})
Exemple #12
0
    def __init__(self,
                 _players,
                 describe_att_name=None,
                 dtype_att=[
                     "COF", "COM", "C7", "angle_lower", "angle_trunk", "phase"
                 ]):
        """Allows to calculate the mean of a move_id or mean_arr of a group of player

        :parameter _players: an Instance of Players
        :parameter move_id: the id of the move to look at
        :parameter dtype_att: the data instance from maindata to look att
        :parameter mean_att: all the instance of MeanMove to consider if move_id is None

        :type _players: Players
        :type move_id: int
        :type dtype_att: list
        :type mean_att: list
        """
        self._players = deepcopy(_players)
        self._players.equalise_length(mode='min')
        # TODO is taking the id 0 robust? need change?
        self.num_move_per_player = len(_players[0].__dict__[describe_att_name])
        self.dtype_att = dtype_att
        self.describe_att_name = describe_att_name

        self.lst_moves = deepcopy(
            list(range(0, len(_players[0].__dict__[self.describe_att_name]))))
        # self.lst_moves = self.get_lst_move()
        # print("players list moves", self.lst_moves)
        self._mean = None  # mean de tous les moves pour tous les joueurs pour le move_id
        self._std = None  # mean de tous les moves pour tous les joueurs pour le move_id
        self.moves_mean = Moves([])
        self.moves_std = Moves([])
        self.add_moves_describe(self.lst_moves)
        # mean de tous les joueurs pour le move_id
        # std de tous les joueurs pour le move_id

        self._mean_drop_end_time = None
        self._mean_drop_end_time = self.mean_drop_end
        self._std_drop_end_time = None
        self._std_drop_end_time = self.std_drop_end
Exemple #13
0
 def __init__(self, white=coords.white, black=coords.black):
     self.black = Board_objects(black)
     self.white = Board_objects(white)
     self.turn = "black"
     self.moves = Moves()
     self.check = False
     self.checkmate = False
     self.check_pieces = []
     self.safe_moves = {}
     self.check_moves = {}
     self.possible_check = False
     self.__init_move()
Exemple #14
0
def get_potential_games(game):
    futures = []
    presenter = GamePresenter(game)
    for x, y in Moves(game).get_empty_positions():
        log("---- generating futures -----")
        log(presenter.dump_board_state())
        log("active player %s" % presenter.active_symbol())
        future = GameAIPresenter(game.clone())
        future.move(x, y, future.active_symbol())
        log("future board state is:")
        log(presenter.dump_board_state())
        log("future active player is: %s" % presenter.active_symbol())
        futures.append(((x, y), future))
    return futures
Exemple #15
0
def movesCallback(code, state, our_uuid):
    logging.debug('code: ' + code + ' state: ' + state + 'user: '******'state = %s with length %d' % (state, len(state)))
    if (len(state) == 0):
        # This is from iOS, we use the custom redirect URL
        redirectUrl = ios_redirect_url
    else:
        # This is from android, so we use the HTTPS one
        redirectUrl = https_redirect_url

    m = Moves(client_id=client_id,
              client_secret=client_secret,
              redirect_url=redirectUrl)

    token = m.auth(request_token=code)
    logging.debug("token = %s" % token)

    moves_access_info = m.access_json
    logging.debug("Response from moves = %s" % moves_access_info)
    # We got a good response from moves.
    # Now we generate a uuid
    saveAccessToken(moves_access_info, our_uuid)
Exemple #16
0
    def main(self):
        self.start()
        moves = Moves()
        principalVariation = PrincipalVariation(moves, self.playerIsWhite,
                                                self.maxDepth)
        board = Board()
        board.initChess(moves, self.playerIsWhite)

        if (self.playerIsWhite):
            player = "W"
            opponent = "B"
        else:
            player = "B"
            opponent = "W"
        board.getAllCurrentLegalMoves(self.whiteTurn)

        while (len(board.currentAllLegalMoves) > 0):
            #if it is player's turn
            if (self.playerIsWhite == self.whiteTurn):
                while (True):
                    playerMove = input(player + ": ")
                    if (playerMove.lower() == "quit"
                            or playerMove.lower() == "q"):
                        print("Computer wins.")
                        exit(0)
                    try:
                        playerMove = self.convertMoveEnteredToInternalNumericalMove(
                            playerMove)
                        board.updateMove(playerMove)
                        break
                    except ValueError as e:
                        print(str(e))
                board.drawBoard(self.playerIsWhite)
                self.whiteTurn = not self.whiteTurn
                board.getAllCurrentLegalMoves(self.whiteTurn)
            #if it is opponent's turn
            else:
                print("Computer is thinking ......")
                bestScore, bestMove = principalVariation.principalVariationSearch(
                    -math.inf, math.inf, board.history, board.whiteKing,
                    board.whiteQueen, board.whiteBishop, board.whiteKnight,
                    board.whiteRook, board.whitePawn, board.blackKing,
                    board.blackQueen, board.blackBishop, board.blackKnight,
                    board.blackRook, board.blackPawn, board.whiteQueenCastle,
                    board.whiteKingCastle, board.blackQueenCastle,
                    board.blackKingCastle, self.whiteTurn, 0)
                if (bestMove == "No Move"):
                    break
                board.updateMove(bestMove)
                print(opponent + ": " +
                      self.convertInternalNumericalMoveToBoardMove(bestMove))
                board.drawBoard(self.playerIsWhite)
                self.whiteTurn = not self.whiteTurn
                board.getAllCurrentLegalMoves(self.whiteTurn)

            ##For debugging
            # if(self.whiteTurn):
            # 	currentPlayer="White"
            # else:
            # 	currentPlayer="Black"

            # print("Now it is "+currentPlayer+"'s turn")
            # print(board.currentAllLegalMoves)
        if (self.whiteTurn == self.playerIsWhite):
            print("Computer wins.")
        else:
            print("Player wins.")
Exemple #17
0
 def __init__(self):
     self.board = Board()
     self.moves = Moves()
     self.getPlayers()
     self.active_player = 1
@author: REDACTED
"""

#This program imports the relevant data from the Moves API
#It calculates the speeds at all points within each commute
#It then exports the data to a GeoJSON file for plotting

import datetime as dt
import json

from geopy.distance import vincenty
from moves import Moves

#Input the authorisation information for the Moves API
m = Moves("REDACTED", "REDACTED", "REDACTED")

# Set up a list of the locations we're interested in.
my_locs = [{
    'name': 'home',
    'lat': 51.5376610267,
    'lon': -0.1334586581
}, {
    'name': 'work',
    'lat': 51.5245335649,
    'lon': -0.134065590859
}]


# A function to check if the distance between two locations
# is less than a set distance
Exemple #19
0
                    self.useItem(self.bag[0])
                    print(f'{self.name} has {self.current_HP} HP')

    #def take_damage(sef):


#Initialize battling Pokemon
squirtle = Pokemon('Squirtle', 100, 5, 'water', 1)
charmander = Pokemon('Charmander', 100, 5, 'fire', 1)
#Add moves

#Shouldn't  be able to change a few things like EXP or HP in obj initialization
#add underscores and update it everywhere

#initialize squirtle moveset
waterGun = Moves("Water Gun", 'water', 50)
bubble = Moves("Bubble", 'water', 25)
scratch = Moves("Scratch", 'normal', 15)
growl = Moves("Growl", 'normal', 15)

#initialize charmander moveset
fireSpin = Moves("Fire Spin", 'fire', 25)
flamethrower = Moves('Flamethrower', 'fire', 50)

#initialize item
potion = Items('Potion', 20)
superpotion = Items('Super Potion', 50)

#Squirtle Add Moves
squirtle.add_move(waterGun)
squirtle.add_move(bubble)
    def __init__(self,
                 name: str,
                 level: int = 1,
                 moveset: list = [],
                 evolves_from: object = None):
        self.pokemon = client.get_pokemon(name)
        self.name = self.pokemon.name.capitalize()
        self.evolves_from = evolves_from
        self.species = client.get_pokemon_species(self.pokemon.id)
        self.level = level if not evolves_from else evolves_from.level
        self.held_item = None if not evolves_from else evolves_from.held_item
        self.used_item = None
        # experience needed per level
        self.growth = client.get_growth_rate(
            self.species.growth_rate.name).levels
        # sets levels by increasing order
        self.growth.reverse()
        # sets inner exp
        self._exp = self.growth[
            self.level -
            1].experience if not self.evolves_from else self.evolves_from._exp
        self.state = 'Awake' if not evolves_from else evolves_from.state
        self.nature = client.get_nature(random.choice(range(
            1, 26))) if not evolves_from else evolves_from.nature
        self.evolution_chain = client.get_evolution_chain(
            self.species.evolution_chain.url.split('/')
            [-2]).chain if not evolves_from else evolves_from.evolution_chain
        # chain of evolution with requirements based on item, level or condition
        self.evolves_to = self.get_evolution(self.evolution_chain)
        # adds moves to the moveset
        self.moveset = Moves(
            self, moveset if not evolves_from else evolves_from.moveset)
        # gets type effectiveness against self
        self.type_defense = type_defense(name=self.pokemon.name, debug=False)
        for stat in self.pokemon.stats:
            # gets the name of each stat
            param = eval('stat.stat.name')
            # if is evolution, iv is the same as pre-evolution randomly chooses an IV
            iv = getattr(self.evolves_from,
                         param)['iv'] if self.evolves_from else random.randint(
                             0, 16)
            # checks nature modifiers
            nature_mod = (1.1 if param == self.nature.increased_stat.name else
                          1) if hasattr(self.nature.increased_stat,
                                        name) else 1
            nature_mod = (0.9 if param == self.nature.increased_stat.name else
                          1) if hasattr(self.nature.increased_stat,
                                        name) else 1
            # creates a dictionary with all parameters
            obj = eval(
                "dict([('base', stat.base_stat), ('effort', stat.effort), ('iv', iv), ('nature', nature_mod), ('current', stat.base_stat), ('max', stat.base_stat)])"
            )
            # sets dict for every attribute
            setattr(self, param, obj)
            # sets the current stat for very attribte based on level
            self.map_by_level(param)

        # if self.species.has_gender_differences:
        #misc attributes

        self.gender = (
            'Male' if self.attack['iv'] > self.species.gender_rate else
            'Female') if not self.evolves_from else evolves_from.gender
        self.color = self.species.color.name
        self.base_happiness = self.species.base_happiness
        self.capture_rate = self.species.capture_rate
        self.shape = self.species.shape.name
        self.is_baby = self.species.is_baby
        self.height = self.pokemon.height
        self.weight = self.pokemon.weight
        self.attack_order = self.pokemon.order
        self.abilities = self.pokemon.abilities
Exemple #21
0
from moves import Moves
import csv

# create instance
moves = Moves()

print('Querying API for move information...')
moves.GetAllMoves()
print('Finished getting move information')

print('Writing file...')
with open('move_database.csv', 'w', newline='') as moveDB:
    writer = csv.writer(moveDB,
                        delimiter=',',
                        quotechar='"',
                        quoting=csv.QUOTE_MINIMAL)

    headers = [
        'Name', 'Description', 'Type', 'Category', 'Power', 'Accuracy', 'PP'
    ]
    writer.writerow(headers)

    for move in moves.moves:
        # get each piece of information
        name = move.name
        description = move.description
        moveType = move.type
        category = move.category
        power = move.power
        accuracy = move.accuracy
        pp = move.pp
Exemple #22
0
 def __init__(self,board=None):
     if board:
         self.board = board
     mv = Moves()
Exemple #23
0
    def go(self):
        mv = Moves()
        movelist = []
        y = 0
        for line in self.board:
            x = 0
            for square in line:
                if square=="P":
                    mlist = mv.pawn(x,y)

                    mlist2 = filter(lambda xy: not self.board[xy[1]][xy[0]].isupper(),mlist)
                    for x2, y2 in mlist2:
                        if util.isThisMoveLegal(copy.deepcopy(self.board),(square.upper(),x,x2,y,y2)):
                            usimove = util.rawtousi(square.lower(),x,x2,y,y2,self.sente)
                            if y2 < 3:
                                usimove += "+"
                            #usimove = util.rawtousi(square.lower(),x,x2,y,y2)
                            movelist.append(usimove)
                            #print(usimove)
                            #print("pawn at {}{} can move to {}{}".format(x+1,y+1,x2+1,y2+1))
                elif square=="L":
                    mlist = mv.lance(x,y)
                    mlist2 = []
                    for lx,ly in mlist:
                        if self.board[ly][lx]=="":
                            mlist2.append((lx,ly))
                        elif self.board[ly][lx].isupper():
                            break
                        else:
                            mlist2.append((lx,ly))
                            break
                        
                    for x2, y2 in mlist2:
                        if util.isThisMoveLegal(copy.deepcopy(self.board),(square.upper(),x,x2,y,y2)):
                            usimove = util.rawtousi(square.lower(),x,x2,y,y2,self.sente)
                            if y2 < 3:
                                usimove += "+"
                            #usimove = util.rawtousi(square.lower(),x,x2,y,y2)
                            movelist.append(usimove)
                            #print(usimove)
                            #print("lance at {}{} can move to {}{}".format(x+1,y+1,x2+1,y2+1))
                elif square=="N":
                    mlist = mv.knight(x,y)

                    mlist2 = filter(lambda xy: not self.board[xy[1]][xy[0]].isupper(),mlist)
                    for x2, y2 in mlist2:
                        if util.isThisMoveLegal(copy.deepcopy(self.board),(square.upper(),x,x2,y,y2)):
                            usimove = util.rawtousi(square.lower(),x,x2,y,y2,self.sente)
                            if y2 < 3:
                                usimove += "+"
                            #usimove = util.rawtousi(square.lower(),x,x2,y,y2)
                            movelist.append(usimove)
                            #print(usimove)
                            #print("knight at {}{} can move to {}{}".format(x+1,y+1,x2+1,y2+1))
                elif square=="S":
                    mlist = mv.silver(x,y)

                    mlist2 = filter(lambda xy: not self.board[xy[1]][xy[0]].isupper(),mlist)
                    for x2, y2 in mlist2:
                        if util.isThisMoveLegal(copy.deepcopy(self.board),(square.upper(),x,x2,y,y2)):
                            usimove = util.rawtousi(square.lower(),x,x2,y,y2,self.sente)
                            if y2 < 3:
                                usimove += "+"
                            #usimove = util.rawtousi(square.lower(),x,x2,y,y2)
                            movelist.append(usimove)
                            #print(usimove)
                            #print("silver at {}{} can move to {}{}".format(x+1,y+1,x2+1,y2+1))
                elif square=="G":
                    mlist = mv.gold(x,y)

                    mlist2 = filter(lambda xy: not self.board[xy[1]][xy[0]].isupper(),mlist)
                    for x2, y2 in mlist2:
                        if util.isThisMoveLegal(copy.deepcopy(self.board),(square.upper(),x,x2,y,y2)):
                            usimove = util.rawtousi(square.lower(),x,x2,y,y2,self.sente)
                            #usimove = util.rawtousi(square.lower(),x,x2,y,y2)
                            movelist.append(usimove)
                            #print(usimove)
                            #print("gold at {}{} can move to {}{}".format(x+1,y+1,x2+1,y2+1))
                elif square=="K":
                    mlist = mv.king(x,y)
                    mlist2 = filter(lambda xy: not self.board[xy[1]][xy[0]].isupper(),mlist)

                    for x2, y2 in mlist2:
                        if util.isThisMoveLegal(copy.deepcopy(self.board),(square.upper(),x,x2,y,y2)):
                            usimove = util.rawtousi(square.lower(),x,x2,y,y2,self.sente)
                            #usimove = util.rawtousi(square.lower(),x,x2,y,y2)
                            movelist.append(usimove)
                            #print(usimove)
                            #print("king at {}{} can move to {}{}".format(x+1,y+1,x2+1,y2+1))
                elif square=="R":
                    mlist = mv.rook(x,y)
                    mlist2 = []
                    #print(mlist)
                    for mlpart in mlist[:4]:
                        for lx,ly in mlpart:
                            if self.board[ly][lx]=="":
                                mlist2.append((lx,ly))
                            elif self.board[ly][lx].isupper():
                                break
                            else:
                                mlist2.append((lx,ly))
                                break
                    for x2, y2 in mlist2:
                        if util.isThisMoveLegal(copy.deepcopy(self.board),(square.upper(),x,x2,y,y2)):
                            usimove = util.rawtousi(square.lower(),x,x2,y,y2,self.sente)
                            if y2 < 3:
                                usimove += "+"
                            #usimove = util.rawtousi(square.lower(),x,x2,y,y2)
                            movelist.append(usimove)
                            #print(usimove)
                            #print("rook at {}{} can move to {}{}".format(x+1,y+1,x2+1,y2+1))
                elif square=="B":
                    mlist = mv.bishop(x,y)
                    mlist2 = []
                    #print(mlist)
                    for mlpart in mlist[:4]:
                        for lx,ly in mlpart:
                            if self.board[ly][lx]=="":
                                mlist2.append((lx,ly))
                            elif self.board[ly][lx].isupper():
                                break
                            else:
                                mlist2.append((lx,ly))
                                break

                    for x2, y2 in mlist2:
                        if util.isThisMoveLegal(copy.deepcopy(self.board),(square.upper(),x,x2,y,y2)):
                            usimove = util.rawtousi(square.lower(),x,x2,y,y2,self.sente)
                            if y2 < 3:
                                usimove += "+"
                            #usimove = util.rawtousi(square.lower(),x,x2,y,y2)
                            movelist.append(usimove)
                            #print(usimove)
                            #print("bishop at {}{} can move to {}{}".format(x+1,y+1,x2+1,y2+1))
                elif square=="+P" or square=="+L" or square=="+N" or square=="+S":
                    mlist = mv.gold(x,y)

                    mlist2 = filter(lambda xy: not self.board[xy[1]][xy[0]].isupper(),mlist)
                    for x2, y2 in mlist2:
                        if util.isThisMoveLegal(copy.deepcopy(self.board),(square.upper(),x,x2,y,y2)):
                            usimove = util.rawtousi(square.lower(),x,x2,y,y2,self.sente)
                            #usimove = util.rawtousi(square.lower(),x,x2,y,y2)
                            movelist.append(usimove)
                            #print(usimove)
                            #print("narikin at {}{} can move to {}{}".format(x+1,y+1,x2+1,y2+1))
                elif square=="+R":
                    mlist = mv.rook(x,y,dragon=True)
                    mlist2 = []
                    for mlpart in mlist[:4]:
                        for lx,ly in mlpart:
                            if self.board[ly][lx]=="":
                                mlist2.append((lx,ly))
                            elif self.board[ly][lx].isupper():
                                break
                            else:
                                mlist2.append((lx,ly))
                                break
                    for lx,ly in mlist[4]:
                            mlist2.append((lx,ly))
                    for x2, y2 in mlist2:
                        if util.isThisMoveLegal(copy.deepcopy(self.board),(square.upper(),x,x2,y,y2)):
                            usimove = util.rawtousi(square.lower(),x,x2,y,y2,self.sente)
                            #usimove = util.rawtousi(square.lower(),x,x2,y,y2)
                            movelist.append(usimove)
                            #print(usimove)
                            #print("dragon at {}{} can move to {}{}".format(x+1,y+1,x2+1,y2+1))
                elif square=="+B":
                    mlist = mv.bishop(x,y,horse=True)
                    mlist2 = []
                    for mlpart in mlist[:4]:
                        for lx,ly in mlpart:
                            if self.board[ly][lx]=="":
                                mlist2.append((lx,ly))
                            elif self.board[ly][lx].isupper():
                                break
                            else:
                                mlist2.append((lx,ly))
                                break
                    for lx,ly in mlist[4]:
                            mlist2.append((lx,ly))

                    for x2, y2 in mlist2:
                        if util.isThisMoveLegal(copy.deepcopy(self.board),(square.upper(),x,x2,y,y2)):
                            usimove = util.rawtousi(square.lower(),x,x2,y,y2,self.sente)
                            #usimove = util.rawtousi(square.lower(),x,x2,y,y2)
                            movelist.append(usimove)
                            #print(usimove)
                            #print("horse at {}{} can move to {}{}".format(x+1,y+1,x2+1,y2+1))
                x += 1
            y += 1
        sfeny = ["a","b","c","d","e","f","g","h","i"]
        for koma in self.komadai:
            for tempy in range(9):
                for tempx in range(9):
                    if self.board[tempy][tempx]=="":
                        if self.sente:
                            usimove = "{}*{}{}".format(koma.upper(),tempx+1,sfeny[tempy])
                        else:
                            usimove = "{}*{}{}".format(koma.upper(),9-tempx,sfeny[8-tempy])
                        if util.isThisDropLegal(copy.deepcopy(self.board),(koma.upper(),tempx,tempy)):
                            movelist.append(usimove)

        print(movelist)
        #time.sleep(5)
        if util.isCheck(self.board,"opponent"):
            ismate = util.isMate(copy.deepcopy(self.board),movelist,self.sente)
            if ismate[0]:
                print("bestmove {}".format("resign"))
                return
            else:
                movelist = ismate[1]
                bm = random.choice(movelist)
                print("bestmove {}".format(bm))
                return

        scoredmovelist=[]
        nodes = 0
        for usimove in movelist:
            calcboard = copy.deepcopy(self.board)
            calckmd = copy.deepcopy(self.komadai)
            if usimove[1]=="*":
                piece = usimove[0]
                calckmd.remove(piece.lower())
                if self.sente:
                    calcboard[self.SFD[usimove[3]]][int(usimove[2])-1] = piece
                else:
                    calcboard[8-self.SFD[usimove[3]]][9-int(usimove[2])] = piece
            else:
                if self.sente:
                    piece = calcboard[self.SFD[usimove[1]]][int(usimove[0])-1]
                    if usimove[-1]=="+":
                        piece = "+"+piece
                    if calcboard[self.SFD[usimove[3]]][int(usimove[2])-1].islower():
                        calckmd.append(calcboard[self.SFD[usimove[3]]][int(usimove[2])-1][-1].lower())
                    calcboard[self.SFD[usimove[3]]][int(usimove[2])-1] = piece
                    calcboard[self.SFD[usimove[1]]][int(usimove[0])-1] = ""
                else:
                    piece = calcboard[8-self.SFD[usimove[1]]][9-int(usimove[0])]
                    if usimove[-1]=="+":
                        piece = "+"+piece
                    if calcboard[8-self.SFD[usimove[3]]][9-int(usimove[2])].islower():
                        calckmd.append(calcboard[8-self.SFD[usimove[3]]][9-int(usimove[2])][-1].lower())
                    calcboard[8-self.SFD[usimove[3]]][9-int(usimove[2])] = piece
                    calcboard[8-self.SFD[usimove[1]]][9-int(usimove[0])] = ""
            #okomadai = evaluation.getokomadai(calcboard,calckmd) 
            #score = evaluation.evaluation(calcboard,calckmd,self.okomadai,mv,turn="opponent")
            score = tansaku.minimax(calcboard,calckmd,self.okomadai,mv,2,1,self.sente)
            nodes += 1
            print("info time 1 depth 1 nodes {} score cp {} pv {}".format(nodes,score,usimove))
            scoredmovelist.append((usimove,score))

        #print(scoredmovelist)
        bm = max(scoredmovelist,key=lambda x:x[1])
        if bm[1]>4000:
            bms = util.TsumiTansaku(self.board,movelist,self.sente,"me")
            if bms==[]:
                bms = [usimv for usimv,sco in scoredmovelist if sco == bm[1]]
        else:
            bms = [usimv for usimv,sco in scoredmovelist if sco == bm[1]]
        print(bms)
       
        bm = random.choice(bms)
        print("bestmove {}".format(bm))