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
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)
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): Moves.__init__(self) self.p1 = Player('white', 'down') self.p2 = Player('black', 'up') self.p1.enemy = self.p2 self.p2.enemy = self.p1 self.turn = self.p1
def scramble(tempcube): # assigning the colors to the array of zeroes for i in range(6): for j in range(3): for k in range(3): tempcube[i][j][k] = i + 1 # scrambling the array by turning random faces for i in range(20): face = random.randrange(0, 6) Moves.turnFront(face, tempcube)
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)
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})
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()
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)
def next_move(self, move_list, game): player_pos = game.player.pos move_prob = [] for i in range(game.grid.size[0]): node_list = [] start = a.node((player_pos[0], player_pos[1], a.nodeState.START)) start.boundary = True final = a.node((i, 0, a.nodeState.FINAL)) final.f = math.inf node_list.append(start) node_list.append(final) y = game.barrier.h for x in game.barrier.get_wall_x(game.grid.size): n = a.node((x, y, a.nodeState.WALL, 1)) node_list.append(n) path = a.astar(node_list, start, final, game.grid.size) if path: while path.father and path.father.state[2] != a.nodeState.START: path = path.father if path is not None: player_next_pos = list(path.get_pos()) player_last_pos = list(player_pos) trans = [ player_next_pos[0] - player_last_pos[0], player_next_pos[1] - player_last_pos[1] ] move = Moves.from_translation(tuple(trans)) if move in move_list: move_prob.append(move) s = [0, 0] for move in move_prob: print(move) t = list(move.translation()) s[0] += t[0] s[1] += t[1] if s[0] > 0: s[0] = 1 elif s[0] < 0: s[0] = -1 if s[1] > 0: s[1] = 1 elif s[1] < 0: s[1] = -1 print(s) return Moves.from_translation(tuple(s))
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'], [])
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)
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
def split_moves_by_side(self, limit, use_droplet=True): """creates individual moves in three categories. Left moves, right moves, both sides moves (all_moves) ---- :param use_droplet: for adult, use False :type: bool""" moves = Moves.from_repetition(self.rep, limit) # print("len drops", len(self.droplets)) if use_droplet: left_moves = LeftMoves.from_list_of_moves(moves, droplets=self.droplets) right_moves = RightMoves.from_list_of_moves(moves, droplets=self.droplets) else: left_moves = LeftMoves.from_list_of_moves(moves) right_moves = RightMoves.from_list_of_moves(moves) # # self.left_moves = left_moves # self.right_moves = right_moves # print(left_moves.list_id, right_moves.list_id) left_moves.flip_moves() right_moves.flip_angle() self.all_moves = AllMoves.from_list_of_moves(left_moves, right_moves) self.num_moves = len(self.all_moves) self.all_moves.selection_sort( ) # self.left_moves.selection_sort() # self.right_moves.selection_sort()
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)
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
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)
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
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)
class Sweep: 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) def main(self): print('main code goes here') jp = self.joint_proba() self.accept_reject() self.moves() return jp def joint_proba(self): alpha,K, A,Z,sigma,y = self.parameters jp = np.zeros(Z.shape) print('self', self.n_components) for t in range(self.n_components): jp[t,:]=alpha[t]*K[t]*A[t,t]*Z[t,:]*sigma[t]*y[t] # confirm how to choose Z values print('sum', jp,np.sum(jp, axis=1)) return jp def moves(self): print('moves here') move = self.moveObj move.update_A(1,2) move.update_sigma() #move.update_Z() #move.update_alpha() #move.split_comb() #move.birth_death() def accept_reject(self): print('accept reject here')
def rateAttack(self, playerKing, playerQueen, playerBishop, playerKnight, playerRook, playerPawn, opponentKing, opponentQueen, opponentBishop, opponentKnight, opponentRook, opponentPawn): Moves = self.Moves counter = 0 kingPosition = None underAttack = Moves.whiteKing_illegalMoves( playerKing, playerQueen, playerBishop, playerKnight, playerRook, playerPawn, opponentKing, opponentQueen, opponentBishop, opponentKnight, opponentRook, opponentPawn) for i in range(64): #we check if our piece at this position is under attack by placing our king at this position #if our king is under attack, playerPawn at this position is also under attack if ((playerPawn >> i) & 1 == 1): kingPosition = (1 << i) if (underAttack & kingPosition != 0): counter = counter - 64 #if our king is under attack, playerRook at this position is also under attack elif ((playerRook >> i) & 1 == 1): kingPosition = (1 << i) if (underAttack & kingPosition != 0): counter = counter - 500 #if our king is under attack, playerKnight at this position is also under attack elif ((playerKnight >> i) & 1 == 1): kingPosition = (1 << i) if (underAttack & kingPosition != 0): counter = counter - 300 #if our king is under attack, playerBishop at this position is also under attack elif ((playerBishop >> i) & 1 == 1): kingPosition = (1 << i) if (underAttack & kingPosition != 0): counter = counter - 300 #if our king is under attack, playerQueen at this position is also under attack elif ((playerQueen >> i) & 1 == 1): kingPosition = (1 << i) if (underAttack & kingPosition != 0): counter = counter - 900 kingPosition = playerKing if (underAttack & kingPosition != 0): counter = counter - 2000 #our piece under attack is less important than our piece actually being captured by opponent, so we divide it by 2 return counter / 2
def rateMoveability(self, playerKing, playerQueen, playerBishop, playerKnight, playerRook, playerPawn, opponentKing, opponentQueen, opponentBishop, opponentKnight, opponentRook, opponentPawn, depth, material, numOfPossibleMoves): Moves = self.Moves counter = 0 #5 points for each valid move counter = counter + (numOfPossibleMoves * 5) #either checkmate or stalemate #stalemate means no square to move to, except for squares that will get king into checked if (numOfPossibleMoves == 0): #if king currently in checked and no place to move to, checkmate if (playerKing & Moves.whiteKing_illegalMoves( playerKing, playerQueen, playerBishop, playerKnight, playerRook, playerPawn, opponentKing, opponentQueen, opponentBishop, opponentKnight, opponentRook, opponentPawn) != 0): counter = counter + (-200000 * depth) #if king currently is not in checked and no place to move to, stalemate else: counter = counter + (-150000 * depth) return counter
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
import random import torch from game import Game from agent import RLAgent from moves import Moves game = Game() agent = RLAgent() moves = Moves() num_win = 0 #initialize no. of win by human num_lose = 0 #initialize no. of win by ai but loss by human num_tie = 0 random.seed(1000) def check_board_and_may_update_state_values(): global num_win, num_lose, num_tie win_or_tie = True if game.who_wins() == -1: #human win print("YOU WIN!!") agent.update_state_values(0) num_win += 1 elif game.who_wins() == 1: #ai win print("YOU LOSE!!") agent.update_state_values(1)
class Splitter(object): """cette classe gère la séparation des données. Permet de feeder une séquence de choplo et export les moves en list.""" 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 create_moves(self): self.index = 1 while self.index < len(self.repetition): drop_last = self.repetition.splitter_info.drop_in[self.index - 1] vasque_last = self.repetition.splitter_info.vasque_start[self.index - 1] # could be useful someday drop_current = self.repetition.splitter_info.drop_in[self.index] vasque_current = self.repetition.splitter_info.vasque_start[self.index] # could be useful someday self.on_event(drop_current, vasque_current, drop_last, vasque_last) self.index += 1 self.save_move() # essential to save the last move def on_event(self, drop_current, vasque_current, drop_last, vasque_last): """Permet d'eviter de rentrer dans les conditions a chaque index, si none.. rien ne se passe """ if drop_last == 0 and drop_current == 1: self.drop_in() elif drop_last == 1 and drop_current == 0: self.drop_end() if vasque_last==0 and vasque_current==1: self.vasque_in() elif vasque_last==1 and vasque_current==0: self.vasque_out() def drop_in(self): if self.current_move is not None: self.save_move() self.initialise_move() def drop_end(self): # print("Drop end") # print(self.current_move.start_index - self.index, abs(self.current_move.start_index - self.index)) self.current_move.drop_end = abs(self.current_move.drop_in_index - self.index) def vasque_in(self): if self.current_move is not None: if self.current_move.vasque_in is not None: self.current_move.vasque_in = abs(self.current_move.drop_in_index - self.index) def vasque_out(self): if self.current_move is not None: if self.current_move.vasque_in is not None: self.current_move.vasque_out = abs(self.current_move.drop_in_index - self.index) def initialise_move(self): self.current_move = Move() self.current_move.drop_in_index = self.index def save_move(self): self.current_move.end_idx = self.index - 1 self.current_move.set_data_from_splitter(copy(self.repetition)) # print(self.current_move.drop_end) self.moves.append(copy(self.current_move)) def get_moves(self, limit): return self.moves.list_of_moves[:limit]
def __init__(self, x, y, dx, dy, screenRect, v = 25): Moves.__init__(self,x,y,dx,dy,screenRect,v) self.drawImage(self.image)
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
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
def __init__(self, screenRect): print "MADE PLAYER" Moves.__init__(self,175, 550,0,0,screenRect,40) self.rect.topleft = 175,550 pygame.draw.circle(self.image, self.color, (self.width/2,self.height/2),12, 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))
def sample_move(): return Moves.random()
def __init__(self, x,y, dx, dy, screenRect,v = 125, c = (255,0,0)): Moves.__init__(self,x,y,dx,dy,screenRect,v) self.color = c #pygame.draw.rect(self.image, self.color, self.image.get_rect(), 0) pygame.draw.rect(self.image, self.color, Rect(0,0, self.width, self.height), 0)
@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
def update(self, dt): if self.screenRect.colliderect(self.rect): self.drawImage(self.image, dt) Moves.update(self,dt) else: self.kill()
def __init__(self, x,y, dx,dy, screenRect, v=20): Moves.__init__(self,x,y,dx,dy,screenRect,v) self.image.fill((0,255,0)) self.drawImage(self.image,1000)
def update(self, dt): if self.screenRect.colliderect(self.rect): Moves.update(self,dt) else: self.kill()
# rep1 = analyse.AnalyseChildCPMultiSenso(lst_patient_id, repetition=1) # rep2 = analyse.AnalyseChildCPMultiSenso(lst_patient_id, repetition=2) # rep3 = analyse.AnalyseChildCPMultiSenso(lst_patient_id, repetition=3) # rep4 = analyse.AnalyseChildCPMultiSenso(lst_patient_id, repetition=4) # # create_pickle("rep1_ms_cp", rep1) # create_pickle("rep2_ms_acp", rep2) # create_pickle("rep3_ms_cp", rep3) # create_pickle("rep4_ms_cp", rep4) r1 = load_pickle("rep1_ms_cp") r2 = load_pickle("rep2_ms_cp") r3 = load_pickle("rep3_ms_cp") r4 = load_pickle("rep4_ms_cp") moves = Moves.from_analysis([r1, r2, r3, r4]) df = create_df_multisenso_single_col(moves).replace('NaN', np.nan) # create_pickle('multisenso_df', df) output_path = 'C:/Users/tousi/Documents/Labo_Laurent_Ballaz/Projet_ChopLo/pyChoplo_output/' folder = 'df_excel/' path = output_path + folder df_success = df.loc[df['target_reach'] == 'success'] df_success_and_cm = df.loc[(df['target_reach'] == 'success') & (df['have_cm'] == 'with_cm')] df_success_and_cm = filter_outlier(df_success_and_cm)
def __init__(self,board=None): if board: self.board = board mv = Moves()