Exemplo n.º 1
0
def drawNewBuilding(x, theScore):
    global buildingList, objectList, scrollSpeed, bomb, walls, pigeonList

    startX = x
    startY = random.getrandbits(5) + 30
    if startY > 70:
        startY = 70

    wallId = random.getrandbits(3) + 1

    if wallId > 3:
        wallId = 3

    buildingLength = ((random.getrandbits(3) + 1) * 3) + 2
    if buildingLength < 10:
        buildingLength = 10
        wallId = 0

    spacing = random.getrandbits(2) + 1

    # Do we need birds
    if buildingLength > 15 and random.getrandbits(7) > 100:
        ctr = 4
        for bird in pigeonList:
            bird.reset(startX + ctr + 20 + (spacing * 8), startY - 6)
            ctr += 7

    floorId = random.getrandbits(3)
    if floorId > 3:
        floorId = 3

    # Create a box or bomb if building is long enough and not the first building
    if theScore > 100:
        # Don't do this on first building
        if x != 0:
            objType = random.getrandbits(1)

            if buildingLength > 15:
                if random.getrandbits(3) > 5:
                    # Crate
                    if objType == 0:
                        objectList.append(
                            Object(blocks, startX + (buildingLength * 8) // 2,
                                   startY, objType, 14, 14))

                    # Bomb
                    else:
                        objectList.append(
                            Object(bomb, startX + ((buildingLength - 3) * 8),
                                   startY, objType, 18, 11))

    windowId = random.getrandbits(1)

    if x == 0:
        spacing = 0

    buildingList.append(
        Building(startX, startY, buildingLength, spacing, floorId, wallId,
                 windowId))
Exemplo n.º 2
0
Arquivo: menu.py Projeto: Edz77/aero
 def __init__(self):
     self.all_sprites = pygame.sprite.Group()
     self.key_group = pygame.sprite.Group()
     self.image = Object(MENU_ASSET, 0, 0, self.all_sprites)
     self.key = Object(KEY_ASSET, 0, 600, self.key_group)
     self.menu_water = Object(MENU_WATER, 0, 550, self.all_sprites)
     self.change_scene = False
     self.tick = 0
Exemplo n.º 3
0
def change_level(levelnumber, inv = [], coins=0):
    level = l.levels[levelnumber]
    news.append("Level " + str(levelnumber + 1) + ", " + l.levels[levelnumber].name + "...")
    floorplan_file = level.m
    gobbonum = level.num_gobbos
    coinum = level.num_gold
    time = level.time
    cs = []
    objects = level.objects
    floorplan = read_floorplan(floorplan_file)
    
    width = len(floorplan[1])
    height = len(floorplan)
       
     # x, y, image, color
    
    player = creatures.Creature(18, 17, "@", 1, "player")
    player.coins = coins
    player.health = 3
    cs.append(player)
    
    player.inv = inv
    rawck = Object(0,0,".", 12, "rock")
    player.inv.append(rawck)

    
    gobbo = creatures.Creature(0, 0, "&", 4, "gobbo")
    spawn_random(1, width - 1, 1, height - 2, gobbo, floorplan, cs, gobbonum)

    villager = creatures.Creature(0, 0, "v", 17, "villager")
    spawn_random(1, width - 1, 1, height - 2, villager, floorplan, cs, level.num_villagers)
    for v in cs:
        if v.type == "villager" and level.name == "The dwarven village of Brorldown":
            brorlspeeches = ["Gooday stranger, welcome to our modest little town of Brorldown.",
                        "I see you are loaded with stolen loot! Might I sugest you check out our magic item shops?",
                        "Oh its you, the notorious Namafero, raider of goblins! It is an honor to have you in our town...",
                        "'Sup!",
                        "I hope you enjoy your stay here, adventurer!"]
            v.speek = choice(brorlspeeches)
        if v.type == "villager" and level.name == "The Begining":
            tankspeeches = ["Gooday stranger, welcome to our modest little town of Tankton.",
                        "I hear the town mage wants to converse with you.",
                        "You're going into the goblin base? That's madness! You'll die!",
                        "Hello there!",
                        "I hope you enjoy your stay here, adventurer!"]
            v.speek = choice(tankspeeches)
    
    chest = Object(0,0,"=", 15, "treasure chest")
    spawn_random(1, width - 1, 1, 5, chest, floorplan, objects, 1)
    
    coin = Object(0,0,"$",15,"coin")
    spawn_random(1, width - 1, 1, height - 2, coin, floorplan, objects, coinum)

    for i in level.inhabitants:
        cs.append(i)

    return (cs, objects, floorplan, time)
Exemplo n.º 4
0
    def __init__(self):
        self.sensor_array = []
        self.sensor_values = [0, 0]
        # Has the sensor can seen the target?
        self.target = False

        # Forward facing sensory inputs.
        for i in range(0, 2):
            self.sensor_array.append(Object(0, (0, 0)))
            self.sensor_array[i].load_image("image_resources/sensor.png")
        # Upward facing sensor
        self.sensor_array.append(Object(0, (0, 0)))
        self.sensor_array[2].load_image("image_resources/sensor_two.png")
Exemplo n.º 5
0
def throw_rock(player, objects, cs, stdscr, m):
    width = len(m[1])
    height = len(m)
    news.append("Where do you want to throw the rock?")
    display_news(stdscr, news, width, height)
    stdscr.addstr(player.y - 1,player.x, "^", curses.color_pair(1)),
    stdscr.addstr(player.y + 1,player.x, "v", curses.color_pair(1))
    stdscr.addstr(player.y,player.x - 1, "<", curses.color_pair(1))
    stdscr.addstr(player.y,player.x + 1, ">", curses.color_pair(1))
    stdscr.refresh()
                                                 
    inp = stdscr.getch()
    dx = 0
    dy = 0
    if inp == curses.KEY_DOWN:
        dy = 5 
    elif inp == curses.KEY_UP:
        dy = -5
    elif inp == curses.KEY_LEFT:
        dx = -5
    elif inp == curses.KEY_RIGHT:
        dx = 5

    news.append("Yeet!")
                           
    drop_first(lambda x: x.type == "rock", player.inv)
    rock = Object(player.x + dx, player.y + dy,".", 12, "rock")
    objects.append(rock)   
    enemies = filter(lambda c: c.type != "player" and distance(c,rock) <= 10, cs)
    for e in enemies:
        e.target = (rock.x, rock.y)
        e.distracted = 3
Exemplo n.º 6
0
Arquivo: menu.py Projeto: Edz77/aero
 def animation(self):
     self.tick += 1
     if self.tick <= 45:
         self.key = Object(KEY_ASSET, 0, 600, self.key_group)
     else:
         if self.tick > 90:
             self.tick = 0
         self.key_group.empty()
Exemplo n.º 7
0
def load_kitti(path, mode='train', image_dir=None, label_dir=None):

    packets = []

    with open(path + mode + '.txt', 'rb') as f:

        file_list = [x.strip() for x in f.readlines()]

    for file in file_list:

        image_path = image_dir + file + '.png'

        label_path = label_dir + file + '.txt'

        with open(label_path) as f:

            object_list = []

            for line in f:

                obj_class, truncated, occluded, alpha, bx1, by1, bx2, by2, dz, dy, dx, tx, ty, tz, rot_y = line.split(
                )

                if obj_class == 'Car':  #and float(truncated) == 0: #and float(occluded) == 0 :

                    size = [float(x) for x in [dx, dy, dz]]

                    position = [float(x) for x in [tx, ty, tz]]

                    rot_y = float(rot_y)

                    top_left = (int(float(bx1)), int(float(by1)))

                    bottom_right = (int(float(bx2)), int(float(by2)))

                    obj = Object(obj_class,
                                 top_left=top_left,
                                 bottom_right=bottom_right)

                    obj.size = size

                    obj.position = position

                    object_list.append(obj)

            if object_list != []:

                packet = Packet(image_path, objects=object_list)

            else:

                continue

        packets.append(packet)

    return packets
Exemplo n.º 8
0
 def world_building(self, object_num):
     if not self.running and (object_num < 4 or self.draw_goal == False):
         if self.custom_build or object_num > 3:
             self.placing_object = True
             # Centered so cursor is in the middle of the image
             self.unplaced = Object(0,
                                    (self.pos[0] - 200, self.pos[1] - 200))
             self.unplaced.load_image("image_resources/" +
                                      self.block_images[object_num] +
                                      ".png")
             self.unplaced_goal = (object_num > 3)
Exemplo n.º 9
0
def analyze_img():
    #print("-------------REQUESTED ANALYZE IMAGE --------------------")
    # Set image_url to the URL of an image that you want to analyze.
    # img_url = image name
    if request.args.get('img_url'):
        image_url = app.config['IMG_FOLDER'] + request.args.get('img_url')
    else:
        return json.dumps({"Error": "Img_url is missing"})

    headers = {
        'Ocp-Apim-Subscription-Key': subscription_key_cv,
        'Content-Type': 'application/octet-stream'
    }
    params = {'visualFeatures': 'Objects'}
    image_data = open(image_url, "rb").read()
    # data = {'url': image_url}
    response = requests.post(analyze_url,
                             headers=headers,
                             params=params,
                             data=image_data)
    response.raise_for_status()

    # The 'analysis' object contains various fields that describe the image. The most
    # relevant caption for the image is obtained from the 'description' property.
    analysis = response.json()

    object_list = []
    for object in analysis['objects']:
        obj_h = object['rectangle']['h']
        desc = object['object']
        if desc in OBJECTS_HEIGHT.keys():
            real_height = OBJECTS_HEIGHT[desc.lower()]
        else:
            real_height = 15
        obj = Object(obj_h, real_height, desc, object['rectangle'])
        obj.calculate_distance()
        object_list.append(obj)
    object_list = sorted(object_list, key=lambda k: k.distance)
    response_json = []
    for obj in object_list:
        #print(str(obj))

        d = {
            'img_height': obj.img_height,
            'real_height': obj.real_height,
            'desc': obj.desc,
            'distance': obj.distance,
            'direction': get_directions(obj, image_url),
            'position': obj.position
        }
        response_json.append(d)
    #print(response_json)
    return json.dumps(response_json)
Exemplo n.º 10
0
def get_objects():
	random.seed(time.gmtime)
	objects = [];

	for i in range(10):
		x = random.randint(-10, 10)
		y = random.randint(-10, 10)

		if not (x == 2 and y == 2) and not (x == 0 and y == 0):
			objects.append(Object(i, x, y))

	return objects
Exemplo n.º 11
0
 def load_room(self, name, passage=None):
     name = 'Data/Rooms/' + name
     with open(name, mode='r') as file:
         room_map = [line.strip() for line in file]
     width = len(room_map[0])
     height = len(room_map)
     room_map = [list(row) for row in room_map]
     if passage is not None:
         row = None
         if passage == 1:
             row = 0
         elif passage == 2:
             row = height - 1
         if row is not None:
             room_map[row][width // 2 - 1] = '|'
             room_map[row][width // 2] = '|'
             room_map[row][width // 2 + 1] = '|'
     for row in range(height):
         for col in range(width):
             obj = None
             if room_map[row][col] == 'W':
                 obj = Object((self.room_sprites, self.wall_sprites),
                              'wall', col, row, BLOCK_SIZE, offset=self.offset)
             elif room_map[row][col] == '.':
                 obj = Object((self.room_sprites,), 'empty', col, row, BLOCK_SIZE, offset=self.offset)
             elif room_map[row][col] == '|':
                 obj = Object((self.room_sprites,), 'empty', col, row, BLOCK_SIZE, offset=self.offset)
                 block_wall = Object((self.block_walls,), 'wall', col, row, BLOCK_SIZE, offset=self.offset)
                 self.block_walls.add(block_wall)
             elif room_map[row][col] == 'S':
                 obj = Object((self.room_sprites,), 'empty', col, row, BLOCK_SIZE, offset=self.offset)
                 script = Object((self.room_sprites,), 'empty', col, row, BLOCK_SIZE, offset=self.offset)
                 self.scripts.add(script)
                 self.room_sprites.add(script)
             elif room_map[row][col] == 'P':
                 obj = Object((self.room_sprites,), 'empty', col, row, BLOCK_SIZE, offset=self.offset)
                 self.player = Player(col, row, offset=self.offset)
             elif room_map[row][col] == 'T':
                 obj = Object((self.room_sprites,), 'empty', col, row, BLOCK_SIZE, offset=self.offset)
                 self.teleport = Object((self.room_sprites,),
                                        'teleport', col - 2, row - 4, BLOCK_SIZE, offset=self.offset)
             if obj is not None:
                 self.room_sprites.add(obj)
     return width, height
Exemplo n.º 12
0
def load_pascal(path, mode='train'):

    packets = []

    imageset_path = path + "ImageSets/Main/" + mode + ".txt"

    annotation_base_path = path + "Annotations/"

    image_base_path = path + "JPEGImages/"

    with open(imageset_path, 'rb') as f:

        file_list = [x.strip() for x in f.readlines()]

        for file_name in file_list:

            file_path = annotation_base_path + file_name + '.xml'

            image_path = image_base_path + file_name + '.jpg'

            tree = ET.parse(file_path)

            root = tree.getroot()

            object_list = []

            for object in root.iter('object'):

                category = object.find('name').text

                xmin = float(object.find('bndbox').find('xmin').text)

                ymin = float(object.find('bndbox').find('ymin').text)

                xmax = float(object.find('bndbox').find('xmax').text)

                ymax = float(object.find('bndbox').find('ymax').text)

                obj = Object(category,
                             top_left=(xmin, ymin),
                             bottom_right=(xmax, ymax))

                object_list.append(obj)

            packet = Packet(image_path=image_path, objects=object_list)

            packets.append(packet)

    return packets
def apply_add_obj_filter(add_obj_filter, bg_img, dest_res_x, dest_res_y):
    """
            Apply 'Add object' filter with given add_obj_filter parameters, a given background image and the desired output
            resolution. The add_obj object can contain almost all other filters, which get applied on each added object.

            :param add_obj_filter: object containing add_obj parameters
            :param bg_img: background image
            :param dest_res_x: x resolution of output image
            :param dest_res_y: y resolution of output image
            :return: bg_img: background image containing all inserted objects
    """
    # get number of wanted additional objects
    if add_obj_filter.obj_min == add_obj_filter.obj_max:
        num_obj = int(add_obj_filter.obj_min)
    else:
        num_obj = random.randint(add_obj_filter.obj_min,
                                 add_obj_filter.obj_max)
    logging.info("   => add %d additional objects" % num_obj)

    # create list of objects containing 'add_obj' object images
    obj_list = []

    # add objects to the background
    for obj_counter in range(num_obj):
        # get object image
        if add_obj_filter.path_type == 0:
            add_obj_path_list = utils.list_directory(
                add_obj_filter.add_obj_path, file_ext_list=['.jpg', '.png'])
            random_add_obj_idx = random.randint(0, len(add_obj_path_list) - 1)
            add_obj_img_path = os.path.abspath(
                add_obj_filter.add_obj_path +
                add_obj_path_list[random_add_obj_idx])
        else:
            add_obj_img_path = add_obj_filter.add_obj_path
        add_obj_img = img_processing.import_image(add_obj_img_path)
        obj = Object(filename='', image=add_obj_img, bbox=None, category=None)
        obj_list.append(obj)

        # add overlap and add_obj filter so method 'apply_filters_on_objects()' can handle this
        add_obj_filter.overlap = None
        add_obj_filter.add_obj = None

    # add chosen object images to background image
    merged_img, obj_list = apply_filters_on_objects(obj_list, add_obj_filter,
                                                    bg_img, dest_res_x,
                                                    dest_res_y)

    return merged_img
Exemplo n.º 14
0
 def generate_world(self):
     # Reset environment
     self.blocks = []
     self.agents = []
     self.agent_num = 0
     # Randomly place 3 blocks.
     while len(self.blocks) < 3:
         self.unplaced = Object(0, (randint(500, 800), randint(0, 200)))
         self.unplaced.load_image("image_resources/" +
                                  self.block_images[randint(0, 3)] + ".png")
         self.unplaced.rotate(randint(0, 180))
         # Only keep the block if it touches the environment
         if self.check_environmental_overlap():
             self.blocks.append(self.unplaced)
     # Place goal
     self.set_goal()
Exemplo n.º 15
0
    def run(self):
        ioObjectTypes=[
                       bacnet.ObjectType.analogInput,  #@UndefinedVariable
                       bacnet.ObjectType.analogOutput, #@UndefinedVariable
                       bacnet.ObjectType.analogValue,  #@UndefinedVariable
                       bacnet.ObjectType.binaryInput,  #@UndefinedVariable
                       bacnet.ObjectType.binaryOutput, #@UndefinedVariable
                       bacnet.ObjectType.binaryValue,  #@UndefinedVariable
                       ]

        for target in self.devices:
            if info: print "FindObjects> ** device start:", target
            message=bacnet.ReadProperty('objectName',('device',target.device))
            response=yield Message(target.address,message)
            name=response.message.value._value
            response=yield database.Device(target.IP,target.port,target.device,name)
            deviceID,=response.pop()
            self.deviceid[deviceID]=Device(target.IP,target.port,target.device,deviceID)
            
            objects=[]
            index=0
            while True:
                index+=1
                readproperty=bacnet.ReadProperty('objectList',('device',target.device),index)
                request=yield Message(target.address,readproperty)
                if isinstance(request.message, bacnet.Error):
                    break
                
                o=request.message.value[0] ## Object
                if debug: print "FindObjects>", o
                if o.type in ioObjectTypes:
                    objects.append(o)

            if debug: print "FindObjects> ** device objects:",target.device
            for o in objects:
                response=yield Message(target.address,bacnet.ReadProperty('objectName',o))
                name=response.message.value._value
                response=yield Message(target.address,bacnet.ReadProperty('description',o))
                description=response.message.value._value
                if debug: print "FindObjects> name:", name, description
                response=yield database.Object(deviceID,target.device,o.type,o.instance,name,description)
                objectID,=response.pop()
                o=Object(deviceID,objectID,o.type,o.instance,name)
                target.objects.append(o)
                self.objectid[objectID]=o
                
            if debug: print "FindObjects> ** device end:",target.device
Exemplo n.º 16
0
    def create_final_objects(self, sensor_data):

        if self.number_of_objects != 0:

            for obj_number in range(1, self.number_of_objects + 1):
                items = []
                for item in sensor_data:
                    if item[1] == obj_number:
                        items.append(item)

                created_object = Object("", obj_number, 0)
                for compare in items:
                    if compare[2] > created_object.percentage:
                        created_object.name = compare[0]
                        created_object.percentage = compare[2]

                self.objects.append(created_object)

        return self.objects
Exemplo n.º 17
0
    def get_product(self, ids, arrayify=False, **kwargs):
        """
        Access products resource.

        Args:

        ``ids``: String o Array of Strings that represents SKU of a product.

        ``arrayify``: Boolean thats indicate if a single product should be returned in a List.

        ``kwarg expand``: expands the result document, which may include any of the __expand values:
        https://documentation.demandware.com/display/DOC132/Product+resource

        Returns:

        Product as object if SKU exists otherwise None.

        https://documentation.demandware.com/display/DOC131/Product+resource#Productresource-Getsingleproduct

        """
        expand = kwargs.get('expand', None)
        expand_query = None
        if not isinstance(expand, (list, tuple)):
            expand = [expand]
        if all(k in self.__expand for k in expand):
            expand_query = {
                'expand': '%s' % ''.join(str('%s,' % q) for q in expand)
            }
        if isinstance(ids, (list, tuple)):
            ids = '(%s)' % ''.join(
                str('%s,' % urllib.quote_plus(e)) for e in ids)
        else:
            ids = urllib.quote_plus(ids)

        self._call('products/%s' % ids, expand_query)

        if self.__last_call.response.info.code == httplib.OK:
            if hasattr(self.__last_call.response.body, 'data'):
                return [Object(o) for o in self.__last_call.response.body.data]
            elif arrayify:
                return [self.__last_call.response.body]
            else:
                return self.__last_call.response.body
Exemplo n.º 18
0
    def calc_gun_trigger(self, image_processor, object_manager):
        last_angle = self.get_last_angle()
        new_angle = image_processor.angle

        print "facing right" if image_processor.faceMinx else "facing left"
        print "last_angle: {0}, new_angle: {1}".format(last_angle, new_angle)

        fire = False
        if self.delaying:
            self.delaying -= 1
        else:
            if image_processor.faceMinx:  #towards minx, righthandside
                if new_angle - last_angle > math.pi / 8:  # shoot up
                    fire = True
            else:  # left
                # mirror angle to face other way
                t_new_angle = math.pi - abs(
                    new_angle) if new_angle >= 0 else -math.pi - abs(new_angle)
                t_last_angle = math.pi - abs(
                    last_angle) if last_angle >= 0 else -math.pi - abs(
                        last_angle)
                if t_new_angle - t_last_angle > math.pi / 8:
                    fire = True

        #and self.angle_diff(last_angle, new_angle) > math.pi/8:

        if fire:
            print "firing, last_angle: {0}, new_angle: {1}".format(
                last_angle, new_angle)

            last_handcx = self.get_last_handcx()
            last_handcy = self.get_last_handcy()
            v = 30
            object_manager.add(
                Object(last_handcx, last_handcy, v * math.cos(last_angle),
                       -v * math.sin(last_angle)))
            self.delaying = self.FIRE_DELAY
            self.last_angles.clear()

        self.last_angles.append(new_angle)
        self.last_handcx.append(image_processor.handcx)
        self.last_handcy.append(image_processor.handcy)
Exemplo n.º 19
0
    def get(self, key, default=None):
        """Get either object by key or default value.

        :param key:
            `key` value might be an `int` value (offset within the cursor),
            or a string to treat it as GUID
        :param default:
            value to return if key if not found
        :returns:
            `Object` value or `default`

        """
        if type(key) is not int:
            for page in self._pages.values():
                for obj in page:
                    if obj is not None and obj.guid == key:
                        return obj
            return Object(self.mountpoint, self.document, self._reply, key)
        else:
            offset = key

        if offset < 0 or self._total is not None and \
                (offset >= self._total):
            return default

        page = offset / self._page_size
        offset -= page * self._page_size

        if page not in self._pages:
            if not self._fetch_page(page):
                return default

        if offset >= len(self._pages[page]):
            total = page + len(self._pages[page])
            _logger.warning('Miscalculated total number, %s instead of %s',
                            total, self._total)
            self._total = total
            return default

        return self._pages[page][offset]
Exemplo n.º 20
0
    def _fetch_page(self, page):
        offset = page * self._page_size

        params = {
            'mountpoint': self.mountpoint,
            'document': self.document,
        }
        for key, value in self._filters.items():
            if value is not None:
                params[key] = value
        params['offset'] = offset
        params['limit'] = self._page_size
        if self._query:
            params['query'] = self._query
        if self._order_by:
            params['order_by'] = self._order_by
        if self._reply:
            params['reply'] = self._reply

        try:
            response = Client.call('GET', **params)
            self._total = response['total']
        except Exception:
            util.exception(_logger, 'Failed to fetch %r query', params)
            self._total = None
            return False

        result = [None] * len(response['result'])
        for i, props in enumerate(response['result']):
            result[i] = Object(self.mountpoint, self.document, self._reply,
                               props['guid'], props, offset + i)

        if not self._page_access or self._page_access[-1] != page:
            if len(self._page_access) == _QUERY_PAGES_NUMBER:
                del self._pages[self._page_access[0]]
            self._page_access.append(page)
        self._pages[page] = result

        return True
Exemplo n.º 21
0
 def __init__(self):
     self.BASE = 0  # Starting location for Quadruples //list starts with empty so its -1
     self.Quads = []
     self.globalMemory = MemoryMap("program")
     self.ConsMemory = MemoryMap("Constant")
     self.varTable = VarTable()
     self.funDir = FunctionDirectory()
     self.ClassDir = ClassTable()
     self.semanticCube = SemanticCube()
     self.pJumps = []  #
     self.VP = []  # Polish vector
     self.pOper = []
     self.pType = []
     self.pArray = []
     self.pIDs = []
     self.pEras = []
     self.pendingQuads = []
     self.current_quad = ()
     self.current_param_num = 0
     self.current_class = Class()
     self.current_object = Object()
     self.current_var = Var()
     self.current_function = Function()
     self.current_params = VarTable()
     self.current_type = SparkyType()
     self.local_class_func = FunctionDirectory()
     self.local_func = Function()
     self.local_class = Class()
     self.local_type = SparkyType()
     self.current_value = 0
     self.current_class_name = ""
     self.current_var_name = ""
     self.current_function_name = ""
     self.called_function = Function()
     self.current_scope = ""  # Working inside the global program
     self.class_stage = False  # Working either in a class or a function
     self.current_id_is_func = False
Exemplo n.º 22
0
 def set_goal(self):
     # Goal is shapped like a flag. Keep trying to place goal until the attaches to the ground by the flag pole
     for i in range(10):
         # Randomly position
         x_pos = randint(850, 900)
         self.goal = Object(0, (x_pos, 0))
         # Pick a direction for the goal to face. When placing on a slope means it can attach to the ground by the pole
         flipped = False
         if randint(0, 100) > 50:
             self.goal.load_image("image_resources/goal.png")
         else:
             self.goal.load_image("image_resources/goal_flipped.png")
             flipped = True
         counter = 0
         # Start the goal in the air. Keep lowering until it touches the ground
         while (not self.check_environmental_overlap(True)):
             counter += 1
             self.goal.set_position((x_pos, counter))
         # Lower the goal by 2 pixels to plant it firmly in the ground
         self.goal.set_position((x_pos, counter + 2))
         # If planted by the flag pole break otherwise try a maximum of 10 times
         if self.check_environmental_overlap(True) > 40:
             break
     self.draw_goal = True
Exemplo n.º 23
0
screen = pygame.display.set_mode(size)  # DEFININDO O TAMANHO DE TELA
pygame.display.set_caption("PONG-PY")

clock = pygame.time.Clock()  # TAXA DE ATUALIZACAO

#PARTE_ESCRITA
pp1 = 0  #PONTOS DO PLAYER 1
pp2 = 0  #PONTOS DO PLAYER 2
win = 0

myfont = pygame.font.SysFont(None, 50)
myfont2 = pygame.font.SysFont(None, 30)
myfont_main = pygame.font.SysFont(None, 80)

#CRIACAO DOS OBJETOS
player1 = Object(0, 210, 20, 100)
player2 = Object(width - 20, 210, 20, 100)

ball = Object(width / 2, 90, 10, 10)
ball2 = Object(width / 2, 90, 10, 10)

wall_top = Object(0, 65, width, 10)
wall_bottom = Object(0, height - 35, width, 10)

vertical_line = Object(width / 2, 65, 3, height - 90)

black_rec = Object(width / 2 - 170, height / 2 - 8, 350, 65)

main_screen = Object(0, 0, width, height)

start = 'MENU'
Exemplo n.º 24
0
 def new_object(self):
     self.current_object = Object()
Exemplo n.º 25
0
class Demandware(object):
    """
    Python Demandware SDK.

    https://documentation.demandware.com/display/DOC131/Open+Commerce+API

    """
    __USER_AGENT = 'Demandware Python SDK/%s' % __version__

    __cookie = None

    __last_call = Object()

    __required = set((
        'client_id',
        'hostname',
        'site',
        'version',
    ))

    EXPAND_AVAILABILITY = 'availability'
    EXPAND_BUNDLED_PRODUCTS = 'bundled_products'
    EXPAND_LINKS = 'links'
    EXPAND_PROMOTIONS = 'promotions'
    EXPAND_OPTIONS = 'options'
    EXPAND_IMAGES = 'images'
    EXPAND_PRICES = 'prices'
    EXPAND_VARIATIONS = 'variations'
    EXPAND_SET_PRODUCTS = 'set_products'

    __expand = set((
        EXPAND_AVAILABILITY,
        EXPAND_BUNDLED_PRODUCTS,
        EXPAND_LINKS,
        EXPAND_PROMOTIONS,
        EXPAND_OPTIONS,
        EXPAND_IMAGES,
        EXPAND_PRICES,
        EXPAND_VARIATIONS,
        EXPAND_SET_PRODUCTS,
    ))

    def __init__(self, params=dict()):
        """
        Set a client to consume OCAPI services.

        Examples:

        params=dict({
            'client_id': '',
            'hostname': '',
            'site': '',
            'version': '',
        })

        Args:

        ``params``: Dictionary that contains settings to be applied,
        all keys are required.

        Raises:

        ``ParameterInvalidError``: If an invalid parameter is detected.

        ``ParameterMissedError``: If an parameter is missed.

        """
        args = set(params.keys())
        diff = self.__required.symmetric_difference(args)

        for arg in diff:
            if arg in self.__required:
                raise ParameterMissedError('%s' % arg)
            elif arg in args:
                raise ParameterInvalidError('%s' % arg)

        self.__client_id = params.get('client_id')
        self.__hostname = params.get('hostname')
        self.__site = params.get('site')
        self.__version = params.get('version')

        self._reset()
        self._debug()
        self._set_cookie()

    def _set_cookie(self):
        """
        Store cookie.

        """
        self.__cookie = cookielib.CookieJar()
        opener = urllib2.build_opener(
            urllib2.HTTPCookieProcessor(self.__cookie))
        opener.addheaders = [('User-agent', self.__USER_AGENT)]
        urllib2.install_opener(opener)

    def _unset_cookie(self):
        """
        Remove cookie.

        """
        if self.__cookie is not None:
            self.__cookie.clear()

    def _reset(self):
        """
        Restore default values used to request a service.

        """
        self.__secure = False
        self.__method = 'GET'

        self.__headers = {
            'User-Agent': self.__USER_AGENT,
            'x-dw-client-id': self.__client_id,
        }

        self.__get = {'format': 'json', 'client_id': self.__client_id}

        self.__post = {}

    def _debug(self):
        """
        Lets inspect request and response data.

        Returns:

        Dictionary with request and response keys.

        """
        self.__debug = {
            'request': {
                'headers': self.__headers,
                'get': self.__get,
                'post': self.__post,
                'method': self.__method,
            },
            'response': {
                'info': {},
                'headers': {},
                'body': {},
            },
        }

    def _call(self, uri, extra_params=None):
        """
        Execute a request and save last response data.

        Args:

        ``uri``: String that represents resource path.

        """
        params = self.__get
        if extra_params is not None:
            params.update(extra_params)
        protocol = 'https' if self.__secure else 'http'
        url = '%s://%s/s/%s/dw/shop/%s/%s?&%s' % (
            protocol,
            self.__hostname,
            self.__site,
            self.__version,
            uri,
            urllib.urlencode(params),
        )

        self._debug()

        request = urllib2.Request(url=url, headers=self.__headers)

        if self.__method == 'POST':
            request.add_data(json.dumps(self.__post))
        try:
            response = urllib2.urlopen(request)
        except urllib2.URLError as e:
            errno = e.code if hasattr(e, 'code') else None
            errstr = str(e.msg) if hasattr(e, 'msg') else (
                str(e.reason) if hasattr(e, 'reason') else None)
            self.__debug['response']['info'] = {
                'code': errno,
                'reason': errstr
            }
        except urllib2.HTTPError as e:
            errno = e.code if hasattr(e, 'code') else None
            errstr = str(e.msg) if hasattr(e, 'msg') else (
                str(e.reason) if hasattr(e, 'reason') else None)
            self.__debug['response']['info'] = {
                'code': errno,
                'reason': errstr
            }
        else:
            self.__debug['response']['info'] = {
                'code': response.getcode(),
                'url': response.geturl()
            }
            self.__debug['response']['headers'] = dict(response.info())

            try:
                self.__debug['response']['body'] = json.loads(response.read())
            except ValueError:
                self.__debug['response']['body'] = json.loads(str(dict()))

        self.__last_call = Object(self.__debug)

        self._reset()

    def set_header(self, key, value):
        """
        Add or update HEADERS data.

        Args:

        ``key``: String that represents key in HEADERS parameters.

        ``value``: Value to be saved.

        """
        self.__headers.update({str(key): value})

    def set_get(self, key, value):
        """
        Add or update GET data.

        Args:

        ``key``: String that represents key in GET parameters.
        ``value``: Value to be saved.

        """
        self.__get.update({str(key): value})

    def set_post(self, key, value):
        """
        Add or update POST data.

        Args:

        ``key``: String that represents key in POST parameters.

        ``value``: Value to be saved.

        """
        self.__post.update({str(key): value})

    def get(self, key=None):
        """
        Lets inspect current GET data.

        Args:

        ``key``: String  that represents key in GET that should be returned.

        Returns:

        Value for key or all GET dictionary.

        """
        if key is not None:
            return self.__get.get(str(key))
        else:
            return self.__get

    def post(self, key=None):
        """
        Lets inspect current POST data.

        Args:

        ``key``: String  that represents key in POST that should be returned.

        Returns:

        Value for key or all POST dictionary.

        """
        if key is not None:
            return self.__post.get(str(key))
        else:
            return self.__post

    def header(self, key=None):
        """
        Lets inspect current HEADERS used to request an service.

        Args:

        ``key``: String that represents a HEADER that should be returned.

        Returns:

        Value for key or all HEADERS dictionary.

        """
        if key is not None:
            return self.__headers.get(str(key))
        else:
            return self.__headers

    def get_response(self, as_dict=False):
        """
        Lets inspect last response.

        Args:

        ``as_dict``: Boolean that indicates if should returns as object or dictionary.

        Returns:

        Last response as object or dictionary, it depends of as_dict.

        """
        if as_dict:
            return self.__debug['response']
        else:
            return self.__last_call

    def get_request(self, as_dict=False):
        """
        Lets inspect last request.

        Args:

        ``as_dict``: Boolean that indicates if should returns as object or dictionary.

        Returns:

        Last request as object or dictionary, it depends of as_dict.

        """
        if as_dict:
            return self.__debug['request']
        else:
            return self.__last_call

    def debug(self):
        """
        Lets inspect request and response data.

        Returns:

        Dictionary with request and response keys.

        """
        return {
            'request': self.get_request(as_dict=True),
            'response': self.get_response(as_dict=True),
        }

    def get_product(self, ids, arrayify=False, **kwargs):
        """
        Access products resource.

        Args:

        ``ids``: String o Array of Strings that represents SKU of a product.

        ``arrayify``: Boolean thats indicate if a single product should be returned in a List.

        ``kwarg expand``: expands the result document, which may include any of the __expand values:
        https://documentation.demandware.com/display/DOC132/Product+resource

        Returns:

        Product as object if SKU exists otherwise None.

        https://documentation.demandware.com/display/DOC131/Product+resource#Productresource-Getsingleproduct

        """
        expand = kwargs.get('expand', None)
        expand_query = None
        if not isinstance(expand, (list, tuple)):
            expand = [expand]
        if all(k in self.__expand for k in expand):
            expand_query = {
                'expand': '%s' % ''.join(str('%s,' % q) for q in expand)
            }
        if isinstance(ids, (list, tuple)):
            ids = '(%s)' % ''.join(
                str('%s,' % urllib.quote_plus(e)) for e in ids)
        else:
            ids = urllib.quote_plus(ids)

        self._call('products/%s' % ids, expand_query)

        if self.__last_call.response.info.code == httplib.OK:
            if hasattr(self.__last_call.response.body, 'data'):
                return [Object(o) for o in self.__last_call.response.body.data]
            elif arrayify:
                return [self.__last_call.response.body]
            else:
                return self.__last_call.response.body

    def search_product(self, query, **kwargs):
        """
        Provides keyword and refinement search functionality for products.

        Args:

        ``query``: String, the query phrase to search for.

        ``kwarg expand``: expands the result document, which may include any of the __expand values:
        https://documentation.demandware.com/display/DOC132/Product+resource

        Returns:

        Search results as object, if an error occur then None.

        https://documentation.demandware.com/display/DOC131/ProductSearch+resource#ProductSearchresource-SearchProducts

        """
        expand = kwargs.get('expand', None)
        expand_query = None
        if not isinstance(expand, (list, tuple)):
            expand = [expand]
        if all(k in self.__expand for k in expand):
            expand_query = {
                'expand': '%s' % ''.join(str('%s,' % q) for q in expand)
            }
        self.set_get('q', query)
        self._call('product_search', expand_query)

        if self.__last_call.response.info.code == httplib.OK:
            return self.__last_call.response.body

    def search_category(self, category='root', levels=2):
        """
        Get online categories.

        Args:

        ``category``: String, category Id.

        ``levels``: Integer, Specifies how many levels of nested sub-categories you want the server to return. The default
        value is 1.

        Returns:

        Categories as object, if an error occur then None.

        https://documentation.demandware.com/display/DOC131/Category+resource#Categoryresource-Getcategory

        """
        self.set_get('levels', levels)
        self._call('categories/%s' % category)

        if self.__last_call.response.info.code == httplib.OK:
            return self.__last_call.response.body

    def get_user(self):
        """
        Get current customer data.

        Returns:

        Returns the account profile object, if an error occur then None.

        https://documentation.demandware.com/display/DOC131/Account+resource#Accountresource-Getaccountprofile

        """
        self.__secure = True
        self._call('account/this')

        if self.__last_call.response.info.code == httplib.OK:
            return self.__last_call.response.body

    def register(self, username, password, profile={}):
        """
        Action to register an account.

        Args:

        ``username``: String, account username.

        ``password:``: String, account password.

        ``profile:``: Dictionary, profile properties.

        Returns:

        Returns the account profile object, if an error occur then None.

        https://documentation.demandware.com/display/DOC131/Account+resource#Accountresource-Registeraccount

        """
        self.__secure = True
        self.__method = 'POST'

        self.set_header('Content-Type', 'application/json')
        self.set_post('credentials', {
            'username': str(username),
            'password': str(password)
        })
        self.set_post('profile', profile)
        self._call('account/register')

        if self.__last_call.response.info.code == httplib.OK:
            return self.__last_call.response.body

    def login(self, username, password):
        """
        Action to login a customer.

        Args:

        ``username``: String, customer username.

        ``password:``: String, customer password.

        Returns:

        If success then returns True otherwise False.

        https://documentation.demandware.com/display/DOC131/Account+resource#Accountresource-Loginaction

        """
        self.__secure = True
        self.__method = 'POST'

        self.set_header('Content-Type', 'application/json')
        self.set_post('username', str(username))
        self.set_post('password', str(password))
        self._call('account/login')

        if self.__last_call.response.info.code == httplib.NO_CONTENT:
            return True
        return False

    def logout(self):
        """
        Action to logout a customer.

        Returns:

        If success then returns True otherwise False.

        https://documentation.demandware.com/display/DOC131/Account+resource#Accountresource-Logoutaction

        """
        self.__secure = True
        self.__method = 'POST'

        self.set_header('Content-Type', 'application/json')
        self._call('account/logout')

        if self.__last_call.response.info.code == httplib.NO_CONTENT:
            return True
        return False

    def get_basket(self):
        """
        Returns a limited set of basket information. Limited means that no checkout related information
        (i.e. addresses, shipping and payment method) are returned.

        Returns:

        If success then Basket as object otherwise None.

        https://documentation.demandware.com/display/DOC131/Basket+resource#Basketresource-Getbasket

        """
        self._call('basket/this')

        if self.__last_call.response.info.code == httplib.OK:
            return self.__last_call.response.body
Exemplo n.º 26
0
    def _call(self, uri, extra_params=None):
        """
        Execute a request and save last response data.

        Args:

        ``uri``: String that represents resource path.

        """
        params = self.__get
        if extra_params is not None:
            params.update(extra_params)
        protocol = 'https' if self.__secure else 'http'
        url = '%s://%s/s/%s/dw/shop/%s/%s?&%s' % (
            protocol,
            self.__hostname,
            self.__site,
            self.__version,
            uri,
            urllib.urlencode(params),
        )

        self._debug()

        request = urllib2.Request(url=url, headers=self.__headers)

        if self.__method == 'POST':
            request.add_data(json.dumps(self.__post))
        try:
            response = urllib2.urlopen(request)
        except urllib2.URLError as e:
            errno = e.code if hasattr(e, 'code') else None
            errstr = str(e.msg) if hasattr(e, 'msg') else (
                str(e.reason) if hasattr(e, 'reason') else None)
            self.__debug['response']['info'] = {
                'code': errno,
                'reason': errstr
            }
        except urllib2.HTTPError as e:
            errno = e.code if hasattr(e, 'code') else None
            errstr = str(e.msg) if hasattr(e, 'msg') else (
                str(e.reason) if hasattr(e, 'reason') else None)
            self.__debug['response']['info'] = {
                'code': errno,
                'reason': errstr
            }
        else:
            self.__debug['response']['info'] = {
                'code': response.getcode(),
                'url': response.geturl()
            }
            self.__debug['response']['headers'] = dict(response.info())

            try:
                self.__debug['response']['body'] = json.loads(response.read())
            except ValueError:
                self.__debug['response']['body'] = json.loads(str(dict()))

        self.__last_call = Object(self.__debug)

        self._reset()
Exemplo n.º 27
0
    def callbackpit(self, TrackedShapes_msg):
        """ read messages received from pit containig the slowest informations related to the shape of the object.
		 	The function merges these informations with the other received from merger node and write them in the ontology.
		 	It saves all individuals in a variable 'object' that keep in memory the old state
		"""
        lentensor = len(self.mergeid)
        lenpit = len(TrackedShapes_msg.tracked_shapes)
        if (lenpit > 0 and lentensor > 0):
            for i in range(0, lenpit):
                for j in range(0, lentensor):
                    if (TrackedShapes_msg.tracked_shapes[i].object_id ==
                            self.mergeid[j]):
                        match = 0
                        for k in range(0, len(self.objects)):
                            if (self.objects[k].id == self.mergeid[j]):
                                match = 1

                                self.objects[
                                    k].label = self.res.check_property(
                                        self.mergeid[j], "has-label", "STRING",
                                        self.tensorlabel[j],
                                        self.objects[k].label)
                                self.objects[
                                    k].Xcenter = self.res.check_property(
                                        self.mergeid[j],
                                        "has-geometric_centerX", "FLOAT",
                                        TrackedShapes_msg.tracked_shapes[i].
                                        x_est_centroid,
                                        self.objects[k].Xcenter)
                                self.objects[
                                    k].Ycenter = self.res.check_property(
                                        self.mergeid[j],
                                        "has-geometric_centerY", "FLOAT",
                                        TrackedShapes_msg.tracked_shapes[i].
                                        y_est_centroid,
                                        self.objects[k].Ycenter)
                                self.objects[
                                    k].Zcenter = self.res.check_property(
                                        self.mergeid[j],
                                        "has-geometric_centerZ", "FLOAT",
                                        TrackedShapes_msg.tracked_shapes[i].
                                        z_est_centroid,
                                        self.objects[k].Zcenter)
                                #check if the shape is changed
                                if (self.objects[k].shape != TrackedShapes_msg.
                                        tracked_shapes[i].shape_tag):
                                    # if the shape is changed, also relative parameters are changed
                                    #delete old state and create a new one with new parameters
                                    self.res.remove_coefficients(
                                        self.objects[k])
                                    self.objects[k].delete_shapes_coefficients(
                                    )
                                    self.objects[
                                        k].shape = TrackedShapes_msg.tracked_shapes[
                                            i].shape_tag
                                    self.res.add_coefficients(
                                        TrackedShapes_msg.tracked_shapes[i].
                                        coefficients, self.objects[k])

                                else:
                                    self.res.check_properties_for_shapes(
                                        self.objects[k], TrackedShapes_msg.
                                        tracked_shapes[i].coefficients)

                                print "UPDATING OBJECT", self.tensorlabel[
                                    j], "	SHAPE:", TrackedShapes_msg.tracked_shapes[
                                        i].shape_tag, "	ID:", self.mergeid[j]

                        #if nothing has been found or if the vector is empty, a new individual is created in the ontology
                        #and the object is added to the vector
                        if (match == 0 or len(self.objects) == 0):
                            print "NEW OBJECT DETECTED", self.tensorlabel[j]
                            ##create a new object
                            individual = Object()
                            ##init common properties for each shape
                            individual.init_common_value(
                                TrackedShapes_msg.tracked_shapes[i].object_id,
                                self.tensorlabel[j],
                                TrackedShapes_msg.tracked_shapes[i].shape_tag,
                                TrackedShapes_msg.tracked_shapes[i].
                                x_est_centroid, TrackedShapes_msg.
                                tracked_shapes[i].y_est_centroid,
                                TrackedShapes_msg.tracked_shapes[i].
                                z_est_centroid)

                            self.res.add_new_individual_and_properties(
                                individual)
                            #add coefficients informations
                            self.res.add_coefficients(
                                TrackedShapes_msg.tracked_shapes[i].
                                coefficients, individual)
                            #add the new object in memory
                            self.objects.append(individual)
            client.utils.apply_buffered_changes()
            client.utils.sync_buffered_reasoner()
            client.utils.save_ref_with_inferences(path + "empty-scene.owl")
Exemplo n.º 28
0
print("Object Name: " + object_name) 
gripper_name="mpalms_all_coarse.stl"
table_name="table_top_collision.stl"

meshes_dir = '/root/catkin_ws/src/config/descriptions/meshes'
# object_mesh = os.path.join(meshes_dir, 'objects/cuboids/', object_name)
object_mesh = os.path.join(meshes_dir, 'objects/', object_name)
table_mesh = os.path.join(meshes_dir, 'table', table_name)
gripper_mesh = os.path.join(meshes_dir, 'mpalm', gripper_name)

# _object = Object(mesh_name="config/descriptions/meshes/objects/" + object_name)
# table = CollisionBody(mesh_name="config/descriptions/meshes/table/" + table_name)
start_time = time.time()
_object = {}
_object['file'] = object_name
_object['object'] = Object(mesh_name=object_mesh)
table = CollisionBody(mesh_name=table_mesh)
trans, quat = listener.lookupTransform("yumi_body", "table_top", rospy.Time(0))
table_pose = trans + quat
table.setCollisionPose(table.collision_object, roshelper.list2pose_stamped(table_pose, "yumi_body"))
# gripper_left = CollisionBody(mesh_name="config/descriptions/meshes/mpalm/" + gripper_name)
# gripper_right = CollisionBody(mesh_name="config/descriptions/meshes/mpalm/" + gripper_name)
gripper_left = CollisionBody(mesh_name=gripper_mesh)
gripper_right = CollisionBody(mesh_name=gripper_mesh)

# q0 = roshelper.list2pose_stamped([0.4500000000000001, -0.040000000000000056, 0.07145000425107054, 0.4999999999999997, 0.4999999999999997, 0.4999999999999997, 0.5000000000000003])
q0 = roshelper.list2pose_stamped([0.45,0,0,0,0,0,1])

#3. sample object
sampler = sampling.Sampling(q0, _object, table, gripper_left, gripper_right, listener, br)
#4. grasp samplers
Exemplo n.º 29
0
Arquivo: menu.py Projeto: Edz77/aero
 def __init__(self):
     self.all_sprites = pygame.sprite.Group()
     self.image = Object(GAMEOVER_ASSET, 0, 0, self.all_sprites)
     self.change_scene = False
Exemplo n.º 30
0
import sampling
import grasp_sampling, lever_sampling
from objects import Object, CollisionBody
import rospy, tf

#initialize ROS
rospy.init_node('planning_test')
listener = tf.TransformListener()
br = tf.TransformBroadcaster()

#1. build environment
# object_name = "cylinder_simplify.stl"
object_name = "realsense_box_experiments.stl"
gripper_name="mpalms_all_coarse.stl"
table_name="table_top_collision.stl"
_object = Object(mesh_name="config/descriptions/meshes/objects/" + object_name)
table = CollisionBody(mesh_name="config/descriptions/meshes/table/" + table_name)
trans, quat = listener.lookupTransform("yumi_body", "table_top", rospy.Time(0))
table_pose = trans + quat
table.setCollisionPose(table.collision_object, roshelper.list2pose_stamped(table_pose, "yumi_body"))
gripper_left = CollisionBody(mesh_name="config/descriptions/meshes/mpalm/" + gripper_name)
gripper_right = CollisionBody(mesh_name="config/descriptions/meshes/mpalm/" + gripper_name)
# q0 = roshelper.list2pose_stamped([0.4500000000000001, -0.040000000000000056, 0.07145000425107054, 0.4999999999999997, 0.4999999999999997, 0.4999999999999997, 0.5000000000000003])
q0 = roshelper.list2pose_stamped([0.45,0,0,0,0,0,1])

#3. sample object
sampler = sampling.Sampling(q0, _object, table, gripper_left, gripper_right, listener, br)
#4. grasp samplers
# grasp_samples = grasp_sampling.GraspSampling(sampler,
#                                              num_samples=3,
#                                              is_visualize=True)