Exemple #1
0
 def __init__(self):
     try:
         self.every_req = [self.unit, self.task]
         self.every_1 = [self.auction]
         self.every_5 = []
         self.every_15 = [self.msg_notify]
     except Exception, e:
         logging.error('Daemon error %s' % e)
Exemple #2
0
 def get_all_cities(self, user=None, user_id=None):
     if user is not None:
         return self.filter(user=user)
     elif user_id is not None:
         return self.filter(user__id=user_id)
     else:
         logging.error("user and user_id is None in city.models.get_all_cities :(")
         return ()
Exemple #3
0
    def decrease(self, type, amt):
        items = self.items
        try:
            items[type] -= amt
        except KeyError:
            logging.error('Cannot decrease %s' % str(type))
            return

        self.item = json.dumps(items)
        self.save()
Exemple #4
0
    def upgrade(self, which='first'):
        if which == 'first':
            if self.first_level < settings.PRODUCT_MAX_UPGRADE_LEVEL:
                self.first_level += 1
        elif which == 'first':
            if self.second_level < settings.PRODUCT_MAX_UPGRADE_LEVEL:
                self.second_level += 1
        else:
            logging.error('Tried to upgrade %s' % str(which))
            return

        self.save()
Exemple #5
0
    def _unit_move(self):
        qualify_tasks = query(
            "SELECT user_id, unit FROM city_move WHERE next_at<=NOW() + INTERVAL 1 MINUTE AND unit!=''")

        for task in qualify_tasks.fetchall():

            for group in json.loads(task[1]):
                if group[3] > int(time.time()): continue

                units_move = MapMove.objects.get_by_user(user_id=task[0])
                units_move_group = MapMoveGroup.objects.get_by_id(group[2])

                from_units = CityUnit.objects.get_by_user(city_id=group[0], user_id=task[0])
                to_units = CityUnit.objects.get_by_user(city_id=group[1], user_id=task[0])

                engine = Engine(DummyRequest(task[0]))
                engine.city.id = group[1]
                engine.city.set_action_type('unit')

                try:
                    for unit_id, unit_cnt in units_move_group.units.iteritems():
                        to_units.add_unit(unit_id, unit_cnt)
                        from_units.rem_unit(unit_id, unit_cnt)

                        engine.stream.post('unit_moved', '%s|<a href="%s">%s</a>' % (
                        engine.city.UNIT[engine.city.all_unit[str(unit_id)].name],
                        reverse('city_enter', args=[group[1]]), engine.city.city_map.name))
                        logging.debug('%s unit moved' % engine.user.user)

                    units_move_group.delete()

                    new_list = [x for x in units_move.units if x[3] > int(time.time())]
                    units_move.unit = json.dumps(new_list)
                    if len(new_list) > 0:
                        units_move.next_at = datetime.datetime.fromtimestamp(min([x[3] for x in new_list]))
                        units_move.save()
                    else:
                        try:
                            units_move.delete()
                        except AssertionError:
                            continue

                except AttributeError:
                    logging.error(
                        'Problem with moving units. %s, %s. AttErr' % (str(units_move), str(units_move_group)))
Exemple #6
0
    def _task(self):
        def execute(engine, module, method, params):
            engine.register(module)
            engine.__dict__[module].__getattribute__(method)(*params)

        available_actions = ('engine', 'sql', 'city')

        crs = query('SELECT id, user_id, task, comment, source FROM task WHERE run_at <= NOW() ORDER BY run_at')
        rows = crs.fetchall()

        for row in rows:
            # Archive
            query(
                """INSERT INTO archive.crims_task_archive (user_id, task, comment, source) VALUES ("%s", "%s", "%s", "%s")""" % (
                row[1], row[2], row[3], row[4]), True)

            if row[4] == 'sql':
                sql(task)
                continue

            if row[4] == 'city':
                city_id = row[2]

                cache.delete('city_building_%s' % city_id)
                profile = UserProfile.objects.get_by_id(user_id=row[1])
                if profile is None: continue

                r = CityRefresh(profile, city_id)
                r.do_refresh()
                continue

            engine = Engine(DummyRequest(row[1]))

            try:
                module, method, params = row[2].split('|')
                params = params.split(',')

                execute(engine, module, method, params)
            except ValueError:
                logging.error("Error executing wait job %s for %s" % (row[2], engine.user.user))

        if len(rows) > 0: query("DELETE FROM task WHERE id IN (%s)" % ','.join(["%s" % str(x[0]) for x in rows]), True)
Exemple #7
0
    def do_tribute(self, bld_type, bld_owner):
        import random
        from crims.city.models import CityUnit
        from crims.common.helpers._crims import fight

        if self.engine.city.city_unit.next_tribute_at > datetime.datetime.now():
            self.engine.log.message(message=_("Can do this right now"))
            return

        try:
            ids = self.city_building.items[bld_type][bld_owner]
        except KeyError:
            logging.error('No bld_type:%s or bld_owner:%s in city_building.items' % (str(bld_type), str(bld_owner)))
            self.engine.log.message(message=_("Error"))
            return

        try:
            job = self.all_tribute[str(random.choice(ids))]
        except KeyError, ValueError:
            logging.error('No tribute_id')
            self.engine.log.message(message=_("Error"))
            return
Exemple #8
0
    def has_enough(self, type, num):
        """Czy user ma wystarczajaca ilosc danych obiektow"""
        if type in (
            "cash",
            "credit",
            "base_attack",
            "base_respect",
            "base_defense",
            "total_attack",
            "total_defense",
            "total_respect",
            "team_attack",
            "team_defense",
            "team_respect",
            "bdp",
            "bdp_level",
        ):
            try:
                if int(self.__dict__[type]) >= int(num):
                    return True
                else:
                    return False
            except KeyError:
                logging.error("No attribute type: %s" % type)
                return False

                # elif type == 'respect':
                # 	try:
                # 		if int(self.base_respect) <= int(num) + int(self.base_respect):
                # 			return True
                # 		else:
                # 			logging.debug('Respect too low')
                # 			return False
                # 	except ValueError:
                # 		logging.debug('Respect value error')
                return False

        elif type == "heat":
            try:
                if int(self.heat) <= int(num) + int(self.heat):
                    return True
                else:
                    return False
            except ValueError:
                logging.error("Heat value error")
                return False

        # elif type == 'level':
        # 	logging.debug('Has not enough %s' % type)
        # 	return True
        #
        # elif type == 'members':
        # 	logging.debug('Has not enough %s' % type)
        # 	return True

        else:
            logging.error("Unsupported type: %s" % type)
            raise NotImplementedError
Exemple #9
0
    def get_by_id(self, user_id=None, username=None):
        if user_id is not None:
            key = "user_%s" % user_id

            item = cache.get(key)
            if item is not None:
                return pickle.loads(str(item))
        else:
            key = None

        try:
            if username is not None:
                item = self.get(username__iexact=username)
            elif user_id is not None:
                item = self.get(user__id=user_id)
            else:
                logging.error("UserProfile not found. USER:%s, ID:%s" % (str(user), str(user_id)))
                return None

        except UserProfile.DoesNotExist:
            return None

        cache.set(key or "user_%s" % item.user.id, pickle.dumps(item))
        return item
Exemple #10
0
    def earn(self, type, num, autosave=True):
        """Dodaje obiekty do profilu"""
        if type in ("cash", "credit", "heat"):
            try:
                # logging.debug('%s just earned %s %s' % (self.user, num, type))
                try:
                    self.__dict__[type] += int(num)
                except TypeError:
                    logging.error("Blad przy przypisywaniu wartosci")
                    return False

                if autosave:
                    self.save()
                return True

            except KeyError:
                logging.error("No type: %s" % type)
                return False

        logging.error("Unsupported type: %s" % type)
        return False
Exemple #11
0
    def move_owner(self, bld_type, bld_id, curr_owner, new_owner):
        bld_type, bld_id, curr_owner, new_owner, items = str(bld_type), str(bld_id), str(curr_owner), str(
            new_owner), self.items

        if not items.has_key(bld_type):
            logging.error('No building_type %s' % bld_type)
            return False
        if not items[bld_type].has_key(curr_owner):
            logging.error('%s is not owner of %s:%s' % (curr_owner, bld_type, bld_id))
            return False
        if bld_id not in items[bld_type][curr_owner]:
            logging.error('%s:%s:%s not in the city' % (bld_type, curr_owner, bld_id))
            return False

        del items[bld_type][curr_owner][items[bld_type][curr_owner].index(bld_id)]
        if len(items[bld_type][curr_owner]) == 0: del items[bld_type][curr_owner]

        if not items[bld_type].has_key(new_owner):
            items[bld_type][new_owner] = []
        items[bld_type][new_owner].append(bld_id)

        self.item = json.dumps(items)
        self.save()
        return True
Exemple #12
0
 def save(self, force_insert=False):
     try:
         super(UserProfile, self).save(force_insert=force_insert)  # Call the "real" save() method
     except Exception, e:
         logging.error("Error saving profile %s" % e)
Exemple #13
0
    def set_action_type(self, action_type):

        if action_type == 'map':
            pass

        elif action_type == 'unit':
            from crims.city.models import Unit, CityUnitProgress

            if self.id is None: logging.error('city_id not set up')

            self.UNIT = {
                'bum': _('Bum'), 'student': _('Student'), 'karate_kid': _('Karate Kid'), 'wrestler': _('Wrestler'),
            'rookie': _('Rookie'), 'soldier': _('Soldier'), 'navy_seals': _('Navy Seals'),
            'chuck_norris': _('Chuck Norris')
            }

            self.all_unit = {}
            for item in Unit.objects.get_all():
                self.all_unit[str(item.id)] = item

            self.city_unit = CityUnit.objects.get_by_user(city_id=self.id, user=self.engine.user.user)
            self.city_unit_progress = CityUnitProgress.objects.get_by_user(city_id=self.id, user=self.engine.user.user)
            self.build_queue = []
            for unit in self.city_unit_progress.units:
                u = copy_model_instance(self.all_unit[str(unit[0])])
                u.ready_at = datetime.datetime.fromtimestamp(unit[1])
                self.build_queue.append(u)

        elif action_type == 'tribute':
            from crims.job.models import JobTribute

            if self.id is None: logging.error('city_id not set up')

            self.TRIBUTE = {
                'cafe': _('Cafe'), 'club': _('Club'), 'gas_station': _('Gas Station'), 'hotel': _('Hotel'),
            'liquor': _('Liquor Store'), 'pub': _('Pub'), 'restaurant': _('Restaurant'),
            'transport_company': _('Transport Company')
            }

            self.all_tribute = JobTribute.objects.get_all()

            user = str(self.engine.user.user)
            self.user_tribute = {}
            for bld_type, bld_owners in self.city_building.items.iteritems():
                self.user_tribute[bld_type] = []
                total_blds = float(sum([len(x) for x in bld_owners.itervalues()]))

                if bld_owners.has_key('0'):
                    self.user_tribute[bld_type].append(
                        ['0', len(bld_owners['0']), "%3.2f" % (len(bld_owners['0']) / total_blds * 100)])
                    del bld_owners['0']
                if bld_owners.has_key(user):
                    self.user_tribute[bld_type].append(
                        ['me', len(bld_owners[user]), "%3.2f" % (len(bld_owners[user]) / total_blds * 100)])
                    del bld_owners[user]

                if len(bld_owners.keys()) == 0: continue

                backitems = [[len(y), x] for x, y in bld_owners.items()]
                backitems.reverse()
                sorted_bld_owners = [backitems[i] for i in range(0, len(backitems))]

                for blds, bld_owner in sorted_bld_owners:
                    self.user_tribute[bld_type].append([bld_owner, blds, "%3.2f" % ((blds / total_blds) * 100)])

        elif action_type == 'production':
            from crims.city.models import Product, CityProduct, CityProductProgress, UserProduct

            if self.id is None: logging.error('city_id not set up')

            self.user_product = UserProduct.objects.get_by_user(user=self.engine.user.user)
            self.city_product = CityProduct.objects.get_by_city(city_id=self.id)

            self.all_product = {}
            for item in Product.objects.get_by_type(self.city_product.first):
                if not self.all_product.has_key(item.type): self.all_product[item.type] = {}
                self.all_product[item.type][item.name] = item

            if (self.city_product.second != ''):
                for item in Product.objects.get_by_type(self.city_product.second):
                    if not self.all_product.has_key(item.type): self.all_product[item.type] = {}
                    self.all_product[item.type][item.name] = item

            self.city_product_progress = CityProductProgress.objects.get_by_city(city_id=self.id)
            self.build_queue = []
            for item in self.city_product_progress.items:
                u = self.all_product[str(item[0])][str(item[1])]
                u.amount = int(item[2])
                u.ready_at = datetime.datetime.fromtimestamp(item[3])
                self.build_queue.append(u)
Exemple #14
0
                    reverse('profile', args=[bld_owner, ]), bld_owner, bld_type, job.name,
                    reverse('city_enter', args=[self.id, ]), self.city_map.name))
                    # self.engine.stream.post('city_defense_lost', '')
                    self.engine.stream.post_to_city_wall('city_new_bld_owner',
                                                         '%s|%s|<a href="%s">%s</a>|<a href="%s">%s</a>' % (
                                                         bld_type, job.name,
                                                         reverse('profile', args=[bld_owner_name, ]), bld_owner_name,
                                                         reverse('profile', args=[self.engine.user.user, ]),
                                                         self.engine.user.user), city_id=self.id, is_public=True)
                    self.engine.stream.trigger('building_defense_failed', user=bld_owner_name)

                attacker.next_tribute_at = datetime.datetime.now() + datetime.timedelta(hours=2)
                attacker.save()

            else:
                logging.error('Problem with moving building owner...')  # TODO: more info
                self.engine.log.message(message=_("Error"))

        else:
            self.engine.stream.trigger('building_attack_failed')
            if bld_owner != '0':
                self.engine.stream.trigger('building_defense_done',
                                           user=self.engine.user.get_by_id(username=bld_owner).user)

        if result[1] > 0:
            attacker.kill_units(result[1])
            self.engine.stream.trigger('city_units_lost', result[1])
        if result[2] > 0 and bld_owner != '0':
            defender.kill_units(result[2])
            self.engine.stream.trigger('city_units_lost', result[2],
                                       user=self.engine.user.get_by_id(username=bld_owner).user)
Exemple #15
0
            self.all_slots[slot_no][to_alloc] = int(bld)

            # new slot_no based on new density
            lvl = self._get_density_lvl(self.density, self.density[slot_no])

            if lvl > self._get_density_lvl(self.density) + 1:
                slot_no = self.density.index(min(self.density))

    def _get_density_lvl(self, density, for_min=None):
        curr_min = for_min or min(density)
        if curr_min < .6:         return 1
        if .6 <= curr_min < .7:  return 2
        if .7 <= curr_min < .85: return 3
        return 4


if __name__ == '__main__':
    from django.contrib.auth.models import User
    from crims.userprofile.models import UserProfile

    for user in User.objects.filter(is_active=True):
        profile = UserProfile.objects.get_by_id(user_id=user.id)
        if profile is not None:
            r = CityRefresh(profile)
            r.do_refresh()
        else:
            logging.error('Disabling %s due to no profile' % user)
            user.is_active = False
            user.save()