def __init__(self):
        Thing.__init__(self, 'My Humidity Sensor', 'multiLevelSensor',
                       'A web connected humidity sensor')

        self.add_property(
            Property(self,
                     'on',
                     Value(True),
                     metadata={
                         'type': 'boolean',
                         'description': 'Whether the sensor is on',
                     }))

        self.level = Value(0.0)
        self.add_property(
            Property(self,
                     'level',
                     self.level,
                     metadata={
                         'type': 'number',
                         'description': 'The current humidity in %',
                         'unit': '%',
                     }))

        log.debug('starting the sensor update looping task')
Beispiel #2
0
    def __setattr__(self, name, value):
        # Bypass all redirection when initializing
        if self.__dict__['__initializing__']:
            super(models.Model, self).__setattr__(name, value)
            return

        # Handle special case for `data` field
        if name == 'data':
            self.__dict__['data'] = Thing(value)
            return

        # Handle special case for `json_data` field
        if name == 'json_data':
            self.__dict__['data'] = Thing(value)
            self.__dict__['json_data'] = value
            return

        # Handle private and protected fields with default behaviour
        if name.startswith('_'):
            super(models.Model, self).__setattr__(name, value)
            return

        try:
            # Let Django try to solve the attribute
            super(models.Model, self).__getattribute__(name)
            # If it exists, then we just set it as usual
            super(models.Model, self).__setattr__(name, value)
        except AttributeError:
            # If it didn't existed, then set it inside our thing
            try:
                setattr(self.data, name, value)
            except ValueError as e:
                raise ValueError("At attribute `%s`: %s" % (name, str(e)))
    def __init__(self, ledPin):
        Thing.__init__(self, 'urn:dev:ops:blue-led-1234', 'Blue LED',
                       ['OnOffSwitch', 'Light'],
                       'Blue LED on SparkFun ESP32 Thing')
        self.pinLed = machine.Pin(ledPin, machine.Pin.OUT)
        self.pwmLed = machine.PWM(self.pinLed)
        self.ledBrightness = 50
        self.on = False
        self.updateLed()

        self.add_property(
            Property(self,
                     'on',
                     Value(self.on, self.setOnOff),
                     metadata={
                         '@type': 'OnOffProperty',
                         'title': 'On/Off',
                         'type': 'boolean',
                         'description': 'Whether the LED is turned on',
                     }))
        self.add_property(
            Property(self,
                     'brightness',
                     Value(self.ledBrightness, self.setBrightness),
                     metadata={
                         '@type': 'BrightnessProperty',
                         'title': 'Brightness',
                         'type': 'number',
                         'minimum': 0,
                         'maximum': 100,
                         'unit': 'percent',
                         'description': 'The brightness of the LED',
                     }))
Beispiel #4
0
def render_n_things(
    n, things, THINGS_SURF
):  # генерация settings.number_thingsнепересекающихся спрайтов с изображениями предметов  на игровай панели
    index_things = 0
    attempt = 0
    offset = 30
    points_list = game_render.get_points_list(
        settings.screen_width - 2 * offset,
        settings.screen_height - 2 * offset)
    while index_things < n and attempt < n * 3:
        if len(
                points_list
        ) > 0:  # заранее подготовленный список точек в разных частях поля
            point = points_list.pop()
            new_thing = Thing(point[0] + offset, point[1] + offset,
                              THINGS_SURF[index_things])
        else:
            new_thing = Thing(
                randint(offset, settings.screen_width - offset),
                randint(
                    offset,
                    settings.screen_height + settings.height_bottom_panel -
                    settings.height_bottom_panel - offset),
                THINGS_SURF[index_things])
        blocks_hit_list = pygame.sprite.spritecollide(
            new_thing, things, False, pygame.sprite.collide_circle)
        if len(blocks_hit_list) == 0:
            things.add(new_thing)
            index_things += 1
        attempt += 1
    # print(attempt)
    return things
    def __init__(self):
        Thing.__init__(
            self,
            'urn:dev:ops:my-humidity-sensor-1234',
            'My Humidity Sensor',
            ['MultiLevelSensor'],
            'A web connected humidity sensor'
        )

        self.level = Value(0.0)
        self.add_property(
            Property(self,
                     'level',
                     self.level,
                     metadata={
                         '@type': 'LevelProperty',
                         'title': 'Humidity',
                         'type': 'number',
                         'description': 'The current humidity in %',
                         'minimum': 0,
                         'maximum': 100,
                         'unit': 'percent',
                         'readOnly': True,
                     }))

        log.debug('starting the sensor update looping task')
 def __init__(self, default_name, path):
     Thing.__init__(self, default_name, path)
     self.open = False
     self.set_description(
         'strong roots',
         'These roots look very strong. You wish you could move them.')
     self.add_adjectives('strong')
     self.actions.append(Action(self.move_roots, ['move'], True, False))
Beispiel #7
0
def main():
    t1 = Thing(0)


    for i in range(10,"good"):
        print "move:",i
        t1.display()
        t1.move()
Beispiel #8
0
 def __init__(self,
              name, char, col,
              control, time_to_act,
              is_immobile):
     Thing.__init__(self, name, char, col, is_immobile)
     
     self.control = control
     self.time_to_act = time_to_act
     self.field_of_view_radius = 10
    def test_heaviest_thing(self):
        t1 = Thing("some name", 20)
        t2 = Thing("some name", 30)

        s = Suitecase(100)
        s.add_thing(t1)
        s.add_thing(t2)

        self.assertEqual(t2, s.heaviest_thing())
Beispiel #10
0
def make_thing():
    thing = Thing('My Lamp', 'dimmableLight', 'A web connected lamp')

    def noop(_):
        pass

    thing.add_property(
        Property(thing,
                 'on',
                 Value(True, noop),
                 metadata={
                     'type': 'boolean',
                     'description': 'Whether the lamp is turned on',
                 }))
    thing.add_property(
        Property(thing,
                 'level',
                 Value(50, noop),
                 metadata={
                     'type': 'number',
                     'description': 'The level of light from 0-100',
                     'minimum': 0,
                     'maximum': 100,
                 }))

    thing.add_available_action(
        'fade', {
            'description': 'Fade the lamp to a given level',
            'input': {
                'type': 'object',
                'required': [
                    'level',
                    'duration',
                ],
                'properties': {
                    'level': {
                        'type': 'number',
                        'minimum': 0,
                        'maximum': 100,
                    },
                    'duration': {
                        'type': 'number',
                        'unit': 'milliseconds',
                    },
                },
            }
        }, FadeAction)

    thing.add_available_event(
        'overheated', {
            'description':
            'The lamp has exceeded its safe operating temperature',
            'type': 'number',
            'unit': 'celsius'
        })

    return thing
    def test_add_things_over_limit(self):
        t1 = Thing("some name", 80)
        t2 = Thing("some name", 21)

        s = Suitecase(100)

        s.add_thing(t1)
        s.add_thing(t2)

        self.assertEqual("1 thing (80kg)", s.to_string())
Beispiel #12
0
 def __init__(self, width, height, mass, speedlimit=.5):
     Thing.__init__(self, width, height, mass, speedlimit=.5)
     self.gravity = True
 
     self.jump_power = 15
     self.jump_power2 = 15
     self.doublejump_delay = 0
     
     self.walljump_power_right = False
     self.walljump_power_left = False
    def get_objects_map(self):

        for thing_name in names_list['things']:
            if thing_name == 'Лошарик':
                object_instance = Thing(name=thing_name,
                                        hp=10,
                                        damage=10,
                                        protection=10)
                self.objects_map['things'].append(object_instance)
            else:
                capacity = random.randint(4, 8)
                for _ in range(capacity):
                    hp = random.randint(1, 10)
                    damage = random.randint(1, 10)
                    protection = random.randint(1, 4)
                    object_instance = Thing(name=thing_name,
                                            hp=hp,
                                            damage=damage,
                                            protection=protection)
                    self.objects_map['things'].append(object_instance)

        for armor_name in names_list['armors']:
            capacity = random.randint(4, 8)
            for _ in range(capacity):
                hp = random.randint(1, 10)
                damage = random.randint(1, 10)
                protection = random.randint(1, 4)
                object_instance = Armor(name=armor_name,
                                        hp=hp,
                                        damage=damage,
                                        protection=protection)
                self.objects_map['armors'].append(object_instance)

        for armor_name in names_list['weapons']:
            capacity = random.randint(4, 8)
            for _ in range(capacity):
                hp = random.randint(1, 10)
                damage = random.randint(1, 10)
                protection = random.randint(1, 10)
                object_instance = Weapon(name=armor_name,
                                         hp=hp,
                                         damage=damage,
                                         protection=protection)
                self.objects_map['weapons'].append(object_instance)

        for person_name in names_list['persons']:
            hp = random.randint(1, 10)
            damage = random.randint(1, 10)
            protection = random.randint(1, 10)
            is_paladin = random.randint(1, 2) == 2
            object_instance = Paladin(name=person_name, hp=hp, damage=damage, protection=protection) if is_paladin \
                else Warrior(name=person_name, hp=hp, damage=damage, protection=protection)
            self.objects_map['persons'].append(object_instance)

        return self.objects_map
Beispiel #14
0
 def __init__(self, default_name, path, bonus, unwieldiness, pref_id=None):
     Thing.__init__(self, default_name, path, pref_id)
     self.bonus = bonus
     self.unwieldiness = unwieldiness
     self.actions.append(Action(self.wear, ['wear', 'use'], True, False))
     self.actions.append(
         Action(self.unwear, ['unwear', 'remove'], True, False))
     # overwrite default drop action:
     for a in self.actions:
         if 'drop' in a.verblist:
             a.func = self.armor_drop
    def __init__(self):
        Thing.__init__(self, 'urn:dev:ops:my-pycom-pysense', 'My Pycom',
                       ['RGBLed', 'memory'], 'A web connected Pycom')

        self.color = 0  #0 is no light, 20 is very light blue #0xff00 #green
        self.updateLeds()
        self.mempycom = Value(0.0)
        self.seconds = 0

        self.__alarm = Timer.Alarm(self._seconds_handler, s=10, periodic=True)
        #self._alarm = Timer.Alarm(updateMemPycom, 1, arg=None, periodic=True)

        self.add_property(
            Property(self,
                     'mempycom',
                     self.mempycom,
                     metadata={
                         '@type': 'SystemParameter',
                         'title': 'Memory',
                         'type': 'number',
                         'description': 'The free RAM of the system',
                     }))
        self.add_property(
            Property(self,
                     'color',
                     Value(self.color, self.setcolor),
                     metadata={
                         '@type': 'ColorProperty',
                         'title': 'Color',
                         'type': 'integar',
                         'description': 'The color of the LED',
                     }))

        self.add_available_action(
            'setrgbcolor',
            {
                'title': 'Change Color',
                'description': 'Change the color of LED',
                'input': {
                    'type': 'object',
                    'required': [
                        'color',
                    ],
                    'properties': {
                        'color': {
                            'type': 'integer',
                            'minimum': 0,
                            'maximum': 0xFFFFFF,
                            #'unit': 'percent',
                        },
                    },
                },
            },
            SetRGBColor)
Beispiel #16
0
 def __init__(self, ID, path, hidden_room):
     Thing.__init__(self, ID, path)
     self.set_description('bookcase full of books', \
     'This bookcase is a hodgepodge of books; some are newer, but a lot of old ones are scattered around them.')
     # we want this to trigger if they type, for example, "take old book"
     self.add_names("book")
     self.add_adjectives("old", "new")
     self.fix_in_place("The bookcase appears to be fixed to the wall.")
     self.actions.append(
         Action(self.handle_book, ["take", "get", "pull"], True, False))
     self.hidden_room = hidden_room
Beispiel #17
0
def pair():
    thing = request.form['thing']

    # check if the authenticated user has already paired with this thing
    if len(filter(lambda x: x.name == thing, current_user.things)) > 0:
        return jsonify(success=True)

    # TODO: implement secure pairing via a pairing code
    # Will involve fetching the pairing code from the thing's shadow state
    # code = request.form['code']

    # create the policy that gives the authenticated user access to the thing
    policy = {
        'Version':
        '2012-10-17',
        'Statement': [{
            'Effect':
            'Allow',
            'Action': [
                'iot:UpdateThingShadow', 'iot:GetThingShadow',
                'iot:DeleteThingShadow'
            ],
            'Resource':
            Thing.fullyQualifiedName(thing)
        }]
    }

    policyName = str(current_user.id) + '_' + thing

    iot = boto3.client('iot')

    try:
        r = iot.create_policy(policyName=policyName,
                              policyDocument=json.dumps(policy))
    except ClientError as e:
        logger.debug('pair: Error creating policy: {}'.format(e))
        return jsonify(success=False)

    # attach the policy to the authenticated user
    try:
        iot.attach_principal_policy(policyName=policyName,
                                    principal=current_user.cognitoID)
    except ClientError as e:
        logger.debug(
            'pair: Error attaching policy {} to principal {}: {}'.format(
                policyName, current_user.cognitoID, e))
        return jsonify(success=False)

    current_user.things.append(Thing(name=thing))
    db.session.commit()

    return jsonify(success=True)
Beispiel #18
0
def main():
    names = ["Paul", "Simon", "Art"]
    things = []
    for name in names:
        things.append(Thing(name))

    another = Thing("Garfunkel", 7)
    things.append(another)

    for i in range(len(things)):
        print("{}. {}.".format(i, things[i]))
        things[i].process(i)
        print("{}. {}.".format(i, things[i]))
        print("...")
Beispiel #19
0
 def __init__(self, default_name, path, pref_id=None):
     Thing.__init__(self, default_name, path, pref_id)
     self.contents = []
     self.see_inside = True  # can contents of container be seen?
     self.closed = False  # can't remove items from closed container
     self.closed_err = ""  # custom "container is closed" error msg
     self.closable = False  # can this container be opened and closed?
     self.liquid = False  # can this container carry liquid?
     self.max_weight_carried = 1
     self.max_volume_carried = 1
     self.insert_prepositions = ["in", "into", "inside"]
     self.actions.append(Action(self.put, ["put", "insert"], True, False))
     self.actions.append(Action(self.remove, ["remove"], True, False))
     self.actions.append(Action(self.open, ["open"], True, False))
     self.actions.append(Action(self.close_action, ["close"], True, False))
    def test_add_thing(self):
        t = Thing("some name", 10)
        s = Suitecase(100)

        s.add_thing(t)

        self.assertEqual("1 thing (10kg)", s.to_string())
Beispiel #21
0
    def get_next_brick(self):
        brick = Thing("brick", self._brick_weight)

        if self._brick_weight < 100:
            self._brick_weight += 1

        return brick
Beispiel #22
0
def put_thing(url, thing):
    res = requests.post(
              '{0}/things'.format(url),
              data=str(thing),
              headers={'Content-Type': 'application/json'})
    res.raise_for_status()
    return Thing.from_json(res.json())
Beispiel #23
0
    def __init__(self, *args, **kwargs):
        self.__dict__['__initializing__'] = True

        super(ThingModel, self).__init__(*args, **kwargs)

        self.__dict__['data'] = Thing(self.json_data)
        self.__dict__['__initializing__'] = False
Beispiel #24
0
    def move_towards(self, turn_summary, param, active=True):
        ''' For moving map actorss around. Calls hidden method of
            the same name in parent. Returns TurnSummary, with
            'TurnSummary.turn_taken' set to 'True' only if a
            voluntary move action was performed successfully.

                active: set to 'False' if movement is not voluntary
                        (the default case for Thing objects), it
                        defaults to 'True'
        '''
        turn_summary = Thing.move_towards(self, turn_summary, param, active)
        blocker = turn_summary.blocked_by
        
        if active:
            if blocker:
                # TODO: default attack
                logging.debug("[%r] bumps into [%s]" % (self, blocker.name))
            else:
                # Turn taken by moving
                self.time_to_act = 3
                turn_summary.turn_taken = True
                turn_summary.to_refresh_game_map_console = True
                logging.debug("[%r] moved successfully" % self)
        
        return turn_summary
Beispiel #25
0
 def fetch_all(page=1):
   page, last_page = page, Startup.num_pages()
   while page <= last_page:
     response = Thing.api().get('startups', {'filter': 'raising', 'page': page})
     page = response['page'] + 1
     for startup in response['startups']:
       yield Startup(startup)
Beispiel #26
0
def thrust_damage(a):
    a.attack_type = THRUST
    st = a.attacker.ST
    a.damage = Thing()
    a.damage.dice += 1 if st < 19 else 2
    a.damage.mod = (-1 if st > 18 else int((st - 1) / 2) - 6)
    return a
    def __init__(self, pin):
        Thing.__init__(self, 'Button 0', ['BinarySensor'],
                       'Button 0 on SparkFun ESP32 Thing')
        self.pin = machine.Pin(pin, machine.Pin.IN)

        self.button = Value(False)
        self.add_property(
            Property(self,
                     'on',
                     self.button,
                     metadata={
                         'type': 'boolean',
                         'description': 'Button 0 pressed',
                         'readOnly': True,
                     }))
        self.prev_pressed = self.is_pressed()
Beispiel #28
0
def setup():
    test_thing = Thing(id='01',
                       token='aaaa',
                       name='aaaa')
    test_cloud = Cloud()
    assert test_cloud.connect(arguments="'wss' 'ws.knot.cloud' 443")
    return test_thing, test_cloud
    def __init__(self, rPin, gPin, bPin):
        Thing.__init__(
            self,
            "urn:dev:ops:esp32-rgb-led-1234",
            "ESP32-RGB-LED",
            ["OnOffSwitch", "Light", "ColorControl"],
            "RGB LED on ESP-Wrover-Kit",
        )
        self.pinRed = machine.Pin(rPin, machine.Pin.OUT)
        self.pinGreen = machine.Pin(gPin, machine.Pin.OUT)
        self.pinBlue = machine.Pin(bPin, machine.Pin.OUT)
        self.pwmRed = machine.PWM(self.pinRed)
        self.pwmGreen = machine.PWM(self.pinGreen)
        self.pwmBlue = machine.PWM(self.pinBlue)
        self.redLevel = 50
        self.greenLevel = 50
        self.blueLevel = 50
        self.on = False
        self.updateLeds()

        self.add_property(
            Property(
                self,
                "on",
                Value(True, self.setOnOff),
                metadata={
                    "@type": "OnOffProperty",
                    "title": "On/Off",
                    "type": "boolean",
                    "description": "Whether the LED is turned on",
                },
            )
        )
        self.add_property(
            Property(
                self,
                "color",
                Value("#808080", self.setRGBColor),
                metadata={
                    "@type": "ColorProperty",
                    "title": "Color",
                    "type": "string",
                    "description": "The color of the LED",
                },
            )
        )
Beispiel #30
0
 def __init__(self,
              default_name,
              path,
              damage,
              accuracy,
              unwieldiness,
              pref_id=None):
     Thing.__init__(self, default_name, path, pref_id)
     self.damage = damage
     self.accuracy = accuracy
     self.unwieldiness = unwieldiness
     self.actions.append(Action(self.wield, ['wield', 'use'], True, False))
     self.actions.append(Action(self.unwield, ['unwield'], True, False))
     # overwrite default drop action:
     for a in self.actions:
         if 'drop' in a.verblist:
             a.func = self.weapon_drop
Beispiel #31
0
    def test_add_suitecase(self):
        t = Thing("some name", 10)
        s = Suitecase(100)
        s.add_thing(t)

        c = Container(100)
        c.add_suitecase(s)

        self.assertEqual("1 suitecase (10kg)", c.to_string())
Beispiel #32
0
def cripple(a):
    if ((a.target.body.is_limb(a.location)
         and a.damage.injury >= int(a.target.HP / 2))
            or (a.target.body.is_extremity(a.location)
                and a.damage.injury >= int(a.target.HP / 3))):
        if not a.target.crippled:
            a.target.crippled = Thing()
        a.target.crippled[a.location] = True
        a.damage.cripple = a.location
    return a
Beispiel #33
0
def swing_damage(a):
    a.attack_type = SWING
    st = a.attacker.ST
    a.damage = Thing()
    a.damage.dice += 1 if st < 9 else int((st - 5) / 4)
    if st < 9:
        a.damage.mod += (-5 + int((st - 1) / 2))
    else:
        a.damage.mod += ((st - 1) % 4) - 1
    return a
Beispiel #34
0
class TestThing(TestCase):
    def setUp(self):
        self.thing = Thing(name='thing')
        self.action1 = Action.create(name='action1')
        self.action2 = Action.create(name='action2')
        self.thing.add_agent_role(verb='action1')

    def test_add_role(self):
        self.thing.add_agent_role(verb='action2')
        self.assertTrue(self.thing.is_valid_agent(self.action2))

    def test_is_valid_for_role(self):
        self.thing.add_role(Role.THEME, 'action2')
        self.assertTrue(self.thing.is_valid_for_role(Role.THEME, self.action2))
Beispiel #35
0
    def __init__(self, rPin, gPin, bPin):
        Thing.__init__(
            self,
            'urn:dev:ops:esp32-rgb-led-1234',
            'ESP32-RGB-LED',
            ['OnOffSwitch', 'Light', 'ColorControl'],
            'RGB LED on ESP-Wrover-Kit'
        )
        self.pinRed = machine.Pin(rPin, machine.Pin.OUT)
        self.pinGreen = machine.Pin(gPin, machine.Pin.OUT)
        self.pinBlue = machine.Pin(bPin, machine.Pin.OUT)
        self.pwmRed = machine.PWM(self.pinRed)
        self.pwmGreen = machine.PWM(self.pinGreen)
        self.pwmBlue = machine.PWM(self.pinBlue)
        self.redLevel = 50
        self.greenLevel = 50
        self.blueLevel = 50
        self.on = False
        self.updateLeds()

        self.add_property(
            Property(self,
                     'on',
                     Value(True, self.setOnOff),
                     metadata={
                         '@type': 'OnOffProperty',
                         'title': 'On/Off',
                         'type': 'boolean',
                         'description': 'Whether the LED is turned on',
                     }))
        self.add_property(
            Property(self,
                     'color',
                     Value('#808080', self.setRGBColor),
                     metadata={
                         '@type': 'ColorProperty',
                         'title': 'Color',
                         'type': 'string',
                         'description': 'The color of the LED',
                     }))
    def __init__(self):
        try:
            # initialize pygame
            pygame.init()

            # create a clock to limit the frames per second
            self.clock = pygame.time.Clock()

            # Set the width and the height of the screen and create the sceen 
            self.screen = pygame.display.set_mode((self.width, self.height))
            pygame.display.set_caption("Press start to play")

            # create player
            self.player = Thing((self.width >> 1), (self.height >> 1))

            # this variable is used to end the main loop
            self.done = 0
        except:
            raise error.Error("init engine")
class Engine:
    done = 0
    width = 1024
    height = 768
    clock = None
    screen = None

    def __init__(self):
        try:
            # initialize pygame
            pygame.init()

            # create a clock to limit the frames per second
            self.clock = pygame.time.Clock()

            # Set the width and the height of the screen and create the sceen 
            self.screen = pygame.display.set_mode((self.width, self.height))
            pygame.display.set_caption("Press start to play")

            # create player
            self.player = Thing((self.width >> 1), (self.height >> 1))

            # this variable is used to end the main loop
            self.done = 0
        except:
            raise error.Error("init engine")

    def main_loop(self):
        try:
            # start main loop
            while self.done != 1:

                # handle some events
                for event in pygame.event.get():
                    if event.type == pygame.VIDEORESIZE:
                        self.width = event.dict["size"][0]
                        self.height = event.dict["size"][1]
                        self.screen = pygame.display.set_mode((self.width, self.height))
                    elif event.type == pygame.QUIT:
                        self.done = 1

                # handle some key input
                keys_pressed = pygame.key.get_pressed()
                if keys_pressed[pygame.K_ESCAPE]:
                    self.done = 1
                dx = 0
                dy = 0
                if keys_pressed[pygame.K_w]:
                    dy -= 1
                if keys_pressed[pygame.K_s]:
                    dy += 1
                if keys_pressed[pygame.K_a]:
                    dx -= 1
                if keys_pressed[pygame.K_d]:
                    dx += 1
                if dx != 0 or dy != 0:
                    self.player.acclerate(dx, dy)

                # update objects
                self.player.update()

                # fill the screen with one color
                self.screen.fill((10, 10, 10))
            
                # render the scene
                pygame.draw.rect(self.screen, (255, 0, 0), (\
                                    self.player.position.x - 16, \
                                    self.player.position.y - 16, \
                                    32, 32), 1)

                # update the screen
                pygame.display.flip()

                # Limit the game loop to 60 ticks(frames) per second
                self.clock.tick(60)
        except:
            raise error.Error("main loop")

    def __del__(self):
        try:
            # release pygame
            pygame.quit()
        except:
            raise error.Error("del engine")
Beispiel #38
0
 def __init__(self, name, use, location=None, pin=0):
     Thing.__init__(self, name, use, location, pin)
Beispiel #39
0
__author__ = 'damariei'

from thing import Thing
from utils import genSeq

	
# Testing
t1 = Thing()
t1.construct(genSeq())
print('T1: '+t1.name)

t2 = Thing()
t2.construct(genSeq())
print('T2: '+t2.name)

print("Diff: "+str(t1.compareTo(t2.seq)))
 def num_pages():
   return Thing.api().get('startups', {'filter': 'raising', 'per_page': 1})['last_page']
Beispiel #41
0
 def __init__(self):
   Thing.__init__(self)
   self.style = "O" 
Beispiel #42
0
def get_thing(url, id):
    res = requests.get('{0}/things/{1}'.format(url, id))
    res.raise_for_status()
    return Thing.from_json(res.json())
Beispiel #43
0
 def __init__(self):
   Thing.__init__(self)
   self.at = {} 
   self.df = Dexterity 
   self.dm = Strength 
Beispiel #44
0
 def __init__(self, width, height, mass, surface=pygame.Surface((0,0)), speedlimit=2):
     Thing.__init__(self, width, height, mass, speedlimit=2)
     self.surface.fill((127,127,127))
     self.mass = 2
     self.gravity = False
Beispiel #45
0
 def init (self):
     # don't allow reset when paused or already won
     if self.paused or self.transition:
         return
     data = conf.LEVEL_DATA[self.ID]
     self.run_timer = 0
     self.kills = 0
     self.won = False
     self.particles = []
     # background
     self.bg = self.game.img('bg{0}.png'.format(self.ID))
     # player
     s = self.space
     if not hasattr(self, 'player'):
         self.player = Player(self, data['start'])
     # doors
     try:
         s.remove_static(self.exit_shape)
     except AttributeError:
         pass
     else:
         self.player.reset(data['start'])
     self.entrance = data['entrance']
     a, b = self.exit = data['exit']
     self.exit_shape = l = pm.Segment(s.static_body, a, b, conf.LINE_RADIUS)
     l.group = conf.SHAPE_GROUP
     l.layers = conf.DOOR_LAYER
     l.sensor = True
     s.add_static(l)
     # things
     try:
         for t in self.things:
             t.die()
     except AttributeError:
         pass
     self.things = []
     ts = self.things
     for p, d, ai in data['things']:
         t = Thing(self, p, d, ai)
         t.dead = False
         ts.append(t)
     # static shapes
     try:
         for shape in self.shapes_shapes:
             s.remove_static(shape)
     except AttributeError:
         pass
     self.shapes = [((0, 0), (1000, 0)), ((1000, 0), (1000, 540)), ((0, 500), (1000, 500)), ((0, 0), (0, 500))]
     self.shapes += data['shapes']
     self.shapes_shapes = ss = []
     rm = []
     for pts in self.shapes:
         if pts[1] is False:
             rm.append(pts)
             pts = pts[0]
         if len(pts) == 2:
             p = pm.Segment(s.static_body, pts[0], pts[1], conf.LINE_RADIUS)
         else:
             p = pm.Poly(s.static_body, pts)
         p.friction = conf.SHAPE_FRICT
         p.elast = conf.SHAPE_ELAST
         p.group = conf.SHAPE_GROUP
         p.layers = conf.COLLISION_LAYER
         s.add_static(p)
         ss.append(p)
     for pts in rm:
         self.shapes.remove(pts)
     self.shape_colour = data['shape_colour']
     # messages
     msgs = data['msg']
     if msgs[0] is None:
         self.msgs = []
         self.msg = None
     else:
         self.msgs = list(msgs[:-1])
         self.msg = 0
     self.end_msg = msgs[-1]
     self.msg_colour = data['msg_colour']
     self.msg_arrow = self.game.img('arrow{0}.png'.format(data['msg_arrow']))
     # music
     try:
         music = data['music']
     except KeyError:
         self.game.music = []
         self.game.play_music()
     else:
         try:
             if music != self.music:
                 raise AttributeError()
         except AttributeError:
             self.music = music
             self.game.find_music(str(music))
             self.game.play_music()
     # triggers
     try:
         s.remove_static(*self.trigger_shapes)
     except AttributeError:
         pass
     trigger_data = data.get('triggers', [])
     self.triggers = ts = []
     self.trigger_shapes = tss = []
     for pts, cb in trigger_data:
         ts.append(cb)
         shape = pm.Poly(s.static_body, pts)
         shape.group = conf.SHAPE_GROUP
         shape.layers = conf.TRIGGER_LAYER
         shape.sensor = True
         s.add_static(shape)
         tss.append(shape)
     self._triggers = []