def expand_frontier(self, state): for row in (-1, 0, 1): for col in (-1, 0, 1): # Only allow adjacent non-diagonal moves #if row != 0 and col != 0: # continue # Get the new position position = Position(state.row() + row, state.column() + col) # Rule out invalid positions if position.row() < 0 or position.column() < 0 or \ position.row() >= self.environment.height or position.column() >= self.environment.width: return p = position.as_tuple() # If not an obstacle and not explored, then add to frontier if p not in self.environment.obstacles and p not in self.explored: self.f += 1 # Create the new state new_state = State(position, state.target, state.cost + 1, state) # Update state path cost new_state.path_cost = new_state.cost + self.heuristic(new_state) # Add to frontier self.frontier.add(new_state)
def __init__(self): Position.__init__(self) self.rect = None self.image = None self.name = None self.type = None self.has_dialog = False
def openPosition(self, order, bar, market = False): position = 0 if order.instrument != "" and order.instrument != bar[11]: print "bar of other instrument!" #exception here raise NotImplementedError if market: if order.orderType == -1: order.price = bar[4] else: order.price = bar[9] position = Position(order, bar[0], self.slippage, self.randomizeSlippage, self.point, stat = []) if self.getStat: position.stat = [] position.stat.append(self.strategy.onGetStatOnPositionOpen(position, bar)) else: position = Position(order, bar[0], stat = []) if self.getStat: position.stat = [] position.stat.append(self.strategy.onGetStatOnPositionOpen(position, bar)) self.positions.append(position) self.orders.remove(position.order) self.strategy.onOrderExecution(position.order)
class TestLongGBPUSDPosition(unittest.TestCase): def setUp(self): getcontext.prec = 2 side = "LONG" market = "GBP/USD" units = Decimal(str(2000)) exposure = Decimal("2000.00") avg_price = Decimal("1.51819") cur_price = Decimal("1.51770") self.position = Position( side, market, units, exposure, avg_price, cur_price ) def test_calculate_pips(self): pos_pips = self.position.calculate_pips() self.assertEqual(pos_pips, Decimal("-0.00049")) def test_calculate_profit_base(self): profit_base = self.position.calculate_profit_base(self.position.exposure) self.assertEqual(profit_base, Decimal("-0.64571")) def test_calculate_profit_perc(self): profit_perc = self.position.calculate_profit_perc(self.position.exposure) self.assertEqual(profit_perc, Decimal("-0.03229"))
def funcVisit(self, x, y): pos = Position(x, y) if pos.x < 0: pos.x = 0 if pos.y < 0: pos.y = 0 self.map[pos.x][pos.y].visible = True self.map[pos.x][pos.y].discovered = True
def test_move_info(self): """Tests move info generation.""" pos = Position() e4 = pos.get_move_info(Move.from_uci('e2e4')) self.assertEqual(e4.san, 'e4') self.assertFalse(e4.is_check) self.assertFalse(e4.is_checkmate) self.assertFalse(e4.is_castle)
def generate_long_algebraic_moves(self): position = Position() for move in self.moves: try: long_move = "%s%s%s" % position.move(move) if len(long_move) > 0: yield long_move except Exception, err: raise BaseException("Could not process move %s (%s)" % (move, err))
class TestRoundTripXOPosition(unittest.TestCase): """ Trade a round-trip trade in Exxon-MObil where the initial trade is a buy/long of 100 shares of XOM, at a price of $74.78, with $1.00 commission. """ def setUp(self): """ Set up the Position object that wil store the PnL. """ self.position = Position('BOT', 'XOM', Decimal('100'), Decimal('74.78'), Decimal('1.00'), Decimal('74.78'), Decimal('74.78')) def test_calculate_round_trip(self): """ After the subsequent purchase, carry outtwo more buys/longs and then close the position out with two additional sells/shorts. The following prices have been tested against those calculated via Interactive Brokers' Trader Workstation (TWS). """ # set the data in the object self.position.transact_shares('BOT', Decimal('100'), Decimal('74.63'), Decimal('1.00')) self.position.transact_shares('BOT', Decimal('250'), Decimal('74.620'), Decimal('1.25')) self.position.transact_shares('SLD', Decimal('200'), Decimal('74.58'), Decimal('1.00')) self.position.transact_shares('SLD', Decimal('250'), Decimal('75.26'), Decimal('1.25')) self.position.update_market_value(Decimal('77.75'), Decimal('77.77')) # start testing the values inside the object # the assertEqual method is derived by the unittest.TestCase from which the class derive from self.assertEqual(self.position.action, 'BOT') self.assertEqual(self.position.ticker, 'XOM') self.assertEqual(self.position.quantity, Decimal('0')) self.assertEqual(self.position.buys, Decimal('450')) self.assertEqual(self.position.sells, Decimal('450')) self.assertEqual(self.position.net, Decimal('0')) self.assertEqual(self.position.avg_bot, Decimal('74.65778')) self.assertEqual(self.position.avg_sld, Decimal('74.95778')) self.assertEqual(self.position.total_bot, Decimal('33596.00')) self.assertEqual(self.position.total_sld, Decimal('33731.00')) self.assertEqual(self.position.net_total, Decimal('135.00')) self.assertEqual(self.position.total_commission, Decimal('5.50')) self.assertEqual(self.position.net_incl_comm, Decimal('129.50')) self.assertEqual(self.position.avg_price, Decimal('74.665')) self.assertEqual(self.position.cost_basis, Decimal('0.00')) self.assertEqual(self.position.market_value, Decimal('0.00')) self.assertEqual(self.position.unrealised_pnl, Decimal('0.00')) self.assertEqual(self.position.realised_pnl, Decimal('129.50'))
def move(self, steps: int) -> 'MegaCar': """ Move car "step" amount of places. """ if self.horizontal: return Car.new(self.start + Position.new(steps, 0), self.horizontal, self.length) else: return Car.new(self.start + Position.new(0, steps), self.horizontal, self.length)
def __repr__(self): result = "Account %s\n" % (self.name) result += " %s\n" % (Position.format(Account.CASH, None, None, self.cash),) for position in self.positions.values(): result += " %s\n" % position result += "================" result += " %s\n" % (Position.format(None, None, None, account.get_value()),) return result
class TestPosition(unittest.TestCase): def setUp(self): self.pos = Position() self.pos_dup = Position() self.pos_other = Position() self.pos_other.make_move(Move.from_uci('e2e4')) def test___delitem__(self): del self.pos['a1'] self.assertIs(None, self.pos['a1']) def test___eq__(self): self.assertEqual(True, self.pos == self.pos_dup) self.assertEqual(False, self.pos == self.pos_other) def test___getitem__(self): self.assertEqual(True, self.pos['e1'] == 'K') def test___hash__(self): self.assertEqual(True, hash(self.pos) == hash(self.pos_dup)) self.assertEqual(False, hash(self.pos) != hash(self.pos_other)) def test___ne__(self): self.assertEqual(False, self.pos != self.pos_dup) self.assertEqual(True, self.pos != self.pos_other) def test___repr__(self): self.assertEqual("Position('%s')" % Fen(), repr(self.pos)) def test___setitem__(self): self.pos['a1'] = 'K' self.assertEqual('K', self.pos['a1']) def test___str__(self): self.assertEqual(str(Fen()), str(self.pos)) self.assertEqual(False, str(self.pos) == str(self.pos_other)) def test_copy(self): copy = self.pos.copy() self.assertEqual(copy, self.pos) def test_is_check(self): self.assertEqual(False, self.pos.is_check()) def test_is_checkmate(self): self.assertEqual(False, self.pos.is_checkmate()) def test_is_game_over(self): self.assertEqual(False, self.pos.is_game_over()) def test_is_insufficient_material(self): self.assertEqual(False, self.pos.is_insufficient_material()) def test_is_king_attacked(self): self.assertEqual(False, self.pos.is_king_attacked(WHITE)) def test_is_stalemate(self): self.assertEqual(False, self.pos.is_stalemate())
def setUp(self): p = Position() self.moves = p.get_legal_moves() m1 = Move.from_uci('e2e4') m2 = Move.from_uci('b1c3') self.san = SanNotation(p, m1) self.san_dup = SanNotation(p, m1) self.san_other = SanNotation(p, m2) self.position = p self.m1 = m1 self.m2 = m2
def simulation(self): """This function will perform the simulation process with several trials.""" for pos in self.positions: p = Position(pos) cumu_ret = np.zeros(self.num_trials) daily_ret = np.zeros(self.num_trials) for trial in range(self.num_trials): #Get a daily return value cumu_ret[trial] = p.invest() #convert return value to return ratio daily_ret[trial] = (cumu_ret[trial] / 1000.0) - 1 self.trials.append(daily_ret)
def cmdBreak(invoker): preprocess = not invoker.hasOption("*") invoker.checkUnsupportedOptions() arguments = invoker.getArguments().strip() runtime = invoker.getRuntime() position = runtime.getPosition(runtime.getCurrentFrame()) if not arguments: if not position: raise CommandError, "%s: no current position" % invoker.getName() id = invoker.getSession().addBreakpointAtPosition(position) at = position.getShortDescription() else: words = arguments.split() linenr_required = False if words[0][0] == '#': linenr_required = True linenr_string = words[1] try: scriptindex = int(words[0][1:]) script = invoker.getSession().getScriptByIndex(scriptindex) if not script: raise ValueError except ValueError: raise CommandError, "%s: invalid script index: %s" % (invoker.getName(), words[0][1:]) else: linenr_string = words[0] script = False try: linenr = int(linenr_string) if not script: if not position: raise CommandError, "%s: no current script" % invoker.getName() script = position.getScript() position = Position(script, linenr) id = invoker.getSession().addBreakpointAtPosition(position) at = position.getShortDescription() except ValueError: if linenr_required: raise CommandError, "%s: line number required" % invoker.getName() try: result = runtime.eval(words[0], True, preprocess) except KeyboardInterrupt: return [] if not result.isObject() or not result.getValue().isFunction(): raise CommandError, "%s: not a function: %s" % (invoker.getName(), result) id = invoker.getSession().addBreakpointAtFunction(result.getValue()) at = str(result) return ["Breakpoint %d at %s." % (id, at)]
def __init__(self, name): Position.__init__(self) self.name = name load_creature(self.name) self.hp = CREATURES_LOADED[self.name]['hp'] self.mp = CREATURES_LOADED[self.name]['mp'] self.level = CREATURES_LOADED[self.name]['level'] self.attack = CREATURES_LOADED[self.name]['attack'] self.attack_m = CREATURES_LOADED[self.name]['attack_m'] self._class = CREATURES_LOADED[self.name]['_class'] self._def = CREATURES_LOADED[self.name]['_def'] self.def_m = CREATURES_LOADED[self.name]['def_m'] self.selfie = None
class TestRoundTripPGPosition(unittest.TestCase): """ Test a round-trip trade in Proctor & Gamble where the initial trade is a sell/short of 100 shares of PG, at a price of $77.69, with $1.00 commission. """ def setUp(self): self.position = Position('SLD', 'PG', Decimal('100'), Decimal('77.69'), Decimal('1.00'), Decimal('77.68'), Decimal('77.70')) def test_calculate_round_trip(self): """ After the subsequent sale, carry out two more sells/shorts and then close the position out with two additional buys/longs. The following prices have been tested against those calculated via Interactive Brokers' Trader Workstation (TWS). """ self.position.transact_shares('SLD', Decimal('100'), Decimal('77.68'), Decimal('1.00')) self.position.transact_shares('SLD', Decimal('50'), Decimal('77.70'), Decimal('1.00')) self.position.transact_shares('BOT', Decimal('100'), Decimal('77.77'), Decimal('1.00')) self.position.transact_shares('BOT', Decimal('150'), Decimal('77.73'), Decimal('1.00')) self.position.update_market_value(Decimal('77.72'), Decimal('77.72')) self.assertEqual(self.position.action, 'SLD') self.assertEqual(self.position.ticker, 'PG') self.assertEqual(self.position.quantity, Decimal('0')) self.assertEqual(self.position.buys, Decimal('250')) self.assertEqual(self.position.sells, Decimal('250')) self.assertEqual(self.position.net, Decimal('0')) self.assertEqual(self.position.avg_bot, Decimal('77.746')) self.assertEqual(self.position.avg_sld, Decimal('77.688')) self.assertEqual(self.position.total_bot, Decimal('19436.50')) self.assertEqual(self.position.total_sld, Decimal('19422.00')) self.assertEqual(self.position.net_total, Decimal('-14.50')) self.assertEqual(self.position.total_commission, Decimal('5.00')) self.assertEqual(self.position.net_incl_comm, Decimal('-19.50')) self.assertEqual(self.position.avg_price, Decimal('77.67600')) self.assertEqual(self.position.cost_basis, Decimal('0.00')) self.assertEqual(self.position.market_value, Decimal('0.00')) self.assertEqual(self.position.unrealised_pnl, Decimal('0.00')) self.assertEqual(self.position.realised_pnl, Decimal('-19.50'))
def _compute_path(self, airplane, timelimit): #print "looking for a path from " + str(start) + " to " + str(dest) + ", starting at " + str(p) begin_computation = time.time() start = Position(airplane) start.time = self._arena.clock plan = [ start ] # aim for approach position, one step in front of airport if isinstance(airplane.dest, Airport): tmp = Position(airplane.dest) tmp.dir = tmp.reverseDirection() approach = tmp.step(0, 1) approach.dir = airplane.dest.dir # turn around else: approach = Position(airplane.dest) approach.dir_tolerance = 90 # allow max. 90 degree derivation from target direction # enter recursion if not self._step_recursive(airplane, plan, start, approach, timelimit): if time.time() > timelimit: print "Path of " + str(airplane) + " from " + str(start) + " to " + str(airplane.dest) + ": COMPUTATION TIMEOUT (comp.time=" + \ str(int((time.time()-begin_computation) * 1000000)/1000.0) + "ms)" else: print "Airplane " + str(airplane) + " will delay its take-off due to ongoing traffic" return False # append destination itself d = Position(airplane.dest) d.time = plan[-1].time + 1 plan.append( d ) self._compute_commands(plan, airplane) print "Path of " + str(airplane) + " from " + str(start) + " to " + str(airplane.dest) + " (" + str(len(plan)) + " steps, comp.time=" + \ str(int((time.time()-begin_computation) * 100000)/100.0) + "ms): ", print string.join(map(str, plan), '; ') # add schedule to database for s in plan: if s.time < self._arena.clock: raise Exception("can't schedule for past time " + str(s.time) + ". current time: " + str(self._arena.clock)) if not s.time in self._schedules: self._schedules[s.time] = {} self._schedules[s.time][airplane] = s return True
def set_static(self, pix_pos=None, x_shift=None, y_shift=None, x_offset=0, y_offset=0, z=1, scale=1.0): if pix_pos is None: pix_pos = Position() else: pix_pos = Position(pos=pix_pos) if x_shift is None or y_shift is None: self.states['static']['pix'].append(self.sheet) else: self.states['static']['pix'].append(self.sheet.copy(pix_pos.x(), pix_pos.y(), x_shift, y_shift)) self.pix = self.parent.m_scene.addPixmap(self.states['static']['pix'][0]) self.pix.setPos(self.pos.x(), self.pos.y()) self.pix.setOffset(x_offset, y_offset) self.pix.setZValue(z) self.pix.setScale(scale)
def __init__(self, view=None, position=None): Position.__init__(self) gobject.GObject.__init__(self) self.view = view # associated BoardView self.game = None self.node = None # the currently active game node for i in range(64): self.squares.append("") if position: self.set_position(position) else: self.setup_starting_pieces()
def _try_letters_at_position(self, board, letters_at_position): '''Adds the letters to the board at the given position. Returns False if a non-word is created by any letter.''' starting_pos = letters_at_position.position_with_direction.position.copy() direction = letters_at_position.position_with_direction.direction letters = letters_at_position.letters try: board.add_letters(letters, starting_pos, direction) except OutOfBoundsException: return False # Check that there is a word at the original position/direction if not self.is_word(board.get_word(starting_pos, direction)): # We didn't make a real word return False # We made a real word, now check to make sure we didn't create any # non-words in the other direction. other_direction = Position.get_other_direction(direction) moving_position = starting_pos.copy() for _ in range(len(letters)): generated_word = board.get_word(moving_position, other_direction) moving_position.add_in_direction(1, direction) # for next time if len(generated_word) < 2: # This one isn't a word- it's just a letter. We're fine continue if not self.is_word(generated_word): # We accidentally made a non word! return False # We made a word, and didn't make any non-words in the other direction! return True
def setUp(self): """ Set up the Position object that wil store the PnL. """ self.position = Position('BOT', 'XOM', Decimal('100'), Decimal('74.78'), Decimal('1.00'), Decimal('74.78'), Decimal('74.78'))
def fill_position(): with open(POSITION_DATA_PATH, newline='') as data: data_reader = csv.reader(data) for item in data_reader: Position.create(\ date = datetime.datetime.strptime(item[0], TIME_PATTERN).date(),\ time = datetime.datetime.strptime(item[0], TIME_PATTERN).time(),\ x = float(item[1]),\ y = float(item[2]),\ z = float(item[3]),\ speed = float(item[4]),\ attack_angle = float(item[5]),\ direction_angle = float(item[6]))
def interactive_search(game_index): game = games[game_index - 1] print("Trying to solve game with breadth first algortihm... ") print("If I can't solve it in a second, I'll ask for your help.") breath_search(game, 1) print("We can simplify this problem by \"freezing\" some cars.") while True: for car in game.cars: car.immobile = False change_goal = bool(input("Do you want to change the goal? True/False ")) if change_goal: index = int(input("Give the index of the goal car: (e.g.: 2) ")) position = list(map(int, input("Give the position of the goal: (e.g.: 2,3) ").split(","))) position = Position.new(position[0], position[1]) game.goal = (index, position) freeze_cars = list(map(int, input("Tell me which cars to freeze: (e.g.: 10, 14, 16) ").split(", "))) freeze_cars = [game.cars[i] for i in freeze_cars] for car in freeze_cars: car.immobile = True total_time = int(input("How long do want to run? ")) try: breath_search(game, total_time) except Win as win: save = bool(input("You won! Do you want to save this game and proceed? True/False ")) if save: game = win.board
def __init__(self, pos_row=0, pos_col=0, icon=Entity.player): """ Contain pos, representation, and direction """ self.pos = Position(pos_row, pos_col) self.icon = icon self.prev_icon = Block.empty self.moved = Move.none
def get_position(self): position = Position() position.squares = copy(self.squares) position.fullmove_number = self.fullmove_number position.side_to_move = self.side_to_move position.en_passant_file = self.en_passant_file position.en_passant_square = self.en_passant_square position.castling_availability = copy(self.castling_availability) position.halfmove_clock = self.halfmove_clock return position
def from_fen(cls, fen_str): # Separate the 6 components board_str, active_colour_str, castling_str, en_passant_str,\ half_move_str, full_move_str = fen_str.strip().split(' ') position = Position() # Construct the board board = tuple() for rank_str in board_str.split('/'): rank = tuple() for piece_str in rank_str: if piece_str in '12345678': # Blanks rank += (None,) * int(piece_str) else: # Piece piece_colour = WHITE if piece_str.isupper() else BLACK rank += (cls.mappings[piece_str.upper()](piece_colour),) board = (rank,) + board # Rest of Properties position.board = board position.active_colour = WHITE if active_colour_str=='w' else BLACK position.castling = '' if castling_str is '-' else castling_str position.en_passant = None if en_passant_str=='-' else get_coord_from_rank_file(en_passant_str) position.half_move = int(half_move_str) position.full_move = int(full_move_str) return position
def resize(self, x, y): direction = self.direction position = Position() position.x = self.x position.y = self.y size = Size() size.width = self.width size.height = self.height side = get_side(direction) if side is not VERTICAL: size.width = x - self.pivot.x if size.width < 0: position.x = x else: position.x = self.pivot.x if side is not HORIZONTAL: size.height = y - self.pivot.y if size.height < 0: position.y = y else: position.y = self.pivot.y self.set_position(position) self.set_size(size)
def __init__(self, start, end): self.start = start self.end = end if start.y == end.y: self.horizontal = True self.length = abs(end.x - start.x) else: self.horizontal = False self.length = abs(end.y - start.y) self.positions = [start] for i in range(1, self.length): if self.horizontal: self.positions.append(start + Position.new(i, 0)) else: self.positions.append(start + Position.new(0, i)) self.positions.append(end)
def test_single_step_pawn_move(self): """Tests that single step pawn moves are possible.""" pos = Position() a3 = Move.from_uci('a2a3') self.assertTrue(a3 in pos.get_pseudo_legal_moves()) self.assertTrue(a3 in pos.get_legal_moves()) pos.get_move_info(a3) pos.make_move(a3)
def test_pawn_captures(self): """Tests pawn captures in the kings gambit.""" pos = Position() pos.make_move(pos.get_move_from_san("e4")) pos.make_move(pos.get_move_from_san("e5")) pos.make_move(pos.get_move_from_san("f4")) accepted = pos.copy() self.assertTrue(Move.from_uci("e5f4") in accepted.get_pseudo_legal_moves()) self.assertTrue(Move.from_uci("e5f4") in accepted.get_legal_moves()) accepted.make_move(accepted.get_move_from_san("exf4")) wierd_declined = pos.copy() wierd_declined.make_move(wierd_declined.get_move_from_san("d5")) wierd_declined.make_move(wierd_declined.get_move_from_san("exd5"))
def test_try_action_fail3(self): # Tests a failing try_action due to action being out of turn (it involves moving someone # else but the current player's avatar, despite otherwise being legal) with self.assertRaises(InvalidActionException): GameTree.try_action(GameTree(self.__state2), Action(Position(0, 1), Position(2, 1)))
def get_index_from_x_y(self, x, y): (horizontal, vertical) = self.get_aspect() position = Position() position.x = int((x - self.x) * pango.SCALE / horizontal) position.y = int((y - self.y) * pango.SCALE / vertical) return self.layout.xy_to_index(position.x, position.y)
def on_mouse_release(x, y, button, modifiers): global Screenstate global seed if Screenstate == "MineField": x = x - Position.world_offset[0] y = y - Position.world_offset[1] tilepos = Position.pixtotile((x, y)) chunkpos = Position.pixtochunk((x, y)) if button == mouse.LEFT: logging.debug('Clicked at (%d, %d), %s, %s, %s', x, y, chunkpos, tilepos, Position.world_offset) #print('Clicked at', x, y, chunkpos, tilepos) chunk = chunk_dict.get(chunkpos, None) if chunk: chunk.activatetile(tilepos=tilepos) if button == mouse.RIGHT: logging.debug('Clicked at (%d, %d), %s, %s, %s', x, y, chunkpos, tilepos, Position.world_offset) #print('Clicked at', x, y, chunkpos, tilepos) chunk = chunk_dict.get(chunkpos, None) if chunk: chunk.flagtile(tilepos) elif Screenstate == "MainMenu": button = state_dict[Screenstate].getbuttonclicked(mouse_pos=(x, y), window=window) if not button: pass elif button.text == "New game": logging.debug("Clicked New game") ChunkManager.dump_chunks() ScoreManager.clearscore() ChunkManager.generate_new_seed() print("seed is %s", seed) ChunkManager.updategenchunks(Position.world_offset, (window.width, window.height)) Screenstate = "MineField" elif button.text == "Load game": logging.debug("Clicked Load game") ChunkManager.dump_chunks() if os.path.isfile('resources\savefile.dat'): seed, randomstate = SaveManager.loadpicklejarfromfile() random.seed(seed) print("seed is %s", seed) if randomstate: random.setstate(randomstate) Screenstate = "MineField" else: logging.critical("No savefile found!") elif button.text == "Save game": logging.debug("Clicked Save game") SaveManager.savepicklejartofile() elif button.text == "Exit game": logging.debug("Clicked Quit game") pyglet.app.exit()
def get_action(self, state: State) -> Action: # Return caffenaited action return Action(Position(0xc0ff33, 1337), Position(0xc0ff33, 1337))
Returns: str: La couleur du joueur gagnant. """ # while self.damier.piece_de_couleur_peut_se_deplacer(self.couleur_joueur_courant) or \ # self.damier.piece_de_couleur_peut_faire_une_prise(self.couleur_joueur_courant): # self.tour() # # if self.couleur_joueur_courant == "blanc": # return "noir" # else: # return "blanc" if __name__ == "__main__": # Point d'entrée du programme. On initialise une nouvelle partie, et on appelle la méthode jouer(). partie = Partie() gagnant = partie.jouer() valide_str = "" valide_bool_true = True valide_bool_false = False pas_valide = "erreur" assert partie.position_cible_valide(Position(4,5)) == [valide_bool_true, valide_str] assert partie.position_cible_valide(Position(4,12)) == [valide_bool_false, pas_valide]
def main(): #Get the time of creation for this log_time = strftime("%b-%d-%Y-%H-%M-%S", gmtime()) time_array = [] readings_cnt = 0 fname = 'logs/%s.txt' % (log_time) f = open(fname, 'w') pos = Position(0, 0, 0) cycle_time = .10 #This is a tenth of a second. Which means 10 hz. gotOrigin = False gyro_x_gotOrigin = False ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=10) #ser.close() accel_z_rate = 0 z_rate_array = [] cnt = 0 new_accel_z = 0 #Initialize a reading counter r_cnt = 0 #Initialize plotter ion() x_graph = arange(0, 100, 1) y_graph = array([0] * 100) fig = figure() ax = fig.add_subplot(111) ax.axis([0, 100, -180, 180]) line1 = ax.plot(x_graph, y_graph, 'r-') line2 = ax.plot(x_graph, y_graph, 'bo') line3 = ax.plot(x_graph, y_graph, 'go') comp_array = [0] * 100 local_min = [0] * 100 graph_time_array = [0] * 100 gyro_x_array = [0] * 100 gyro_x_peaks = [0] * 100 gyro_x_rests = [0] * 100 local_peak_count = 0 local_rest_count = 0 PEAK = 0 REST = 0 situp_cnt = 0 max_readings = 10 print("Finish plotter") while (1): s = ser.readline() old_accel_z = new_accel_z """ while (s == ""): print "READING..." s = ser.readline() print "READING DONE" """ if s == "AGDATA\n": while (s == "AGDATA\n"): s = ser.readline() now = dt.datetime.now() timestamp = round(float(now.strftime('%s.%f')), 3) t = timestamp #This is the time since the epoch in milliseconds. #Strip the newline before starting s = s.strip("\n") accel, gyro, sens = parseSerialReading(s) #Print out data #print "Accel: ", accel, "Gyro: ", gyro accel_z = accel[2] gyro_x = gyro[0] if gyro_x_gotOrigin == False: gyro_x_origin = gyro[0] gyro_x_gotOrigin = True gyro_x -= gyro_x_origin gyro_x_array.append(gyro_x) time_array.append(t) graph_time_array.append(t) if len(time_array) > 1: R = math.sqrt((accel[0]**2) + (accel[1]**2) + (accel[2]**2)) #roll = math.degrees(math.acos(accel[0]/R)) #pitch = math.degrees(math.acos(accel[1]/R)) #yaw = math.degrees(math.acos(accel[2]/R)) roll = math.degrees(math.atan2(accel[0], accel[2]) + math.pi) pitch = math.degrees(math.atan2(accel[1], accel[2]) + math.pi) #gyro_z*dt/1000 converts the gyro data into degrees. comp_part = (gyro_x) * (time_array[r_cnt] - time_array[r_cnt - 1]) / 1000 comp_filt = ((0.92) * (roll + comp_part)) + ((.08) * (accel[0])) #comp_filt = ( (0.85)*(roll+comp_part) ) + ( (.15)*(roll)) if gotOrigin == False: origin = comp_filt gotOrigin = True comp_filt = comp_filt - origin #print "Comp Filter: %f" % (comp_filt) comp_array.append(comp_filt) #Write data to log file for future usage. txt = "%f,%f,%f\n" % (t - time_array[0], roll, pitch) f.write(txt) #plot complementary filter results! CurrentXAxis = arange( len(comp_array) - 100, len(comp_array), 1) line1[0].set_data(CurrentXAxis, array(comp_array[-100:])) ax.axis([ CurrentXAxis.min(), CurrentXAxis.max(), min(comp_array), max(comp_array) ]) #find local minimum #gyro_x_array.append(gyro #if r_cnt % 50 == 0 and r_cnt > 0: result = validPeak(gyro_x, comp_filt) if (result == 1): gyro_x_peaks.append(comp_filt) gyro_x_rests.append( -800 ) #This will represent a null number that is impossible line2[0].set_data(CurrentXAxis, array(gyro_x_peaks[-100:])) if REST == 1: local_peak_count += 1 elif (result == 2): gyro_x_rests.append(comp_filt) gyro_x_peaks.append( -800 ) #This will represent a null number that is impossible line3[0].set_data(CurrentXAxis, array(gyro_x_rests[-100:])) local_rest_count += 1 else: gyro_x_peaks.append( -800 ) #This will represent a null number that is impossible gyro_x_rests.append( -800 ) #This will represent a null number that is impossible if PEAK == 1 and REST == 1: situp_cnt += 1 local_rest_count = 0 #We should see any counts while in the peak threshold zoen local_peak_count = 0 print "You have done %d situps!" % (situp_cnt) PEAK = 0 REST = 0 if PEAK == 0 and local_peak_count >= max_readings and REST == 1: PEAK = 1 print "ITS A PEAK!", local_peak_count if REST == 0 and local_rest_count >= max_readings: REST = 1 print "ITS A REST!", local_rest_count #ax.axis([CurrentXAxis.min(),CurrentXAxis.max(),min(gyro_x_array),max(gyro_x_array)]) """ now = len(comp_array) - 1 if r_cnt > 10: if comp_array[now-1] < comp_array[now] and comp_array[now-1] < comp_array[now-2]: local_min.append(comp_array[now-1]) line2[0].set_data(CurrentXAxis,array(local_min[-100:])) """ #line1.set_ydata(comp_array) comp_filt_prev = comp_filt fig.canvas.draw() #print "Roll: %f\tPitch: %f\tYaw: %f\tCOMP_FILT: %f" %(roll,pitch,yaw,comp_filt) #print "ACCEL_Z: %f\tGYRO_Z: %f" % (accel_z, gyro_z) r_cnt += 1 else: print s cnt += 1
elif instr.startswith('settings timebank'): bot.timebank = int(instr.split(' ')[-1]) elif instr.startswith('settings time_per_move'): bot.time_per_move = int(instr.split(' ')[-1]) return '' if __name__ == '__main__': import sys from position import Position from rolloutbot import RolloutBot import argparse parser = argparse.ArgumentParser(description='run RolloutBot') parser.add_argument('weights_file', nargs='?', default=None, help='pkl file containing weights') args = parser.parse_args() pos = Position() bot = RolloutBot(weights_file=args.weights_file) while True: try: instr = raw_input() except Exception as e: sys.stderr.write('error reading input') outstr = parse_command(instr, bot, pos) sys.stdout.write(outstr) sys.stdout.flush()
continue if matches.group(2) and matches.group(2) != m.source.file: continue if matches.group(3) and matches.group(3) != str(m.source.rank): continue # Move matches. Assert it is not ambiguous. if source: raise MoveError( "Move is ambiguous: %s matches %s and %s." % san, source, m) source = m.source if not source: raise MoveError("No legal move matches %s." % san) return Move(source, target, matches.group(5) or None) if __name__ == '__main__': from position import Position from move import Move p = Position() m = Move.from_uci('b1c3') san = SanNotation(p, m) print san print SanNotation.to_move(p, san)
def hill_climb(seed_state, iterations=20, search_algo=Search.A_star_man, metric_function=max_fringe_size, reset_limit=20, log=False): """An implementation of the hill climbing algorithm. The search will generate neighbor states of a seed state. Over each neighbor state, the input search_algo is conducted over it. A running account of the state that maximizes the metric_function is kept. Each iteration, a new set of neighbor states is generated. The search halts after a certain number of iterations has been met or a local maximia has been met. """ # Gather parameters from the seed state dim = seed_state.maze.dim p = seed_state.maze.p # variable that returns the metric values metric_list = [] # initial and goal states for the search algorithm initial_state = Position([0, 0]) goal_state = Position([dim - 1, dim - 1]) # Generates all neighboring states neighbors = generate_neighbor_states(seed_state) current_best = seed_state.copy() # This is the list of current_best states on which a local maximia was reached # If the reset_limit condition is met, we will return the hardest maze # in this list. local_maximas = [] # Loops for number of iterations. Iter must be an int value. i = 0 # Set the reset counter. reset_count = 0 while (i < iterations): metric_list.append(metric_function(current_best.metrics)) if log: print("iter {}..".format(i), end='') found_new_best = False neighbors = generate_neighbor_states(current_best) # For each state in the neighbors of current_best, # Check if the neighbor is the new currest_best for state in neighbors: valid, _, metrics = search_algo(state.maze, initial_state, goal_state) state.metrics = metrics if valid: metric = metric_function(metrics) if metric > metric_function(current_best.metrics): # Update current best # if log: print("\tFound new best: {}".format(metric)) current_best = state.copy() found_new_best = True # If none of the neighbors can top the current best # We are at a local maximia. if not found_new_best: if log: print("**At a local maxima...metric val:{}".format( metric_function(current_best.metrics))) # At this maze to the local maximia list. local_maximas.append(current_best) # If we've reset beyond the limit, return the best of local maximia if reset_count == reset_limit: if log: print( "**Max reset limit reached. Returning best of local maximia." ) # Finding best maximia best = current_best for maximia in local_maximas: score = metric_function(maximia.metrics) if score > metric_function(best.metrics): best = maximia return best, metric_list # Preparing to reset the serach at a new maze reset_count += 1 valid = False # Loop to ensure the new maze is solveable before restarting while (not valid): current_best = HardState(Maze(dim, p, 0)) valid, _, metrics = search_algo(current_best.maze, initial_state, goal_state) current_best.metrics = metrics # Reset iter index. Restart the search. i = 0 if log: print("**Resetting...{} of {}.\n".format( reset_count, reset_limit)) continue i += 1 # Total iteration cap has been met. Return current_best if log: print("Max iterations met.") return current_best, metric_list
def test_try_action_fail4(self): # Tests a failing try_action due to action involves moving thru another character with self.assertRaises(InvalidActionException): GameTree.try_action(GameTree(self.__state2), Action(Position(4, 0), Position(2, 1)))
def test_try_action_fail5(self): # Tests a failing try_action due to action involves moving to an already occupied tile with self.assertRaises(InvalidActionException): GameTree.try_action(GameTree(self.__state2), Action(Position(4, 0), Position(3, 0)))
#!/usr/bin/env python import roslib import rospy import sys from navigator import Navigator from position import Position try: rospy.init_node('sdp_navigator') nav = Navigator() # Pass arguments:Point[0],Point[1],Quaternion[2] myarg = rospy.myargv(argv=sys.argv) command = myarg[1] x = float(myarg[2]) y = float(myarg[3]) angle = float(myarg[4]) position = Position(x, y, angle) if myarg[1] == 'pose': nav.set_initial_position(position) elif myarg[1] == 'goal': nav.go_to(position) rospy.loginfo("done") except Exception as e: print("error: ", e)
def playGame(game, robot, robot2, q): global facts game = Game(game) facts = game.getFacts() q.put(facts) robot1Moves, robot2Moves = game.getMoves() assert (robot.color == ROBOT_1_COLOR) assert (robot2.color == ROBOT_2_COLOR) turn = 0 global stopGame global resetGame global lowerPosistions for rb1Move, rb2Move in zip_longest(robot1Moves, robot2Moves, fillvalue=None): if resetGame is True: print('resetting') break if stopGame is True: print('stopping') if lowerPosistions is True: # This will move the robot arms closer to the table to prepare them to crash!!! print('lowering') Robot.movDownQuit(robot) Robot.movDownQuit(robot2) return turn += 1 logging.debug("Turn:%d" % turn) if rb1Move is not None: logging.debug("ROBOT1: Start[%d,%d] End[%d,%d] %s" % \ (rb1Move[0][0], rb1Move[0][1], rb1Move[1][0], rb1Move[1][1], robot.color)) start = Position(rb1Move[0][0], rb1Move[0][1]) end = Position(rb1Move[1][0], rb1Move[1][1]) castle = int(rb1Move[2]) if castle != 0: robot.castle(castle, 1) else: robot.move(start, end) if resetGame is True: print('resetting') break if stopGame is True: print('stopping') if lowerPosistions is True: # This will move the robot arms closer to the table to prepare them to crash!!! print('lowering') Robot.movDownQuit(robot) Robot.movDownQuit(robot2) return if rb2Move is not None: logging.debug("ROBOT2: Start[%d,%d] End[%d,%d] %s" % \ (rb2Move[0][0], rb2Move[0][1], rb2Move[1][0], rb2Move[1][1], robot2.color)) start = Position(rb2Move[0][0], rb2Move[0][1], True) end = Position(rb2Move[1][0], rb2Move[1][1], True) castle = int(rb2Move[2]) if castle != 0: robot2.castle(castle, 2) else: robot2.move(start, end) # The board is shared so it can be reset by either robot. #robot.resetBoard(None) robot.clearRobotPieces() robot2.clearRobotPieces() logging.debug("Cleared") # robot.printBoard() # robot.printCaptureBoard() # robot2.printCaptureBoard() robot.resetToOriginalPosition() robot2.resetToOriginalPosition() logging.debug("game complete and reset")
self.start_date = start_date self.end_date = end_date self.logs = logs def build_from_logs(self): for l in self.logs: pass return def get_portfolio(portfolio_id): return Portfolio() # Fake if __name__ == "__main__": # s_list = ["WPC", "WELL", "CCI", "PLD", "VER", "AMT", "MPW", "O", "PSA", "EQIX"] # s_list = ["V", "MA", "CCI", "PLD", "AAPL", "AMT", "O", "FB", X"OM"] s_list = ["GSK", "MSFT", "JPM", "XOM", "LMT", "GE"] # p = RiskyPortfolio(assets=s_list, weights=np.random.dirichlet(np.ones(len(s_list)), size=1), start_date="2000-01-01", end_date="2019-07-01") # print("Warning pairs:", p.corr_warning(threshold=0.6)) # dropping = p.corr_based_recommendation(threshold=0.7, period='d') # p.weighting_based_recommendation() test_p = RiskyPortfolio( positions={ 1299: Position(1299, 74.8, 1000, '2019-01-01'), 2318: Position(2318, 94.8, 1000, '2018-02-21') }) print(test_p.to_json())
def display(self): """This method display the labyrinth""" labyrinth = "" for i in range(self.heigth): for j in range(self.width): needle, tube, ether = self.object_positions if Position(i, j) == self.macgyver.position: labyrinth += "M" elif Position(i, j) == needle: if Position(i, j) not in self.macgyver.items: labyrinth += "n" else: labyrinth += "." elif Position(i, j) == tube: if Position(i, j) not in self.macgyver.items: labyrinth += "t" else: labyrinth += "." elif Position(i, j) == ether: if Position(i, j) not in self.macgyver.items: labyrinth += "e" else: labyrinth += "." elif Position(i, j) == self.arrival: labyrinth += "A" elif Position(i, j) == self.departure: labyrinth += "D" elif Position(i, j) in self.streets: labyrinth += "." elif Position(i, j) in self.walls: labyrinth += "#" labyrinth += "\n" return labyrinth
def setup(self): self._initialize_pieces() B = PieceColor.Black W = PieceColor.White p = PieceRank.Pawn k = PieceRank.Knight K = PieceRank.King Q = PieceRank.Queen b = PieceRank.Bishop r = PieceRank.Rook piece_positions = { # Back row for white Position(0, 0): Piece(r, W), Position(1, 0): Piece(k, W), Position(2, 0): Piece(b, W), Position(3, 0): Piece(Q, W), Position(4, 0): Piece(K, W), Position(5, 0): Piece(b, W), Position(6, 0): Piece(k, W), Position(7, 0): Piece(r, W), # Front row for white Position(0, 1): Piece(p, W), Position(1, 1): Piece(p, W), Position(2, 1): Piece(p, W), Position(3, 1): Piece(p, W), Position(4, 1): Piece(p, W), Position(5, 1): Piece(p, W), Position(6, 1): Piece(p, W), Position(7, 1): Piece(p, W), # Back row for black Position(0, 7): Piece(r, B), Position(1, 7): Piece(k, B), Position(2, 7): Piece(b, B), Position(3, 7): Piece(Q, B), Position(4, 7): Piece(K, B), Position(5, 7): Piece(b, B), Position(6, 7): Piece(k, B), Position(7, 7): Piece(r, B), # Front row for black Position(0, 6): Piece(p, B), Position(1, 6): Piece(p, B), Position(2, 6): Piece(p, B), Position(3, 6): Piece(p, B), Position(4, 6): Piece(p, B), Position(5, 6): Piece(p, B), Position(6, 6): Piece(p, B), Position(7, 6): Piece(p, B), } for position, piece in piece_positions.items(): self.add_piece(piece, position)
def a_star13(maze, start, end, walls): maze2 = copy.deepcopy(maze) opened = 0 p_queue = PriorityQueue(maxsize=0) cost_so_far = {} cost = {} prev = {} start_pos = Position(start, 0) p_queue.put(start_pos) prev[start] = None cost_so_far[start] = 0 cost[start] = 0 #initialize the position of the ghost by checking for the first instance where there is no wall ghostPos = [0, 0] initGhostPos = [0, 0] shouldBreak = False for i in range(len(walls)): for j in range(len(walls[i])): if maze2[i][j] is 'G': ghostPos = [i, j] initGhostPos = [i, j] shouldBreak = True break if (shouldBreak): break #set ghostDirection to be right at first ghostDirection = 'R' firstTurn = True while not p_queue.empty(): current = p_queue.get() x_pos = current.pos[0] y_pos = current.pos[1] #if pacman's position is equal to ghosts if (x_pos == ghostPos[0] and y_pos == ghostPos[1]): print("GAME OVER1") end = current.pos break if not firstTurn: #check if you pass through it if (prev[(x_pos, y_pos)][0] == x_pos and prev[(x_pos, y_pos)][1] == y_pos - 1 and x_pos == ghostPos[0] and y_pos == ghostPos[1] + 1 and ghostDirection is 'L'): print("GAME OVER2") end = current.pos break if (prev[(x_pos, y_pos)][0] == x_pos and prev[(x_pos, y_pos)][1] == y_pos + 1 and x_pos == ghostPos[0] and y_pos == ghostPos[1] - 1 and ghostDirection is 'R'): print("GAME OVER3") end = current.pos break firstTurn = False #check if pacman's position is the same as the end position: game over if x_pos == end[0] and y_pos == end[1]: print("YOU WIN") break #updating the ghosts position #if the ghost's direction is R and there is no wall, move it to the right #if there is a wall, change the direction so that it's going the other way #likewise the same logic applies for the ghost's direction being L if (ghostDirection is 'R'): if (walls[ghostPos[0]][ghostPos[1] + 1]): ghostDirection = 'L' ghostPos = [ghostPos[0], ghostPos[1] - 1] else: ghostPos = [ghostPos[0], ghostPos[1] + 1] else: if (walls[ghostPos[0]][ghostPos[1] - 1]): ghostDirection = 'R' ghostPos = [ghostPos[0], ghostPos[1] + 1] else: ghostPos = [ghostPos[0], ghostPos[1] - 1] #check if pacman's will pass through the ghost on it's next iteration # if(x_pos == ghostPos[0] and y_pos == ghostPos[1]): # print("GAME OVER") # break # if(maze2[ghostPos[0]][ghostPos[1]] != 'G' and maze2[ghostPos[0]][ghostPos[1]] != 'P'): # maze2[ghostPos[0]][ghostPos[1]] = 'g' opened += 1 neighbors = [(x_pos - 1, y_pos), (x_pos, y_pos + 1), (x_pos + 1, y_pos), (x_pos, y_pos - 1)] for neighbor in neighbors: if not neighbor[0] < 0 and not neighbor[1] < 0 and not neighbor[ 0] >= len(walls) and not neighbor[1] >= len(walls[0]): if not walls[neighbor[0]][neighbor[1]]: if neighbor not in cost or cost[neighbor] > ( cost_so_far[(x_pos, y_pos)] + 1 + manhattan_distance(neighbor, end)): new = Position( neighbor, cost_so_far[(x_pos, y_pos)] + 1 + manhattan_distance(neighbor, end)) cost_so_far[new.pos] = cost_so_far[(x_pos, y_pos)] + 1 cost[new.pos] = cost_so_far[ (x_pos, y_pos)] + 1 + manhattan_distance( neighbor, end) prev[new.pos] = [x_pos, y_pos] p_queue.put(new) current = end steps = 0 while maze[current[0]][current[1]] != 'P': current = prev[(current[0], current[1])] if maze[current[0]][current[1]] != 'G' and maze[current[0]][ current[1]] != 'g': maze2[current[0]][current[1]] = '.' steps += 1 maze2[start[0]][start[1]] = 'P' maze2[initGhostPos[0]][initGhostPos[1]] = 'G' return maze2, steps, opened
def __init__(self, *args, **kwargs): super(GameTreeTests, self).__init__(*args, **kwargs) # Initialize boards self.__board1 = Board.homogeneous(5, 5, 3) self.__board2 = Board.homogeneous(3, 5, 2) self.__board3 = Board({ Position(0, 0): Tile(5), Position(0, 1): Tile(3), Position(0, 2): Tile(2), Position(1, 0): Tile(2), Position(1, 1): Tile(3), Position(1, 2): Tile(2), Position(2, 0): Tile(3), Position(2, 1): Tile(4), Position(2, 2): Tile(1), Position(3, 0): Tile(1), Position(3, 1): Tile(1), Position(3, 2): Tile(5), Position(4, 0): Tile(2), Position(4, 1): Tile(3), Position(4, 2): Tile(4) }) # Initialize some players for testing self.__p1 = PlayerEntity("John", Color.RED) self.__p2 = PlayerEntity("George", Color.WHITE) self.__p3 = PlayerEntity("Gary", Color.BLACK) self.__p4 = PlayerEntity("Jeanine", Color.BROWN) self.__p5 = PlayerEntity("Obama", Color.RED) self.__p6 = PlayerEntity("Fred", Color.BROWN) self.__p7 = PlayerEntity("Stewart", Color.WHITE) self.__p8 = PlayerEntity("Bobby Mon", Color.BLACK) self.__p9 = PlayerEntity("Bob Ross", Color.WHITE) self.__p10 = PlayerEntity("Eric Khart", Color.BROWN) self.__p11 = PlayerEntity("Ionut", Color.RED) # ========================== STATE 1 ========================== # Initialize a premature state self.__state1 = State(self.__board1, [self.__p1, self.__p2, self.__p3, self.__p4]) # ========================== STATE 2 ========================== # Initialize a finalized state where at least two more rounds are possible self.__state2 = State(self.__board1, [self.__p1, self.__p2, self.__p3]) # Place all avatars # Player 1 place self.__state2.place_avatar(Color.RED, Position(4, 0)) # Player 2 place self.__state2.place_avatar(Color.WHITE, Position(0, 1)) # Player 3 place self.__state2.place_avatar(Color.BLACK, Position(2, 2)) # Player 1 place self.__state2.place_avatar(Color.RED, Position(1, 0)) # Player 2 place self.__state2.place_avatar(Color.WHITE, Position(2, 0)) # Player 3 place self.__state2.place_avatar(Color.BLACK, Position(3, 2)) # Player 1 place self.__state2.place_avatar(Color.RED, Position(1, 1)) # Player 2 place self.__state2.place_avatar(Color.WHITE, Position(4, 1)) # Player 3 place self.__state2.place_avatar(Color.BLACK, Position(3, 0)) # Make up tree for this state self.__tree2 = GameTree(self.__state2) # ========================== STATE 3 ========================== # Setup state that is one move away from game over self.__state3 = State( self.__board2, players=[self.__p5, self.__p6, self.__p7, self.__p8]) # Set up the board with placements s.t. only 2 moves can be made # Player 1 self.__state3.place_avatar(Color.RED, Position(3, 0)) # Player 2 self.__state3.place_avatar(Color.BROWN, Position(0, 0)) # Player 3 self.__state3.place_avatar(Color.WHITE, Position(1, 0)) # Player 4 self.__state3.place_avatar(Color.BLACK, Position(2, 0)) # Player 1 self.__state3.place_avatar(Color.RED, Position(3, 1)) # Player 2 self.__state3.place_avatar(Color.BROWN, Position(0, 1)) # Player 3 self.__state3.place_avatar(Color.WHITE, Position(1, 1)) # Player 4 self.__state3.place_avatar(Color.BLACK, Position(2, 1)) # Make move 1 for p1 self.__state3.move_avatar(Position(3, 1), Position(4, 1)) # Make up tree for this state self.__tree3 = GameTree(self.__state3) # ========================== STATE 4 ========================== # Setup state that is game over self.__state4 = copy.deepcopy(self.__state3) # Make final move self.__state4.move_avatar(Position(2, 0), Position(4, 0)) # Make up tree for this state self.__tree4 = GameTree(self.__state4) # ========================== STATE 5 ========================== # Setup state that includes heterogeneous board self.__state5 = State(self.__board3, players=[self.__p9, self.__p10, self.__p11]) # Player 1 self.__state5.place_avatar(Color.WHITE, Position(2, 0)) # Player 2 self.__state5.place_avatar(Color.BROWN, Position(0, 1)) # Player 3 self.__state5.place_avatar(Color.RED, Position(0, 2)) # Player 1 self.__state5.place_avatar(Color.WHITE, Position(1, 0)) # Player 2 self.__state5.place_avatar(Color.BROWN, Position(1, 2)) # Player 3 self.__state5.place_avatar(Color.RED, Position(0, 0)) # Player 1 self.__state5.place_avatar(Color.WHITE, Position(3, 1)) # Player 2 self.__state5.place_avatar(Color.BROWN, Position(2, 1)) # Player 3 self.__state5.place_avatar(Color.RED, Position(3, 2)) # Make up tree for this state self.__tree5 = GameTree(self.__state5)
def __init__(self): """Constructeur du Damier. Initialise un damier initial de 8 lignes par 8 colonnes. """ self.n_lignes = 8 self.n_colonnes = 8 self.cases = { Position(7, 0): Piece("blanc", "pion"), Position(7, 2): Piece("blanc", "pion"), Position(7, 4): Piece("blanc", "pion"), Position(7, 6): Piece("blanc", "pion"), Position(6, 1): Piece("blanc", "pion"), Position(6, 3): Piece("blanc", "pion"), Position(6, 5): Piece("blanc", "pion"), Position(6, 7): Piece("blanc", "pion"), Position(5, 0): Piece("blanc", "pion"), Position(5, 2): Piece("blanc", "pion"), Position(5, 4): Piece("blanc", "pion"), Position(5, 6): Piece("blanc", "pion"), Position(2, 1): Piece("noir", "pion"), Position(2, 3): Piece("noir", "pion"), Position(2, 5): Piece("noir", "pion"), Position(2, 7): Piece("noir", "pion"), Position(1, 0): Piece("noir", "pion"), Position(1, 2): Piece("noir", "pion"), Position(1, 4): Piece("noir", "pion"), Position(1, 6): Piece("noir", "pion"), Position(0, 1): Piece("noir", "pion"), Position(0, 3): Piece("noir", "pion"), Position(0, 5): Piece("noir", "pion"), Position(0, 7): Piece("noir", "pion"), }
def test_try_action_fail1(self): # Tests a failing try_action due to action being invalid (type-wise) with self.assertRaises(TypeError): self.__tree2.try_action(Position(0, 0), Position(1, 0))
def move(self, x, y): self.cursor.visible = False Position.move(self, x, y)
def test_try_action_fail2(self): # Tests a failing try_action due to action being invalid (not accessible via a straight # line path) with self.assertRaises(InvalidActionException): GameTree.try_action(GameTree(self.__state2), Action(Position(3, 0), Position(0, 0)))
def runTest(self): rv, es = guess_edit(self.initial_line, self.a, self.b, Position(*self.ppos), Position(*self.pos)) self.assertEqual(rv, True) self.assertEqual(self.wanted, es)
def generateAssignment(self, l, r, curFn): ''' Assignment. Possible cases: 1. var = expression simply generate the expression into var 2. *(e1) = e2 generate e1 into tmp0 (address) generate e2 into tmp1 put indirect tmp1 at tmp0 3. (*var).field = expression ''' if isinstance(l, Value): # case 1: simple variable if not l.isLValue(): raise SemanticError(l.getPosition(), "Cannot assign to an r-value") dest = l resultLoc, codeExpr = self.generateExpression(r, 0, dest, curFn) if resultLoc == dest: # already assigned where needed return codeExpr else: # need to copy _, codeMove = self.backend.genMove(dest, resultLoc, False) return codeExpr + codeMove elif l.data == 'deref': # case 2: dereferenced expression ptr = l.children[0] self.maxTempVarIndex = max(self.maxTempVarIndex, 1) rvPtr, codePtr = self.generateExpression( ptr, 0, Value.variable(Position.fromAny(ptr), labelname.getTempName(0, curFn)), curFn) assert (not rvPtr.getSource().isRegister()) rvR, codeR = self.generateExpression( r, 1, Value.variable(Position.fromAny(r), labelname.getTempName(1, curFn)), curFn) codePutIndirect = self.backend.genPutIndirect(rvPtr, rvR) return codePtr + codeR + codePutIndirect elif l.data == 'arrow': # case 3: member of a derefed struct ptr = l.children[0] fields = l.children[1:] self.maxTempVarIndex = max(self.maxTempVarIndex, 1) rvPtr, codePtr = self.generateExpression( ptr, 0, Value.variable(Position.fromAny(ptr), labelname.getTempName(0, curFn)), curFn) assert (not rvPtr.getSource().isRegister()) try: offset, type = structure.getField(rvPtr.getType().deref(), fields) except LookupError as e: raise SemanticError(Position.fromAny(r), str(e)) except ValueError as e: raise SemanticError(Position.fromAny(r), str(e)) if type.getIndirectionOffset() < 0: raise SemanticError(Position.fromAny(l), "Cannot assign to an r-value") rvR, codeR = self.generateExpression( r, 1, Value.variable(Position.fromAny(r), labelname.getTempName(1, curFn)), curFn) codePutIndirect = self.backend.genPutIndirect( rvPtr.withType(PtrType(type)), rvR, offset) return codePtr + codeR + codePutIndirect else: raise RuntimeError("Unknown assignment case")
def trivial(N, dim, p, search_algo=Search.A_star_man): """ The trivial strategy to developing hard mazes. Generates N number of valid mazes. Solves each one to maximize metrics. Returns the value of the largest metric and the associated maze. Return: ( (longest_path, maze_metrics_dict[longest_path_idx]), (largest_nodes_expanded, maze_metrics_dict[largest_nodes_expanded_idx]), (largest_fringe_size, maze_metrics_dict[largest_fringe_size_idx]), maze_dict ) """ # Generate N valid mazes mazes = [] for i in range(int(N)): found_valid = False while (not found_valid): m = Maze(dim, p, q=0) valid, _, _ = Util.valid_maze(m) if valid: mazes.append(m) found_valid = True # Setup for A* initial_state = Position([0, 0]) goal_state = Position([dim - 1, dim - 1]) # The output structure maze_metrics_dict = {} # These are the metrics to be maximized longest_path = 0 largest_nodes_expanded = 0 largest_fringe_size = 0 # The key for the associated maximized metrics longest_path_idx = 0 largest_nodes_expanded_idx = 0 largest_fringe_size_idx = 0 # For each maze in N, run the search algorithm. # Compare the solution's metrics with the current best. Replace if applicable for idx, maze in enumerate(mazes): _, _, metrics = search_algo(maze, initial_state, goal_state) maze_metrics_dict[idx] = (maze, metrics) if metrics.path_length >= longest_path: longest_path = metrics.path_length longest_path_idx = idx if metrics.total_nodes_expanded >= largest_nodes_expanded: largest_nodes_expanded = metrics.total_nodes_expanded largest_nodes_expanded_idx = idx if metrics.max_fringe_size >= largest_fringe_size: largest_fringe_size = metrics.max_fringe_size largest_fringe_size_idx = idx return (maze_metrics_dict[longest_path_idx], maze_metrics_dict[largest_nodes_expanded_idx], maze_metrics_dict[largest_fringe_size_idx], maze_metrics_dict)
def generateStatement(self, t, curFn): pos = Position.fromAny(t) f, l = self.lineInfo.translatePosition(pos) result = self.backend.sourceFilename(f) result += self.backend.lineNumber(l) if t.data == 'assignment': l, r = t.children result += self.generateAssignment(l, r, curFn) elif t.data == 'decl_var': result += "" elif t.data == 'block': result += "".join( self.generateStatement(child, curFn) for child in t.children) elif t.data == 'conditional': result += self.generateConditional( t.children[0], t.children[1], t.children[2] if len(t.children) == 3 else None, curFn) elif t.data == 'while_loop': result += self.generateWhile(t.children[0], t.children[1], curFn) elif t.data == 'for_loop': result += self.generateFor(t.children[0], t.children[1], t.children[2], t.children[3], curFn) elif t.data == 'break_statement': if len(self.breakLabel) == 0: raise SemanticError(t.line, "Not in a loop") result += self.backend.genJump(self.breakLabel[0]) elif t.data == 'continue_statement': if len(self.continueLabel) == 0: raise SemanticError(t.line, "Not in a loop") result += self.backend.genJump(self.continueLabel[0]) elif t.data == 'function_call': result += self.generateFunctionCall(Position.fromAny(t), str(t.children[0]), t.children[1:], curFn) elif t.data == 'assignment_function': call = t.children[1] result += self.generateFunctionAssignment( Position.fromAny(t.children[0]), Position.fromAny(call), t.children[0], str(call.children[0]), call.children[1:], curFn) elif t.data == 'return_statement': dest = Value.variable(Position.fromAny(t), labelname.getReturnName(curFn, False), self.nameInfo.functions[curFn].retType) result += self.generateAssignment(dest, t.children[0], curFn) + self.backend.genReturn( curFn, self.useStack) elif t.data == 'empty_return_statement': result += self.backend.genReturn(curFn, self.useStack) elif t.data == 'return_fc_statement': call = t.children[0] dest = Value.variable(Position.fromAny(t), labelname.getReturnName(curFn, False), self.nameInfo.functions[curFn].retType) callCode = self.generateFunctionAssignment(Position.fromAny(t), Position.fromAny(call), dest, str(call.children[0]), call.children[1:], curFn) retCode = self.backend.genReturn(curFn, self.useStack) result += callCode + retCode return result
# Main loop while Continue_games: # Loop Speed Limitation pygame.time.Clock().tick(30) # Displays the maze window_game.blit(bg, (0, 0)) level = Maze("Level1") level.display(window_game, hero) position_hero = level.position_start_hero() print(position_hero) window_game.blit(hero, position_hero) for event in pygame.event.get(): # We track the list of all the events received if event.type == QUIT: # If one of these events is type QUIT Continue_games = 0 # We stop the loop if event.type == KEYDOWN: if event.key == K_RIGHT: position_hero = position_hero.move(0, 30) elif event.key == K_LEFT: new_position = Hero.move(Position.left()) window_game.blit(hero, new_position) elif event.key == K_DOWN: new_position = Hero.move().down() window_game.blit(hero, new_position) elif event.key == K_UP: new_position = Hero.move().up() window_game.blit(hero, new_position) pygame.display.flip()
def generateExpression(self, t, minTempVarIndex, resultLoc, curFn): ''' Generate code to compute the expression. :param t: the expression tree :param minTempVarIndex: minimum index of a temp variable to use :param resultLoc: where to place the result. The result can be placed somewhere else (TODO). :param curFn: name of the current function. :return: the actual location of the result ''' try: if isinstance(t, Value): return self.backend.genMove(resultLoc, t, True) else: ch = t.children if len(ch) == 1: if isinstance(ch[0], Value): argCode = "" rv = ch[0] else: self.maxTempVarIndex = max(self.maxTempVarIndex, minTempVarIndex) rv, argCode = self.generateExpression( ch[0], minTempVarIndex, Value.variable( Position.fromAny(ch[0]), labelname.getTempName(minTempVarIndex, curFn)), curFn) resultLoc, myCode = self.backend.genUnary( t.data, resultLoc, rv) return resultLoc, argCode + myCode elif t.data == "type_cast": if isinstance(ch[1], Value): argCode = "" rv = ch[1] else: self.maxTempVarIndex = max(self.maxTempVarIndex, minTempVarIndex) rv, argCode = self.generateExpression( ch[1], minTempVarIndex, Value.variable( Position.fromAny(ch[1]), labelname.getTempName(minTempVarIndex, curFn)), curFn) resultLoc, myCode = self.backend.genCast( resultLoc, ch[0], rv) return resultLoc, argCode + myCode elif t.data == "arrow": ptr = ch[0] fields = ch[1:] self.maxTempVarIndex = max(self.maxTempVarIndex, minTempVarIndex) rv, argCode = self.generateExpression( ptr, minTempVarIndex, Value.variable( Position.fromAny(ptr), labelname.getTempName(minTempVarIndex, curFn)), curFn) offset, type = structure.getField(rv.getType().deref(), fields) if type.getIndirectionOffset() == 0: resultLoc, derefCode = self.backend.genDeref( resultLoc.withType(type), rv, offset) return resultLoc, argCode + derefCode elif type.getIndirectionOffset() == -1: rv, offsetCode = self.backend.genAddPointerOffset( resultLoc.withType(type), rv.withType(type), offset) return rv, argCode + offsetCode else: raise RuntimeError("Wrong indirection offset") elif t.data == "p_arrow": ptr = ch[0] fields = ch[1:] self.maxTempVarIndex = max(self.maxTempVarIndex, minTempVarIndex) rv, argCode = self.generateExpression( ptr, minTempVarIndex, resultLoc.withType(UnknownType()), curFn) offset, type = structure.getField(rv.getType().deref(), fields) if type.getIndirectionOffset() < 0: raise SemanticError(Position.fromAny(t), "Cannot get address") rv, offsetCode = self.backend.genAddPointerOffset( resultLoc.withType(PtrType(type)), rv.withType(PtrType(type)), offset) return rv, argCode + offsetCode elif len(ch) == 2: hasFirstArg = False if isinstance(ch[0], Value): rv1 = ch[0] argCode1 = "" else: self.maxTempVarIndex = max(self.maxTempVarIndex, minTempVarIndex) tmp0 = Value.variable( Position.fromAny(ch[0]), labelname.getTempName(minTempVarIndex, curFn)) rv1, argCode1 = self.generateExpression( ch[0], minTempVarIndex, tmp0, curFn) hasFirstArg = True if isinstance(ch[1], Value): rv2 = ch[1] argCode2 = "" else: indexIncrement = 1 if hasFirstArg else 0 self.maxTempVarIndex = max( self.maxTempVarIndex, minTempVarIndex + indexIncrement) tmp1 = Value.variable( Position.fromAny(ch[1]), labelname.getTempName( minTempVarIndex + indexIncrement, curFn)) rv2, argCode2 = self.generateExpression( ch[1], minTempVarIndex + indexIncrement, tmp1, curFn) if rv1.getSource().isRegister(): rv1, moveCode = self.backend.genMove( tmp0, rv1, False) argCode1 += moveCode try: resultLoc, myCode = self.backend.genBinary( t.data, resultLoc, rv1, rv2, self) except RegisterNotSupportedError as e: if e.argNumber == 0: rv1, moveCode = self.backend.genMove( tmp0, rv1, False) argCode1 += moveCode elif e.argNumber == 1: rv2, moveCode = self.backend.genMove( tmp1, rv2, False) argCode2 += moveCode else: raise resultLoc, myCode = self.backend.genBinary( t.data, resultLoc, rv1, rv2, self) return resultLoc, argCode1 + argCode2 + myCode else: raise RuntimeError("Too many children") except LookupError as e: raise SemanticError(Position.fromAny(t), str(e)) except ValueError as e: raise SemanticError(Position.fromAny(t), str(e))
def __init__(self, dim=7): self.curr_char = 'a' self.dim = dim self.reds_turn = True # Red always starts self.board = [ [ Position() for i in range(dim) ] for j in range(dim) ] self.movesTaken = []
if initialize_network: npos = init_npos else: npos = positions_per_iteration with open('../allfens.txt') as fens: while lines_read != offset: fen = fens.readline() lines_read += 1 if fen == '': break lines_read = 0 while lines_read != npos: fen = fens.readline() lines_read += 1 if fen == '': break positions.append(Position.from_fen(fen)) offset += npos if initialize_network: # initialize_weights(positions) initialize_weights_sf(npos) model.save_model() break else: n = offset m = 0 for psn in positions: n += 1 m += 1 print("============================")