示例#1
0
    def ResetGame(self):
        for option in self.UiAdvancedOptions:
            option.Delete()
        self.UiAdvancedOptions = []
        self.InAMiddleOfEating = False
        self.someoneWin = False
        self.justEat = False

        for i in range(self.NumberOfCellsInAxis):
            for j in range(self.NumberOfCellsInAxis):
                if (self.BoardState[i][j] is not None):
                    self.BoardState[i][j].Delete()
                    self.BoardState[i][j] = None
                if ((i + j) % 2 == 0):
                    if (i < 3):
                        self.BoardState[i][j] = Solider(
                            self.BoardUi, "black", Position(i, j), False,
                            self.OnSoliderPressed)
                    elif (i > 4):
                        self.BoardState[i][j] = Solider(
                            self.BoardUi, "white", Position(i, j), False,
                            self.OnSoliderPressed)
                    else:
                        self.BoardState[i][j] = None
                else:
                    self.BoardState[i][j] = None

        self.playerTurn = "white"
        self.whitePlayersCount = 12
        self.blackPlayersCount = 12

        self.gameMenu.UpdateBlackSoliderCounter(self.blackPlayersCount)
        self.gameMenu.UpdateWhiteSoliderCounter(self.whitePlayersCount)
        self.gameMenu.UpdatePlayerTurn(self.playerTurn)
示例#2
0
    def getPossibleActions(self, state):

        r = state.m_agentPos.row
        c = state.m_agentPos.col
        action = None

        l = []

        oponent_color = -1
        if self.m_color == 0:  # white pawn
            oponent_color = 1
        elif self.m_color == 1:  # black pawn
            oponent_color = 1

        if state.m_board[r + 1][c] == Utils.empty:  # standard pawn move
            l.append(Action(state.m_agentPos, Position(r + 1, c)))
        if r == 1 and (state.m_board[r + 2][c]
                       == Utils.empty):  # starting pawn move
            l.append(Action(state.m_agentPos, Position(r + 2, c)))
        if c > 0 and (state.m_board[r + 1][c - 1] != Utils.empty) and (
                Utils.getColorPiece(
                    state.m_board[r + 1][c - 1]) == oponent_color):  # capture
            l.append(Action(state.m_agentPos, Position(r + 1, c - 1)))
        if c < (state.m_boardSize - 1) and (
                state.m_board[r + 1][c + 1] !=
                Utils.empty) and (Utils.getColorPiece(
                    state.m_board[r + 1][c + 1]) == oponent_color):  # capture
            l.append(Action(state.m_agentPos, Position(r + 1, c + 1)))

        return l
示例#3
0
	def estIntacte(self,Position): 
		# Return True si la case a un bateau et n'a pas déjà été tiré
		res = False
		for PositionCur in self.positionsOcuppees:
			if (Position.getX() == PositionCur.getX() and Position.getY() == PositionCur.getY() and not(PositionCur.get_Tire())):
				res = True
		return res 
    def positions(self, tank, world):
        positions = []

        for i in range(self.width - 1):
            positions.append(
                Position(world.width * (1 + i) / (self.width + 1),
                         world.height - self.distance,
                         "LOW BORDER %s/%s" % (i + 1, self.width)))

            positions.append(
                Position(world.width * (1 + i) / (self.width + 1),
                         self.distance,
                         "TOP BORDER %s/%s" % (i + 1, self.width)))

        for j in range(self.height - 1):
            positions.append(
                Position(world.width - self.distance,
                         world.height * (1 + j) / (self.height + 1),
                         "RIGHT BORDER %s/%s" % (j + 1, self.height)))

            positions.append(
                Position(self.distance,
                         world.height * (1 + j) / (self.height + 1),
                         "LEFT BORDER %s/%s" % (j + 1, self.height)))

        return positions
    def find_center(start, end):
        center = Position()
        center.x = (start.x + end.x) / 2.0
        center.y = (start.y + end.y) / 2.0
        center.z = (start.z + end.z) / 2.0

        return center
示例#6
0
    def __init__(self,tweets, blacklist= []) :
        self.tweets=sorted(tweets,key=lambda tweet : tweet.time)
        
        self.eventStartingTime=self.tweets[0].time
        self.eventEndingTime=self.tweets[0].time
        self.eventMedianTime=self.tweets[len(tweets)/2].time
        self.estimatedEventDuration=self.tweets[len(tweets)/10].delay(self.tweets[(9*len(tweets))/10])

        userIdSet=set()
	#----- Calcul du centre (latitude,longitude) -----#
        self.eventCenter=Position(0,0)
        for tweet in tweets :
            userIdSet.add(tweet.userId)
            self.eventCenter.latitude+=tweet.position.latitude
            self.eventCenter.longitude+=tweet.position.longitude
            if (tweet.time<self.eventStartingTime) :
                self.eventStartingTime=tweet.time
            elif (tweet.time>self.eventEndingTime) :
                self.eventEndingTime=tweet.time
        self.eventCenter.latitude/=len(tweets)
        self.eventCenter.longitude/=len(tweets)
		
	#---- Calcul de la distance angulaire maximale -----#
        self.eventRadius=self.eventCenter.distance(tweets[0].position)
        for tweet in tweets :
            distance=self.eventCenter.distance(tweet.position)
            if (distance>self.eventRadius) :
                self.eventRadius=distance
                
        self.userNumber=len(userIdSet)        
        self.importantHashtags=self.getImportantHashtags(20, blacklist)
        self.hashtags=self.getImportantHashtags(20, blacklist, False)
示例#7
0
    def __init__(self, char_id, name, user_id, experience, lvl, weapon_id, armor_id, trait_id,
                 exp_gain_time, x, y, trait_bonus, alive, connection, weapon=None, armor=None, trait=None):
        self.__char_id = char_id

        self.cache[self.__char_id] = self

        self.name = name
        self.user_id = user_id
        self.experience = experience
        self.lvl = lvl
        if exp_gain_time.tzinfo is None:
            exp_gain_time = utc.localize(exp_gain_time)
        self.exp_gain_time = exp_gain_time

        self.weapon_id = weapon_id
        self._weapon = weapon

        self.armor_id = armor_id
        self._armor = armor

        self.trait_id = Trait.Traits(trait_id)  # This is an enum
        self._trait = trait
        self.trait_bonus = trait_bonus

        self._specials = None

        self.position = Position(x, y)
        self.alive = alive

        self.connection = connection
示例#8
0
    def initiate(self):
        i = 0
        for player in self.players:
            i += 1
            print("jugador: ", i)
            posX = 0
            posY = 0
            for index in range(3):
                #tam = int(input("Tamaño del barco  "))-1
                tam = index + 1
                #posX = int(input("Posicion X del barco  "))
                posX += 2
                #posY = int(input("Posicion Y del barco  "))
                posY = posX
                start = Position(posX, posY)
                #dir = input("Direccion del barco [U,R,D,L]  ")
                dir = "D"
                if (dir == "U"):  #Up
                    posY -= tam
                elif (dir == "D"):  #Down
                    posY += tam
                elif (dir == "R"):  #Right
                    posX += tam
                elif (dir == "L"):  #Left
                    posX -= tam
                end = Position(posX, posY)

                player.hud.boatsBoard.pushNewBoat(Boat(start, end))
                player.hud.mostrarBB()
示例#9
0
    def Move(self):
        """
        input:
            none
        output:
            none
            
        Description:
            Moves the snake's head one unit in the direction of travel, as def-
            ined by self.direction. The rest of the snake's body will move to
            where the previous segment used to be.
        
        """
        grow = self.segmentsToGrow > 0

        if (grow):
            self.segmentsToGrow -= 1
            lastPosition = Position(
                self.snakeSegments[-1].position.coordinates)

        oldSnakeSegments = [
            Snake_Segment(Position(snakeSeg.position.coordinates[:]))
            for snakeSeg in self.snakeSegments
        ]
        for index, segment in enumerate(self.snakeSegments[1:]):
            self.snakeSegments[index +
                               1].position.coordinates = oldSnakeSegments[
                                   index].position.coordinates[:]

        if (grow):
            self.snakeSegments.append(Snake_Segment(lastPosition))

        self.snakeSegments[
            0].position = self.snakeSegments[0].position + self.direction
示例#10
0
    def testPositionInSet(self):
        mySet = set([Position.zero(), Position(0, 1)])
        self.assertEqual(len(mySet), 2)
        mySet.add(Position.zero())
        self.assertEqual(len(mySet), 2)

        self.assertEqual(Position.zero() in mySet, True)
示例#11
0
    def GetAdvancePositionForSpecificDirection(self, solider,
                                               verticalDirection,
                                               horizontalDirection):
        try:
            if (solider.Position.Row + verticalDirection < 0
                    or solider.Position.Column + horizontalDirection < 0):
                return None
            if (self.BoardState[solider.Position.Row + verticalDirection][
                    solider.Position.Column + horizontalDirection] == None):
                return Position(solider.Position.Row + verticalDirection,
                                solider.Position.Column + horizontalDirection)

            if (solider.Position.Row + 2 * verticalDirection < 0
                    or solider.Position.Column + 2 * horizontalDirection < 0):
                return None

            if (solider.color !=
                    self.BoardState[solider.Position.Row + verticalDirection][
                        solider.Position.Column + horizontalDirection].Color):
                if (self.BoardState[solider.Position.Row + verticalDirection *
                                    2][solider.Position.Column +
                                       2 * horizontalDirection] == None):
                    return Position(
                        solider.Position.Row + verticalDirection * 2,
                        solider.Position.Column + 2 * horizontalDirection)
        except IndexError:
            return None
 def getShips(agent):
     carrier = Ship("Carrier", [1, 1, 1, 1, 1],
                    100,
                    Position(2, 3),
                    Ship.ORIENTATION_90_DEG,
                    immovable=True)
     battleship = Ship("Battleship", [1, 1, 1, 1],
                       80,
                       Position(0, 0),
                       Ship.ORIENTATION_0_DEG,
                       immovable=True)
     cruiser = Ship("Cruiser", [1, 1, 1],
                    60,
                    Position(6, 2),
                    Ship.ORIENTATION_180_DEG,
                    immovable=True)
     submarine = Ship("Submarine", [1, 1, 1],
                      60,
                      Position(8, 1),
                      Ship.ORIENTATION_90_DEG,
                      immovable=True)
     destroyer = Ship("Destroyer", [1, 1],
                      40,
                      Position(6, 6),
                      Ship.ORIENTATION_0_DEG,
                      immovable=True)
     return [carrier, battleship, cruiser, submarine, destroyer]
示例#13
0
 def test_update(self):
     pos = Position(toVector(500., 1100., 250.))
     vel = Velocity(toVector(10., 20., 5.))
     pos.update(vel, 1.)
     self.assertEqual(510., pos.values[0])
     self.assertEqual(1120., pos.values[1])
     self.assertEqual(255., pos.values[2])
示例#14
0
 def __init__(self, maze_dim = None, file_path = None):
     if file_path is not None:
         with open(file_path, 'rb') as f_in:
             # First line should be an integer with the maze dimensions
             self.dim = int(f_in.next())
     else:
         self.dim = maze_dim
     self.cells = {}
     for x in range(self.dim):
         for y in range(self.dim):
             pos = Position(x, y)
             cell = MazeCell(pos)
             self.cells[pos] = cell
             # West wall
             if pos.x == 0:
                 cell.walls[w] = Wall(True)
             else:
                 cell.walls[w] = self.cells[pos.add(w)].walls[e]
             # East wall
             if pos.x == self.dim-1 or (pos.x == 0 and pos.y == 0):
                 cell.walls[e] = Wall(True)
             else:
                 cell.walls[e] = Wall(None)
             # South wall
             if pos.y == 0:
                 cell.walls[s] = Wall(True)
             else:
                 cell.walls[s] = self.cells[pos.add(s)].walls[n]
             # North wall
             if pos.y == self.dim-1:
                 cell.walls[n] = Wall(True)
             else:
                 cell.walls[n] = Wall(None)
     if file_path is not None:
         self.read_from_file(file_path)
示例#15
0
    def __init__(self, direction: float, port: int, ip: str ='keuper-labs.org'):
        self.measurements = None
        self.IP = ip
        self.PORT = port
        zumi_no = int(int(self.PORT) - 9000)

        # Connecting via RPC
        rpyc.core.protocol.DEFAULT_CONFIG['allow_pickle'] = True
        conn = rpyc.connect(ip, port)
        self.zumi = conn.root

        self.position = Position(zumi_no, direction)

        # Creating directory for zumi data
        self.directory = "Zumi_{}".format(port - 9000)
        try:
            os.makedirs(self.directory)
        except FileExistsError:
            # directory already exists
            pass

        # Creating directory for top-cam data
        self.directory_two = "{}/Data_from_{}".format(self.directory, datetime.now().strftime("%m-%d-%Y"))
        try:
            os.makedirs(self.directory_two)
        except FileExistsError:
            # directory already exists
            pass
        self.csv_name = "{}/IR_from_{}.csv".format(self.directory_two, datetime.now().strftime("%H-%M-%S"))
        # self.csv_name = "{}/IR_from_{}.csv".format(self.directory,datetime.now().strftime("%H-%M-%S"))
        print("Zumi Initialized")
示例#16
0
    def __init__(self, tweets):
        self.tweets = sorted(tweets, key=lambda tweet: tweet.time)

        self.eventStartingTime = self.tweets[0].time
        self.eventEndingTime = self.tweets[0].time
        self.eventMedianTime = self.tweets[len(tweets) / 2].time
        self.estimatedEventDuration = self.tweets[len(tweets) / 10].delay(
            self.tweets[(9 * len(tweets)) / 10])

        userIdSet = set()
        self.eventCenter = Position(0, 0)
        for tweet in tweets:
            userIdSet.add(tweet.userId)
            self.eventCenter.latitude += tweet.position.latitude
            self.eventCenter.longitude += tweet.position.longitude
            if (tweet.time < self.eventStartingTime):
                self.eventStartingTime = tweet.time
            elif (tweet.time > self.eventEndingTime):
                self.eventEndingTime = tweet.time
        self.eventCenter.latitude /= len(tweets)
        self.eventCenter.longitude /= len(tweets)
        self.eventRadius = self.eventCenter.distance(tweets[0].position)
        for tweet in tweets:
            distance = self.eventCenter.distance(tweet.position)
            if (distance > self.eventRadius):
                self.eventRadius = distance

        self.userNumber = len(userIdSet)

        self.importantHashtags = self.getImportantHashtags()
示例#17
0
def main():
    #Construct nodes
    start_a = Position(2, 3, 4)
    end_a = Position(0, 1, 2)
    length_a = 4
    width_a = 6
    height_a = 2
    node_a = Node(start_a, end_a, length_a, width_a, height_a)

    start_b = Position(0, 0, 1)
    end_b = Position(0, 1, 1)
    length_b = 3
    width_b = 2
    height_b = 8
    node_b = Node(start_b, end_b, length_b, width_b, height_b)

    #Check for static collision
    static_hit = CollisionDetection.check_for_collision(node_a, node_b)
    print('Static hit: ' + str(static_hit))

    #Check for linear velocity collision
    time_step = 0.2
    linear_hit = CollisionDetection.check_for_collision_velocity(
        node_a, node_b, time_step)
    print('Linear hit with time step (' + str(time_step) + ' seconds): ' +
          str(linear_hit))

    return
示例#18
0
class GameEngine:
    """This is the Game Engine"""
    """Create our ball (i.e, the ConcreteSubject)"""
    ball = Football()
    """Create few players (i.e, ConcreteObservers)"""
    Owen = Player(ball, "Owen")
    Ronaldo = Player(ball, "Ronaldp")
    Rivaldo = Player(ball, "Rivaldo")
    """Create few referees (i.e, ConcreteObservers)"""
    Mike = Referee(ball, "Mike")
    John = Referee(ball, "John")
    """Attach them with the ball"""
    ball.AttachObserver(Owen)
    ball.AttachObserver(Ronaldo)
    ball.AttachObserver(Rivaldo)
    ball.AttachObserver(Mike)
    ball.AttachObserver(John)
    print " After attaching the observers..."
    print "Update the position of the ball."
    print "At this point, all the observers should be notified"

    ball.SetBallPosition(Position())
    """Remove some observers"""
    ball.DetachObserver(Owen)
    ball.DetachObserver(John)
    print " After detaching Owen and John..."
    print "Updating the position of ball again"
    print "At this point, all the observers should be notified"

    ball.SetBallPosition(Position(10, 10, 30))
    print "Press any key to continue.."
    raw_input()
    def open_position(self, action, currency, open_value, currency_amount):
        position_id = self.get_id()

        # Check if position can be created
        if action == "buy":
            if open_value > self.balance:
                print("buy value exceeds balance")
            else:
                currency_amount = self.get_currency_amount_from_value(
                    currency, open_value)
                self.positions[position_id] = Position(action, currency,
                                                       open_value,
                                                       currency_amount,
                                                       self.client)
                self.balance -= open_value
                self.currencies[currency] += currency_amount
        if action == "sell":
            if currency_amount > self.currencies[currency]:
                print("sell value exceeds {} balance".format(currency))
            else:
                open_value = self.get_value_from_currency_amount(
                    currency, currency_amount)
                self.positions[position_id] = Position(action, currency,
                                                       open_value,
                                                       currency_amount,
                                                       self.client)
                self.currencies[currency] -= currency_amount
                self.balance += open_value
示例#20
0
    def can_attack(self, from_pos: Position, to_pos: Position):
        if not from_pos.is_in_boundary(self.SIZE) or not to_pos.is_in_boundary(
                self.SIZE):
            return False

        from_piece: Piece = self.board[from_pos.x][from_pos.y]
        if from_piece is None:
            return False

        to_piece: Piece = self.board[to_pos.x][to_pos.y]
        if to_piece is None:
            return False

        if from_piece.player == to_piece.player:
            return False

        # should beck special moves also (not per piece only)
        if to_piece.id == 'K':
            available_moves = self.available_piece_moves_c(from_piece,
                                                           attack=True)
        else:
            available_moves = self.available_piece_moves(from_piece,
                                                         attack=True)

        if to_pos in available_moves:
            return True

        return False
示例#21
0
    def getNeighboringPositions(self):
        result = []
        positions = self.world.getNeighboringPositions(self.position)
        for pos in positions:
            Org = self.world.getOrganismFromPosition(pos)
            print(Org)
            if Org.__class__.__name__ == 'Wolf':
                antelope_next_pos_x = self.position.x + (self.position.x -
                                                         Org.position.x) * 2
                antelope_next_pos_y = self.position.y + (self.position.y -
                                                         Org.position.y) * 2
                if antelope_next_pos_x >= 0 and antelope_next_pos_x < self.world.worldX and antelope_next_pos_y >= 0 and antelope_next_pos_y < self.world.worldY:
                    result.append(
                        Position(xPosition=antelope_next_pos_x,
                                 yPosition=antelope_next_pos_y))
                else:
                    print("Atakuję ")
                    antelope_next_pos_x = Org.position.x
                    antelope_next_pos_y = Org.position.y
                    result.append(
                        Position(xPosition=antelope_next_pos_x,
                                 yPosition=antelope_next_pos_y))

                return result

        return self.world.filterPositionsWithoutAnimals(
            self.world.getNeighboringPositions(self.position))
示例#22
0
 def __init__(self, _pos="A0", _player=0, _inGoal=False, _outHome=False):
     self.pos = Position(_pos)
     self.x = self.pos.getX()
     self.y = self.pos.getY()
     self.occupyplayer = _player  # integer
     self.inGoal = _inGoal  # boolean
     self.outHome = _outHome  # boolean
示例#23
0
 def print_city_with_cars(self, car_position_list):
     """
     Prints City Grid, adding cars in given positions
     """
     g_str = ""
     g_str += "".ljust(3)
     for i in range(len(self.grid)):
         g_str += str(i).ljust(4)
     g_str += "\n"
     for i in range(len(self.grid)):
         g_str += str(i).ljust(4)
         for j in range(len(self.grid[0])):
             if Position(j, i) in car_position_list:
                 g_str += (
                     "c" +
                     str(car_position_list.index(Position(j, i)))).ljust(4)
             elif (j + 1, i + 1) in self.building_positions:
                 g_str += str(self.num_free_park_spaces(j + 1,
                                                        i + 1)).ljust(4)
             elif self.grid[i][j] == LaneType.Building:
                 g_str += str(self.grid[i][j]).ljust(
                     4, str(self.grid[i][j]))
             else:
                 g_str += str(self.grid[i][j]).ljust(4)
         g_str += "\n"
     g_str = g_str[:len(g_str) - 1]
     return g_str
    def use_lizard(self, action, game_map, player_info):

        max_ = speed_bracket[player_info.damage]
        if action == Commands.USE_LIZARD:

            if not itemize_command(action) in player_info.power_ups:

                return {
                    "player_info": player_info,
                    "game_map": game_map,
                    "progression": False,
                    "additional_score": -1000
                }

            y = player_info.position.y
            x = player_info.position.x + player_info.speed
            progress = True  # goes deeper into the game tree?
            if not x in game_map[y].keys():
                x = [i for i in game_map[y].keys()][-1]
                progress = False
            a = AStar()
            path = a.forward(player_info.position, Position(y, x), game_map)

            p_speed = 0  # plaussible speeds
            if not player_info.boosting:
                if "BOOST" in player_info.power_ups:
                    p_speed = max_ - player_info.speed
            else:
                n_speed = max_ if player_info.boosting else speeds[
                    player_info.speed].right
                p_speed = n_speed if n_speed else player_info.speed

            score = 0

            if True:

                score += 4
                player_info.power_ups.remove(itemize_command(action))

            score -= abs((player_info.position.x + player_info.speed) -
                         (player_info.position.x + p_speed))
            score -= abs((player_info.position.x + player_info.speed) -
                         [i for i in game_map[y].keys()][-1])

            # walking the paths to collect damages/speed-deduction and points
            path_walk = self.walk_path(path, game_map, is_lizard=True)
            score += len(
                path_walk["powerups"]
            ) * 4  # <-- actually using of powerups will justify this more
            score += self.compute_wall_damages(path_walk["obstacles"],
                                               player_info)
            player_info.power_ups += path_walk["powerups"]

            if progress: player_info.position = Position(y, x)
            return {
                "player_info": player_info,
                "game_map": game_map,
                "progression": progress,
                "additional_score": score
            }
示例#25
0
	def aUnBateau(self,Position):
		# Renvoie True si la un bateau se trouve à une position donnée
		res = False
		for PositionCur in self.positionsOcuppees:
			if (Position.getX() == PositionCur.getX() and Position.getY() == PositionCur.getY()):
				res = True
		return res
示例#26
0
	def consequences(self, atackingOrganism):
		result = []
		if self.power > atackingOrganism.power:
			result.append(Action(ActionEnum.A_REMOVE, Position(xPosition=-1, yPosition=-1), 0, atackingOrganism))
		else:
			result.append(Action(ActionEnum.A_REMOVE, Position(xPosition=-1, yPosition=-1), 0, self))
		return result
示例#27
0
class Vehicle():
    def __init__(self, row, col):
        self.position = Position(row, col)
        self.colected_food = 0
        self.solution = None

    '''
    direction: indica a direcao a qual o veiculo devera se mover (o valor deve ser uma das constantes em OperationTypes.py) // 'up' | 'right' | ... 
    '''

    def move(self, direction, limit=None):
        if direction == OperationTypes.MOVE_UP:
            new_position = self.position.move_up()
            if new_position is not None:
                self.position = new_position
        elif direction == OperationTypes.MOVE_RIGHT:
            new_position = self.position.move_right(limit)
            if new_position is not None:
                self.position = new_position
        elif direction == OperationTypes.MOVE_DOWN:
            new_position = self.position.move_down(limit)
            if new_position is not None:
                self.position = new_position
        elif direction == OperationTypes.MOVE_LEFT:
            new_position = self.position.move_left()
            if new_position is not None:
                self.position = new_position

    '''
    matrix: corresponde apenas a uma matriz de objetos do tipo Cell
    search_type: indica o tipo de busca a ser realizada // 'DFS' | 'BFS' | ...
    '''

    def search_food(self, matrix, search_type):
        cell_food = Cell()
        cell_food.set_type(CellTypes.TYPE_FOOD, CellTypes.FOOD_COLOR)

        self.solution = search(self.position, cell_food, matrix, search_type)

        return self.solution

    def run_solution(self, row_limit, col_limit, env):
        if self.solution is not None:
            operations = self.get_operations(self.solution, [])
            for op in operations:
                if op == OperationTypes.MOVE_LEFT or op == OperationTypes.MOVE_UP:
                    self.move(op)
                elif op == OperationTypes.MOVE_RIGHT:
                    self.move(op, col_limit)
                elif op == OperationTypes.MOVE_DOWN:
                    self.move(op, row_limit)
                env.update_vehicle_position(self.position)
            self.colected_food += 1

    def get_operations(self, node, operations):
        if node.previousNode is not None:
            operations.insert(0, node.operation)
            return self.get_operations(node.previousNode, operations)
        return operations
示例#28
0
    def test_turn_right_from_west(self):
        position = Position(direction=Direction.west)

        position.turn(Turn.right)

        self.assertEqual(position.x_coord, 0)
        self.assertEqual(position.y_coord, 0)
        self.assertEqual(position.direction, Direction.north)
示例#29
0
    def test_go_forwards_3(self):
        position = Position()

        position.walk_forward(3)

        self.assertEqual(position.x_coord, 0)
        self.assertEqual(position.y_coord, 3)
        self.assertEqual(position.direction, Direction.north)
示例#30
0
    def test_go_forwards_4_from_east(self):
        position = Position(Direction.east)

        position.walk_forward(4)

        self.assertEqual(position.x_coord, 4)
        self.assertEqual(position.y_coord, 0)
        self.assertEqual(position.direction, Direction.east)
示例#31
0
    def test_turn_left_from_west(self):
        position = Position(direction=Direction.west)

        position.turn(Turn.left)

        self.assertEqual(position.x_coord, 0)
        self.assertEqual(position.y_coord, 0)
        self.assertEqual(position.direction, Direction.south)
 def kill_neighbors(self):
     position = self.position
     for dx in range(-1, 1):
         for dy in range(-1, 1):
             if not (dx == 0 and dx == dy):
                 killing_position = Position(position.x + dx, position.y + dy)
                 if killing_position.is_valid():
                     self.kill_if_animal(killing_position)
示例#33
0
    def test_go_forwards_2_from_south(self):
        position = Position(Direction.south)

        position.walk_forward(2)

        self.assertEqual(position.x_coord, 0)
        self.assertEqual(position.y_coord, -2)
        self.assertEqual(position.direction, Direction.south)
示例#34
0
文件: Client.py 项目: EdlinLink/Go
	def send_station(self, x, y):
		if self.Name == self.state.Turn:	

			input = str(x)+","+str(y)
			pos = Position(input, self.Name)

			if is_valid(self.state.Board, pos) == False:
				print "[Position Invalid, Enter Again]"
			else:
				self.sock.send(pos.to_str())
class Event :
    def __init__(self,tweets) :
        self.tweets=sorted(tweets,key=lambda tweet : tweet.time)
        
        self.eventStartingTime=self.tweets[0].time
        self.eventEndingTime=self.tweets[0].time
        self.eventMedianTime=self.tweets[len(tweets)/2].time
        self.estimatedEventDuration=self.tweets[len(tweets)/10].delay(self.tweets[(9*len(tweets))/10])

        userIdSet=set()
        self.eventCenter=Position(0,0)
        for tweet in tweets :
            userIdSet.add(tweet.userId)
            self.eventCenter.latitude+=tweet.position.latitude
            self.eventCenter.longitude+=tweet.position.longitude
            if (tweet.time<self.eventStartingTime) :
                self.eventStartingTime=tweet.time
            elif (tweet.time>self.eventEndingTime) :
                self.eventEndingTime=tweet.time
        self.eventCenter.latitude/=len(tweets)
        self.eventCenter.longitude/=len(tweets)
        self.eventRadius=self.eventCenter.distance(tweets[0].position)
        for tweet in tweets :
            distance=self.eventCenter.distance(tweet.position)
            if (distance>self.eventRadius) :
                self.eventRadius=distance
                
        self.userNumber=len(userIdSet)
        
        self.importantHashtags=self.getImportantHashtags()

    def getImportantHashtags(self, topk=10) :
        dictHashtags={}
        for t in self.tweets :
            for h in t.hashtags :
                try : dictHashtags[h.lower()]+=1
                except KeyError : dictHashtags[h.lower()]=1
        importantHashtags=sorted(list(dictHashtags), key=lambda element : dictHashtags[element], reverse=True)[0:min(topk,len(dictHashtags))]
        return importantHashtags

    #---------------- Visualize -----------------------------------------------------------------------#
    def __str__(self) :
        NUM_DIGIT=10**2
        SEPARATOR="\t|"
        S="|"+SEPARATOR.join([str(self.eventMedianTime),
                              str(int(self.estimatedEventDuration)),
                              str(float(int(NUM_DIGIT*self.eventCenter.latitude))/NUM_DIGIT),
                              str(float(int(NUM_DIGIT*self.eventCenter.longitude))/NUM_DIGIT),
                              str(float(int(NUM_DIGIT*self.eventRadius))/NUM_DIGIT),
                              str(self.userNumber),
                              str(len(self.tweets)),
                              ",".join(self.importantHashtags)])+SEPARATOR
        return S.encode("utf-8")
示例#36
0
 def from_string( string ):
     components = string.replace("[","").replace("]","").replace(" ","").split(";")
     state = []
     for position in components:
         if position is not "":
             state.append( Position.from_string( position ) )
     return Pattern( state )
    def __init__(self,tweets) :
        self.tweets=sorted(tweets,key=lambda tweet : tweet.time)
        
        self.eventStartingTime=self.tweets[0].time
        self.eventEndingTime=self.tweets[0].time
        self.eventMedianTime=self.tweets[len(tweets)/2].time
        self.estimatedEventDuration=self.tweets[len(tweets)/10].delay(self.tweets[(9*len(tweets))/10])

        userIdSet=set()
        self.eventCenter=Position(0,0)
        for tweet in tweets :
            userIdSet.add(tweet.userId)
            self.eventCenter.latitude+=tweet.position.latitude
            self.eventCenter.longitude+=tweet.position.longitude
            if (tweet.time<self.eventStartingTime) :
                self.eventStartingTime=tweet.time
            elif (tweet.time>self.eventEndingTime) :
                self.eventEndingTime=tweet.time
        self.eventCenter.latitude/=len(tweets)
        self.eventCenter.longitude/=len(tweets)
        self.eventRadius=self.eventCenter.distance(tweets[0].position)
        for tweet in tweets :
            distance=self.eventCenter.distance(tweet.position)
            if (distance>self.eventRadius) :
                self.eventRadius=distance
                
        self.userNumber=len(userIdSet)
        
        self.importantHashtags=self.getImportantHashtags()
 def __init__(self, maze_dim, dump_mazes=False):
     self.location = Position(0, 0)
     self.heading = Direction(0)
     self.maze_map = MazeMap(maze_dim)
     self.timestep = 0
     self.run_number = 0
     self.found_goal = False
     self.dump_mazes = dump_mazes
     self.planner = Planner(self.maze_map)  # planner needs to be set by sub-class
示例#39
0
def placerBateaux(i=0):
	# i = BateauCourant
	

	while (Partie.get_JoueurActif().get_Bateaux().get_NombreBateauxNonPlaces() > 0):

		header()
		print "===> Placer vos bateaux <====\n"
		print Partie.get_JoueurActif().get_NomJoueur()+" >> "+str(Partie.get_JoueurActif().get_Bateaux().get_NombreBateauxNonPlaces())+ " bateaux à placer."
		print "Bateau selectionné: \nTaille:"+str(Partie.get_JoueurActif().get_Bateaux().get_Bateau(i).get_taille())+"\n"
		print("Entrez une coordonnee: ")
		X = int(raw_input("X: "))
		Y = int(raw_input("Y: "))
		LastPos=Position(X,Y,Partie.get_JoueurActif().get_Bateaux().get_Bateau(i))
		try:
			Partie.get_JoueurActif().get_Grille().marquerPosition(LastPos)
			k=1
			while(k < Partie.get_JoueurActif().get_Bateaux().get_Bateau(i).get_taille()):
			
				header()
				print "===> Placer vos bateaux <====\n"
				print Partie.get_JoueurActif().get_NomJoueur()+" >> "+str(Partie.get_JoueurActif().get_Bateaux().get_NombreBateauxNonPlaces())+ " bateaux à placer."
				print "Bateau selectionné: \nTaille:"+str(Partie.get_JoueurActif().get_Bateaux().get_Bateau(i).get_taille())+"\n"
				print("Entrez une coordonnee: ")
				X = int(raw_input("X: "))
				Y = int(raw_input("Y: "))
				pos=Position(X,Y,Partie.get_JoueurActif().get_Bateaux().get_Bateau(i))
				if (pos.est_AdjacenteY(LastPos) or pos.est_AdjacenteX(LastPos)):
					try:
						Partie.get_JoueurActif().get_Grille().marquerPosition(pos)
						k = k+1

						LastPos = pos
					except:
						raw_input("Case occuppée et/ou hors grille !")
				else:
					raw_input("Mauvaise case, non adjacente.")
			# k == taille(Bateau)
			Partie.get_JoueurActif().get_Bateaux().get_Bateau(i).set_estPlace()
			i=i+1
			raw_input("Bateau place, Bateau suivant")
		except:
			raw_input("Case occuppée et/ou hors grille !")
			placerBateaux(i)
 def reset(self):
     """
     Move the robot back to 0,0 and facing north. Also changes the run_number to 1. Call this when you are ready to
     start the second run.
     :return: Returns the reset string for convenience.
     """
     self.location = Position(0, 0)
     self.heading = Direction(0)
     self.run_number = 1
     print "Number of moves in first run: {}".format(self.timestep)
     print "Exploration efficiency: {}".format(self.get_exploration_efficiency())
     self.planner.replan(self.location, self.heading)
     return "Reset", "Reset"
示例#41
0
  def runStrategy(self, ticker, merged):
    print '\nRunning strategy on ' + ticker + '..'  
    time.sleep(2)

    
    # First, do analytics to figure out how to execute the strategy.
    # Return lagged correlations and (10dayMA) of those lagged correlations.
    analyticsObj = Analytics()
    s_p_r_ma = analyticsObj.getAnalytics(ticker, merged)
    
    # Second, determine the position.
    positionObj = Position()
    s_p_r_ma_pos = positionObj.getPosition(ticker, s_p_r_ma)
    
    # Third, run the strategy!
    # Return a performance list (with dates?)
    strategyObj = RunStrategy()
    strategyResults = strategyObj.getResults(ticker, s_p_r_ma_pos)
    
    # Fourth, determine the metrics.
    metricsObj = StrategyMetrics()
    metrics = metricsObj.getStrategyMetrics(ticker, strategyResults, s_p_r_ma_pos)
    return metrics
示例#42
0
	def quelBateau(self,Position):
		# Si Position.aUnBateau()
		for PositionCur in self.positionsOcuppees:
			if (Position.getX() == PositionCur.getX() and Position.getY() == PositionCur.getY()):
				res = PositionCur.getBateau()
		return res
示例#43
0
 def __init__(self,poiId,longitude,latitude,visits=[]) :
     self.id=poiId
     Position.__init__(self,longitude,latitude)
     self.visits=visits[:]
     self.accumulatedStayTime=sum([visit.duration() for visit in self.visits])
示例#44
0
	def bateauEnVue(self,Position):
		res = False
		for Pos in self.positionsOcuppees:
			if (Position.getX() == Pos.getX() or Position.getY() == Pos.getY()):
				res = True
		return res
示例#45
0
 def move(self, color, movetext):
     m = list(movetext)
     
     logging.debug("starting move with len(m): " + str(len(m)))
     
     # Nbxd2(+|#) -- kNight in column B takes piece in d2
     
     destination = None
     x = None
     y = None
     for i in range(len(m)-1, -1, -1):
         logging.debug("i=" + str(i) + ", m[i]=" + m[i])
         
         if m[i] == "x" or m[i] == "+" or m[i] == "#":
             skip = True
         else:
             if destination is not None:
                 x = None
                 y = None
             
             if m[i] not in ["K", "Q", "B", "N", "R"]:
                 if m[i].isdigit():
                     y = m[i]
                 else:
                     if m[i] == "a":
                         x = 1
                     elif m[i] == "b":
                         x = 2
                     elif m[i] == "c":
                         x = 3
                     elif m[i] == "d":
                         x = 4
                     elif m[i] == "e":
                         x = 5
                     elif m[i] == "f":
                         x = 6
                     elif m[i] == "g":
                         x = 7
                     elif m[i] == "h":
                         x = 8
                 if destination is None and x is not None and y is not None:
                     destination = int(y) * 8 - int(x)
                 else:
                     if x is not None and y is not None:
                         origin = int(y) * 8 - int(x)
                     else:
                         origin = m[i]
             else:
                 if m[i] == "K" and color == "W":
                     piece = whiteking
                 elif m[i] == "Q" and color == "W":
                     piece = whitequeen
                 elif m[i] == "B" and color == "W":
                     piece = whitebishop
                 elif m[i] == "N" and color == "W":
                     piece = whiteknight
                 elif m[i] == "R" and color == "W":
                     piece = whiterook
                 elif color == "W":
                     piece = whitepawn
                 elif m[i] == "K" and color == "B":
                     piece = blackking
                 elif m[i] == "Q" and color == "B":
                     piece = blackqueen
                 elif m[i] == "B" and color == "B":
                     piece = blackbishop
                 elif m[i] == "N" and color == "B":
                     piece = blackknight
                 elif m[i] == "R" and color == "B":
                     piece = blackrook
                 else:
                     piece = blackpawn
     
     if not origin.isdigit():
         pos = Position(self.moves)
         origin = pos.find_origin(piece, destination, origin)
         
     
     # TODO: castling, king-side and queen-side
     
     # if origin is non specific (None or just a column), determine origin square
     
     # modify BitVector to move piece to new square
         # use concat (+) with two splices to move bits around - bv1[6:9]  = bv2[0:3]
     
     return piece, destination, origin
class RobotController(object):
    """
    This is the base class for all robot controllers. You must override next_move and initialize self.planner in
    a sub-class.
    """
    def __init__(self, maze_dim, dump_mazes=False):
        self.location = Position(0, 0)
        self.heading = Direction(0)
        self.maze_map = MazeMap(maze_dim)
        self.timestep = 0
        self.run_number = 0
        self.found_goal = False
        self.dump_mazes = dump_mazes
        self.planner = Planner(self.maze_map)  # planner needs to be set by sub-class

    def next_move(self, sensors):
        """
        This is the main method to implement for a controller. Make sure that the move the controller returns is a valid
        move (it doesn't try to go through walls). If it does, the location and heading class members will be incorrect.
        :param sensors: The distance in squares to the next wall for the left, middle and right sensors.
        :return: The sub-class should return the next move as a (int, int). The first is the rotation
        (could be -90, 0 or 90), the second is the number of squares to move (from -3 to 3).
        """
        raise NotImplemented("Implement by overriding in sub-class.")

    def update(self, sensors):
        """
        Convenience function for updating the maze, re-planning (if the maze was updated), and dumping the maze for
        debugging.
        :param sensors:
        :return: True if maze was updated
        """
        self.timestep += 1
        maze_updated = self.maze_map.update(self.location, self.heading, sensors)
        if maze_updated:
            self.planner.replan(self.location, self.heading)
        if self.dump_mazes:
            self.maze_map.dump_to_file(os.path.join(os.curdir, "known_maze.txt"))
        return maze_updated

    def move(self, rotation, movement):
        """
        Update the current location and heading for the class. This should be called in the sub-class after choosing
        a move.
        :type rotation: int
        :type movement: int
        :param rotation: The rotation to perform
        :param movement: The number of squares to move
        :return: None
        """
        self.heading = self.heading.rotate(rotation)
        direction_of_movement = self.heading if movement > 0 else self.heading.flip()
        for i in range(abs(movement)):
            self.location = self.location.add(direction_of_movement)
        if self.maze_map.at_goal(self.location):
            self.found_goal = True

    def reset(self):
        """
        Move the robot back to 0,0 and facing north. Also changes the run_number to 1. Call this when you are ready to
        start the second run.
        :return: Returns the reset string for convenience.
        """
        self.location = Position(0, 0)
        self.heading = Direction(0)
        self.run_number = 1
        print "Number of moves in first run: {}".format(self.timestep)
        print "Exploration efficiency: {}".format(self.get_exploration_efficiency())
        self.planner.replan(self.location, self.heading)
        return "Reset", "Reset"

    def show_current_policy_and_map(self):
        """
        For visualization of the maze and policy when using the A* planner.
        :return: None
        """
        vis = Visualizer(self.maze_map.dim)
        vis.draw_maze(Maze('known_maze.txt'))
        vis.draw_policy(reversed(self.planner.policy), self.location, self.heading)
        vis.show_window()

    def get_exploration_efficiency(self):
        return self.maze_map.get_num_known_walls() / float(self.timestep)
示例#47
0
 def __init__(self,time,longitude,latitude) :
     self.time=time
     Position.__init__(self,longitude,latitude)
示例#48
0
def grab_position(keyword, gj='', xl='', yx='', gx='', st='', lc='', workAddress='', city='全国'):
    reload(sys)
    sys.setdefaultencoding('utf-8')
    url = "http://www.lagou.com/jobs/list_" + keyword
    params = {'spc': 1, 'pl': "", 'xl': xl, 'yx': yx, 'gx': gx, 'st': st, 'labelWords': '', 'city': city,
              'requestId': ""}
    list = requests.get(url, params=params)
    parser = BeautifulSoup(list.content)

    # print list.content
    posistions = []
    companys = []

    pos_html = parser.find_all("div", class_="hot_pos_l")
    cmp_html = parser.find_all("div", class_="hot_pos_r")
    for i in range(len(pos_html)):
        p2 = BeautifulSoup(repr(pos_html[i]))
        cmp_parser = BeautifulSoup(repr(cmp_html[i]))
        p = Position()
        c = Company()

        # 抓取职位信息
        spans = p2.find_all('span')
        p.salary = spans[1].text
        p.experience = spans[2].text
        p.edu = spans[3].text
        p.candy = spans[4].text
        p.name = pos_html[i].div.a.text
        p.place = pos_html[i].div.span.text
        p_url = pos_html[i].div.a['href']
        p_detail = requests.get(p_url)
        detail_parser = BeautifulSoup(p_detail.content)
        p.detail = detail_parser.find_all("dd", class_="job_bt")[0].text

        # 抓取公司信息
        hot_pos_r = cmp_parser.find_all("span")
        if len(hot_pos_r) == 4:
            c.field = hot_pos_r[0].text
            c.founder = hot_pos_r[1].text
            c.funding = hot_pos_r[2].text
            c.extent = hot_pos_r[3].text
        elif len(hot_pos_r) == 3:
            c.field = hot_pos_r[0].text
            c.funding = hot_pos_r[1].text
            c.extent = hot_pos_r[2].text

        # 关联
        tmp = cmp_parser.find_all("a")
        c_id_a = tmp[1]
        c.name = c_id_a.text
        c_id = c_id_a['href']
        c_id = re.findall('\d+', c_id)
        cmp_page = requests.get(c_id_a['href'])
        page_parser = BeautifulSoup(cmp_page.content)
        intro = page_parser.find_all("div", class_="c_intro")
        if len(intro) > 0:
            c.mainPage = intro[0].text
        else:
            c.mainPage = '暂无简介'
        p.cmp_id = c_id
        c.id = c_id
        write_to_db.add_pos(p, 'position')
        write_to_db.add_pos(c, 'company')
    print len(posistions)
	def isThisRaidOrSneak(self, tempBoxState, rowIndex, columnIndex, firstPlayerValue, secondPlayerValue):
		raid = False
		positions = []
		# Determine the position above
		if(rowIndex > 0):
			upPosition = Position(0, 0)
			upPosition.rowIndex = rowIndex - 1
			upPosition.columnIndex = columnIndex
			if(tempBoxState[upPosition.rowIndex][upPosition.columnIndex].occupiedBy == firstPlayerValue):
				raid = True

		# Determine the position to the right
		if(columnIndex < (len(tempBoxState)-1)):
			rightPosition = Position(0, 0)
			rightPosition.rowIndex = rowIndex
			rightPosition.columnIndex = columnIndex + 1
			if(tempBoxState[rightPosition.rowIndex][rightPosition.columnIndex].occupiedBy == firstPlayerValue):
				raid = True

		# Determine the position below
		if(rowIndex < len(tempBoxState)-1):
			bottomPosition = Position(0, 0)
			bottomPosition.rowIndex = rowIndex + 1
			bottomPosition.columnIndex = columnIndex
			if(tempBoxState[bottomPosition.rowIndex][bottomPosition.columnIndex].occupiedBy == firstPlayerValue):
				raid = True

		# Determine the position to the left
		if(columnIndex > 0):
			leftPosition = Position(0, 0)
			leftPosition.rowIndex = rowIndex
			leftPosition.columnIndex = columnIndex - 1
			if(tempBoxState[leftPosition.rowIndex][leftPosition.columnIndex].occupiedBy == firstPlayerValue):
				raid = True

		return raid
示例#50
0
	def enleverPosition(self,Position):
		for PositionCur in self.positionsOcuppees:
			if (Position.getX() == PositionCur.getX() and Position.getY() == PositionCur.getY()):
				PositionCur.set_Tire()
示例#51
0
#!/usr/bin/python

from Servo import Servo
from Position import Position

servo0 = Servo(0)
servo1 = Servo(1)
p = Position()

while True:
        (x_pos, y_pos, z_pos) = p.get_position()
        print("X:{} Y:{} Z:{}".format(x_pos, y_pos, z_pos))

        x_pos_target  = int((1.0 + x_pos) * 50)
        y_pos_target  = int((1.0 + y_pos) * 50)

        servo0.move_to_position(x_pos_target)
        servo1.move_to_position(y_pos_target)
	def getEnemyBoxPositionsAdjacentToTheBox(self, tempBoxState, rowIndex, columnIndex, firstPlayerValue, secondPlayerValue):
		raidOrSneak = True
		raidOrSneak = self.isThisRaidOrSneak(tempBoxState, rowIndex, columnIndex, firstPlayerValue, secondPlayerValue)

		positions = []
		if(raidOrSneak == True):
			# Determine the position above
			if(rowIndex > 0):
				upPosition = Position(0, 0)
				upPosition.rowIndex = rowIndex - 1
				upPosition.columnIndex = columnIndex
				if(tempBoxState[upPosition.rowIndex][upPosition.columnIndex].occupiedBy == secondPlayerValue):
					positions.append(upPosition)
					# print "up added"

			# Determine the position to the right
			if(columnIndex < (len(tempBoxState)-1)):
				rightPosition = Position(0, 0)
				rightPosition.rowIndex = rowIndex
				rightPosition.columnIndex = columnIndex + 1
				if(tempBoxState[rightPosition.rowIndex][rightPosition.columnIndex].occupiedBy == secondPlayerValue):
					positions.append(rightPosition)
					# print "right added"

			# Determine the position below
			if(rowIndex < len(tempBoxState)-1):
				bottomPosition = Position(0, 0)
				bottomPosition.rowIndex = rowIndex + 1
				bottomPosition.columnIndex = columnIndex
				if(tempBoxState[bottomPosition.rowIndex][bottomPosition.columnIndex].occupiedBy == secondPlayerValue):
						positions.append(bottomPosition)
						# print "bottom added"

			# Determine the position to the left
			if(columnIndex > 0):
				leftPosition = Position(0, 0)
				leftPosition.rowIndex = rowIndex
				leftPosition.columnIndex = columnIndex - 1
				if(tempBoxState[leftPosition.rowIndex][leftPosition.columnIndex].occupiedBy == secondPlayerValue):
						positions.append(leftPosition)
						# print "left added"
		return positions
示例#53
0
	def coordonneValide(self,Position):
		# Return true si la position appartient à la grille
		return (Position.getX() <= self.largeur and Position.getX() >= 0 and Position.getY() <= self.hauteur and Position.getY() >= 0)