Ejemplo n.º 1
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
Ejemplo n.º 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 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())
    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())
    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
Ejemplo n.º 6
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("...")
Ejemplo n.º 7
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
Ejemplo n.º 8
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
Ejemplo n.º 9
0
    def get_next_brick(self):
        brick = Thing("brick", self._brick_weight)

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

        return brick
Ejemplo n.º 10
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 test_add_thing(self):
        t = Thing("some name", 10)
        s = Suitecase(100)

        s.add_thing(t)

        self.assertEqual("1 thing (10kg)", s.to_string())
Ejemplo n.º 12
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())
Ejemplo n.º 13
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
Ejemplo n.º 14
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
Ejemplo n.º 15
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
Ejemplo n.º 16
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)
Ejemplo n.º 17
0
def init_character(**kwargs):
    params = {
        'ST': 10,
        'DX': 10,
        'IQ': 10,
        'HT': 10,
        'skills': {},
        'body': Humanoid,
        'can_defend': True,
    }
    params['HP'] = params['HT']
    params.update(kwargs)
    return Thing(**params)
Ejemplo n.º 18
0
    def __init__(self, mqttc, cfg, backlight_cb=None, **kwargs):
        super(SmartPanelWidget, self).__init__(**kwargs)

        self.backlight_cb = backlight_cb

        self.cfg = cfg

        self.mqtt = mqttc

        # Initialize the things
        self.things = []
        for sec in filter(lambda s: s.startswith("Thing:"),
                          self.cfg.sections()):
            section = sec[6:]
            pos_x = int(self.cfg.get("Thing:" + section, "posX"))
            pos_y = int(self.cfg.get("Thing:" + section, "posY"))

            t = Thing(section, self.cfg, self.mqtt, self, pos=(pos_x, pos_y))
            self.things.append(t)
            self.add_widget(t)

        self.IMGDIR = "resources/nixie/"
        clock_pos = (0, 220)

        self.clock = ClockWidget(self.cfg,
                                 self.IMGDIR,
                                 pos=clock_pos,
                                 touch_cb=None)
        self.add_widget(self.clock)

        self.player = PlayerWidget(self.cfg, self.mqtt, pos=(330, 0))
        self.add_widget(self.player)

        self.fav = FavButtonWidget(self.cfg, self.mqtt, pos=(700, 220))
        self.add_widget(self.fav)

        self.environment = EnvironmentWidget(self.cfg,
                                             self.mqtt,
                                             pos=(330, 220))
        self.add_widget(self.environment)

        if "WifiRepeater" in self.cfg.sections():
            self.wifi_repeater = WifiRepeater(self.cfg,
                                              self.mqtt,
                                              pos=(700, 380))
            self.add_widget(self.wifi_repeater)
Ejemplo n.º 19
0
 def f(x=None):
     if x is None:
         x = Thing()
     flist = functions
     while len(flist) > 0:
         deferred = []
         stuck = True
         for function in flist:
             try:
                 x = function(Branch(x)).commit()
                 stuck = False
             except (AttributeError, KeyError):
                 deferred.append(function)  #not ready yet
         if stuck:
             x = deferred[0](x)  #should raise AttributeError
         flist = deferred  #try again with what is left
     return x
Ejemplo n.º 20
0
    def message(self, msg):
        """
        Process incoming message stanzas. Be aware that this also
        includes MUC messages and error messages. It is usually
        a good idea to check the messages's type before processing
        or sending replies.

        Arguments:
            msg -- The received message stanza. See the documentation
                   for stanza objects and the Message stanza to see
                   how it may be used.
        """

        jid_full = msg['from']
        jid_bare = msg['from'].bare

        #check only on bare username
        if not jid_bare in self.config.allowed_users:
            return

        if msg['type'] in ('chat', 'normal'):
            #Strip whitespace, split on space and keep only the first portion
            message = msg['body'].strip().split(" ")[0]

            thing = Thing(message)
            #Check which worker can handle the link, the first that can wins
            #and the loop stops
            tentacle_found = False
            for t, q in self.cur_tentacles:
                if t.supports(thing):
                    logging.debug("%s supports %s" %
                                  (t.__class__, thing.url.href()))
                    self._start_sched_out_queue()
                    #We get the jid before replying, to keep the original jid
                    reply_to = self.get_jid(msg)
                    msg.reply(random.choice(CONFIRM)).send()
                    q.put((reply_to, thing))
                    self.num_cur_downloads += 1
                    tentacle_found = True
                    break

            if not tentacle_found:
                logging.debug("No valid tentacles found for processing %s" %
                              message)
                msg.reply(random.choice(UNRECOGNIZED)).send()
Ejemplo n.º 21
0
from fleet import Fleet
from thing import Thing

getMilk=Thing("Get milk")
getMilk.complete()
removeObs=Thing("Remove the obstacles")
removeObs.complete()
standUp=Thing("Stand up")
eatLunch=Thing("Eat lunch")
fleet = Fleet()
fleet.add(getMilk)
fleet.add(removeObs)
fleet.add(standUp)
fleet.add(eatLunch)
# Create a fleet of things to have this output:
# 1. [ ] Get milk
# 2. [ ] Remove the obstacles
# 3. [x] Stand up
# 4. [x] Eat lunch

print(fleet)
Ejemplo n.º 22
0
def make_thing():
    thing = Thing('My Lamp', ['OnOffSwitch', 'Light'], 'A web connected lamp')

    thing.add_property(
        Property(thing,
                 'on',
                 Value(True),
                 metadata={
                     '@type': 'OnOffProperty',
                     'title': 'On/Off',
                     'type': 'boolean',
                     'description': 'Whether the lamp is turned on',
                 }))
    thing.add_property(
        Property(thing,
                 'brightness',
                 Value(50),
                 metadata={
                     '@type': 'BrightnessProperty',
                     'title': 'Brightness',
                     'type': 'integer',
                     'description': 'The level of light from 0-100',
                     'minimum': 0,
                     'maximum': 100,
                     'unit': 'percent',
                 }))

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

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

    return thing
from fleet import Fleet
from thing import Thing

fleet = Fleet()

# Töltsd fel a fleet példányt olyan módon, hogy a következő legyen a kimenet:
# 1. [ ] Get milk
# 2. [ ] Remove the obstacles
# 3. [x] Stand up
# 4. [x] Eat lunch

fleet.add(Thing('Get milk'))
fleet.add(Thing('Remove the obstacles'))
thing2 = Thing('Stand up')
thing2.complete()
fleet.add(thing2)
thing3 = Thing('Eat lunch')
thing3.complete()
fleet.add(thing3)

print(fleet)
Ejemplo n.º 24
0
def make_thing():
    thing = Thing(
        "urn:dev:ops:my-lamp-1234",
        "My Lamp",
        ["OnOffSwitch", "Light"],
        "A web connected lamp",
    )

    on_property = Property(
        thing,
        "on",
        writeproperty=lambda v: print(v),
        initial_value=True,
        metadata={
            "@type": "OnOffProperty",
            "title": "On/Off",
            "type": "boolean",
            "description": "Whether the lamp is turned on",
        },
    )

    brightness_property = Property(
        thing,
        "brightness",
        writeproperty=lambda v: print(v),
        initial_value=50,
        metadata={
            "@type": "BrightnessProperty",
            "title": "Brightness",
            "type": "integer",
            "description": "The level of light from 0-100",
            "minimum": 0,
            "maximum": 100,
            "unit": "percent",
        },
    )

    thing.add_property(on_property)
    thing.add_property(brightness_property)

    def fade_function(args):
        time.sleep(args["duration"] / 1000)
        brightness_property.set_value(args["brightness"])

    fade_action = Action(
        thing,
        "fade",
        invokeaction=fade_function,
        metadata={
            "title": "Fade",
            "description": "Fade the lamp to a given level",
            "input": {
                "type": "object",
                "required": [
                    "brightness",
                    "duration",
                ],
                "properties": {
                    "brightness": {
                        "type": "integer",
                        "minimum": 0,
                        "maximum": 100,
                        "unit": "percent",
                    },
                    "duration": {
                        "type": "integer",
                        "minimum": 1,
                        "unit": "milliseconds",
                    },
                },
            },
        },
    )

    thing.add_action(fade_action)

    return thing
Ejemplo n.º 25
0
import yaml

from algorithm import PartialSwarmOptimization
from room import Room
from thing import Thing
from visualization_utils import RoomDrawer

if __name__ == "__main__":
    room = Room(400, 400)

    with open('room.yml') as f:
        data = yaml.safe_load(f)
        things = [Thing(**v) for v in data.values()]

        for thing in things:
            room.add_thing(thing)

        pso = PartialSwarmOptimization(room, -100, 100)
        pso.find_best_solution(partials=20, iterations=100)

        room.set_thing_positions(pso.global_solution)
        drawer = RoomDrawer(room)
        drawer.show()
Ejemplo n.º 26
0
# Create a fleet of things to have this output:
# 1. [ ] Get milk
# 2. [ ] Remove the obstacles
# 3. [x] Stand up
# 4. [x] Eat lunch

from fleet import Fleet
from thing import Thing

fleet = Fleet()

item_1 = Thing("Get milk")
print(item_1)
item_2 = Thing("Remove the obstacles")
print(item_2)
item_3 = Thing("Stand up")
item_3.complete()
print(item_3)
item_4 = Thing("Eat Lunch")
item_4.complete()
print(item_4)

print(fleet)
Ejemplo n.º 27
0
def thing():
    return Thing("Bob")
Ejemplo n.º 28
0
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from thing import Thing, Base

engine = create_engine('sqlite:///stuffbot.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()

new_thing = Thing('001', "18L Really Useful Box")
session.add(new_thing)

the_banner = Thing('000', "The banner", parent=new_thing)
session.add(the_banner)

session.commit()
Ejemplo n.º 29
0
from thing import Thing


class Fleet(object):
    def __init__(self):
        self.things = []

    def add(self, thing):
        self.things.append(thing)

    def __str__(self):
        result = ""
        for i in range(0, len(self.things)):
            result += str(i + 1) + ". " + self.things[i].__str__() + "\n"
        return result


thing1 = Thing('Get milk')
thing2 = Thing('Remove the obstacles')
thing3 = Thing('Stand up')
thing4 = Thing('Eat lunch')
fleet = Fleet()
fleet.add(thing1)
fleet.add(thing2)
fleet.add(thing3)
fleet.add(thing4)
thing3.complete()
thing4.complete()
print(fleet)
Ejemplo n.º 30
0
    def __init__(self, filename, count):
        pygame.init()
        width = 500
        height = 500
        gameDisplay = pygame.display.set_mode((width, height))
        pygame.display.set_caption('Caption')
        clock = pygame.time.Clock()
        loop = True
        self.instances = []
        self.rects = []
        sector_count = math.ceil(math.sqrt(count))
        angle_increment_base = 1
        angle_increment = 0.0

        for i in range(count):
            instance = Thing(filename,
                             width=width,
                             height=height,
                             speed=1,
                             length=1,
                             pos_x=width / 2,
                             pos_y=height / 2)
            self.instances.append(instance)
            x = i % sector_count
            y = i // sector_count
            self.sector_width = round(min(width, height) / sector_count)
            self.rects.append(
                (x * self.sector_width, y * self.sector_width,
                 (x + 1) * self.sector_width, (y + 1) * self.sector_width))

        while loop:
            gameDisplay.fill((255, 255, 255))
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        loop = False
                    if event.key == pygame.K_RIGHT:
                        angle_increment = angle_increment_base
                    if event.key == pygame.K_LEFT:
                        angle_increment = -angle_increment_base
                    #if event.key == pygame.K_UP:
                    #    position_increment = position_increment_base
                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_RIGHT:
                        angle_increment = 0.0
                    if event.key == pygame.K_LEFT:
                        angle_increment = 0.0
                    #if event.key == pygame.K_UP:
                    #    position_increment = 0.0

            for i in range(count):
                instance = self.instances[i]
                instance.update(angle_increment)
                image = instance.GetImage()
                gameDisplay.blit(
                    pygame.transform.scale(
                        image, (self.sector_width, self.sector_width)),
                    self.rects[i])

            pygame.display.update()
            clock.tick(100)