Ejemplo n.º 1
0
    def do_skill(self, skill_type):
        try:
            skill = self.to_do_skill[skill_type]
        except KeyError:
            logging.warning('skill_type:%s does not exist' % skill_type)
            return

        if len(self.skills.queues) > 0:  # one queue for everyone?
            self.engine.log.message(message=_('You can\'t learn two things at the same time'))
            return

        if not self.profile.has_enough('cash', skill.cost):
            self.engine.log.message(message=_('Not enough cash'))
            return

        self.skills.queue = json.dumps(
            {skill.name: str(datetime.datetime.now() + datetime.timedelta(minutes=skill.time))[:19]})
        self.skills.save()
        self.profile.cash -= skill.cost
        self.profile.has_skills = True
        self.profile.save()

        logging.debug('%s: learning %s skill at lvl %s' % (self.user, skill.name, skill.level))
        self.engine.stream.trigger('skill_learn_start')
        self.engine.stream.trigger('skill_%d_learn_start' % int(skill.id))
        self.engine.log.message(message=_('Learning right now, come back later.'))

        return True
Ejemplo n.º 2
0
    def _unit_build(self):
        qualify_tasks = query(
            "SELECT user_id, city_id FROM city_unit_progress WHERE next_at<=NOW() + INTERVAL 1 MINUTE AND unit!=''")

        for task in qualify_tasks.fetchall():

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

            for unit in engine.city.city_unit_progress.units:
                if unit[1] > int(time.time()): continue

                engine.city.city_unit.add_unit(unit[0])

                engine.stream.post('unit_hired', '%s|<a href="%s">%s</a>' % (
                engine.city.all_unit[str(unit[0])].name, reverse('city_enter', args=[task[1]]),
                engine.city.city_map.name))
                logging.debug('%s unit hired' % engine.user.user)

            new_list = [x for x in engine.city.city_unit_progress.units if x[1] > int(time.time())]
            engine.city.city_unit_progress.unit = json.dumps(new_list)
            if len(new_list) > 0:
                engine.city.city_unit_progress.next_at = datetime.datetime.fromtimestamp(min([x[1] for x in new_list]))
                engine.city.city_unit_progress.save()
            else:
                engine.city.city_unit_progress.delete()
Ejemplo n.º 3
0
    def add_unit(self, id, cnt=1):
        units = self.units
        try:
            units[str(id)] += cnt
        except KeyError:
            units[str(id)] = cnt

        self.unit = json.dumps(units)
        self.save()
        logging.debug('add_unit id:%s, city:%s, user:%s' % (id, self.city_id, self.user))
        return True
Ejemplo n.º 4
0
    def activate(self, profile, bonus=None):
        if bonus is None:
            bonus = Bonus.objects.get_by_name(self.bonus_name)

        logging.debug("%s: activating %s" % (str(self.user), str(bonus.name)))

        self.start_at = datetime.datetime.now()
        self.end_at = datetime.datetime.now() + datetime.timedelta(hours=int(bonus.period))
        self.is_active = True
        self.save()

        profile.__dict__["%s_mod" % self.bonus_subject] = str(bonus.mod)
        profile.save()
Ejemplo n.º 5
0
    def send_to(self, sender, receiver, msg):
        try:
            user = User.objects.get(username__iexact=receiver)
            return self._send_to_user(sender, user, msg)
        except User.DoesNotExist:
            try:
                gang = Gang.objects.get_by_name(name=receiver)
                return self._send_to_gang(sender, gang, msg)
            except Gang.DoesNotExist:
                pass

        logging.debug('No msg receiver %s' % receiver)
        return False
Ejemplo n.º 6
0
    def start(self):
        for user in self.qualify_users:
            stats = json.loads(user[1])
            if not stats.has_key('robbery_done') or \
                            stats['robbery_done'] < 10:
                logging.debug('%d not qualify for free credit' % user[0])
                continue

            engine = Engine(DummyRequest(user[0]))
            engine.user.profile.credit += 1
            engine.user.profile.save()

            engine.stream.post('credit_awarded', 1)
            logging.debug('%d awarded with free credit' % user[0])
Ejemplo n.º 7
0
    def enter_city(self, cid):
        self.engine.user.profile.active_city_id = cid
        self.engine.user.profile.save()

        city = CityMap.objects.get_by_id(cid)
        if city.owner_id != self.engine.user.profile.user_id:
            self.engine.stream.post_to_city_wall('city_visit', '<a href="%s">%s</a>' % (
            reverse('city_enter', args=[self.engine.user.profile.default_city_id]), self.engine.user.profile.user),
                                                 city_id=cid, is_public=False)
            self.in_my_city = False
            logging.debug('%s entered foreign city (%s)' % (self.engine.user.user, cid))
        else:
            self.in_my_city = True
            logging.debug('%s entered his city' % self.engine.user.user)
Ejemplo n.º 8
0
    def block_money(self, amount):
        if amount <= 0:
            logging.warning("%s: tried to block <= 0 amount" % (self.engine.user.user))
            self.engine.log.message(message=_("You highest offer is higher"))
            return False

        if self.engine.user.profile.has_enough('cash', amount):
            self.engine.user.profile.cash -= amount
            self.engine.user.profile.save()

            logging.debug("%s: blocked $%d for auction" % (self.engine.user.user, amount))
            return True
        self.engine.log.message(message=_("Not enough cash"))
        return False
Ejemplo n.º 9
0
    def rem_unit(self, id, cnt=1):
        units = self.units
        try:
            if units[str(id)] <= 0 or units[str(id)] < cnt: raise ValueError
            units[str(id)] -= cnt
        except (KeyError, ValueError):
            logging.warning('Failed to remove unit_id:%s (city:%s, user:%s)' % (str(id), self.city_id, self.user))
            return False

        if units[str(id)] == 0: del units[str(id)]

        self.unit = json.dumps(units)
        self.save()
        logging.debug('rem_unit id:%s, city:%s, user:%s' % (id, self.city_id, self.user))
        return True
Ejemplo n.º 10
0
    def recalculate_team(self, recalc_strengths=False):
        """Przelicza calkowita moc calego teamu"""
        logging.debug("recalculate_team() for %s" % self.profile.user)

        self.set_members()
        uf = self.members

        if recalc_strengths:
            uf._calculate_strengths()
            uf.save()

        self.profile.team_attack = int(uf.attack) + int(self.profile.total_attack)
        self.profile.team_defense = int(uf.defense) + int(self.profile.total_defense)
        self.profile.team_respect = int(uf.respect) + int(self.profile.total_respect)

        self.profile.save()
Ejemplo n.º 11
0
    def do_job(self, user):
        import math

        res = {}

        if self.is_premium and not user.is_premium:
            res['result'] = 'NO_PREMIUM'
            return res

        # Job req
        if not user.match_req(self.reqs):
            res['result'] = 'NO_REQ'
            return res

        chance = get_chance(user.total_attack, \
                            user.total_respect, \
                            self.req_attack, \
                            self.req_respect, \
                            0, \
                            user.heat, \
                            user.max_heat, \
                            self.heat)
        rand_chance = random.randint(1, 100)
        if chance < rand_chance:
            logging.debug("%s failed job %s" % (str(user.user), str(self.id)))

            res['result'] = 'NO_CHANCE'
            return res

        res['result'] = True
        res['cash'] = int(math.ceil(int(self.base_instant_cash) * random.uniform(0.8, 1.2)))
        res['attack'] = int(self.base_attack) * random.uniform(float(self.attack_modifier_min),
                                                               float(self.attack_modifier_max))
        res['defense'] = int(self.base_attack) * random.uniform(float(self.attack_modifier_min),
                                                                float(self.attack_modifier_max))
        res['respect'] = int(self.base_respect) * random.uniform(float(self.respect_modifier_min),
                                                                 float(self.respect_modifier_max))

        res['attack'] = round(res['attack'], 2)
        res['defense'] = round(res['defense'], 2)
        res['respect'] = round(res['respect'], 2)

        res['loot'] = self.draw_loot()

        logging.debug("%s done job %s" % (str(user.user), str(self.id)))

        return res
Ejemplo n.º 12
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)))
Ejemplo n.º 13
0
    def draw_loot(self):
        rand_chance = random.randint(1, 100)

        loot_arr = []
        last_loot = 0
        for item_id, chance in self.loots.iteritems():
            for i in xrange(last_loot, last_loot + int(chance)):
                loot_arr.append(int(item_id))
                last_loot += 1

        if last_loot == 0: return
        if len(loot_arr) < rand_chance: return
        try:
            won = loot_arr[rand_chance]
        except IndexError:
            return

        logging.debug("won loot %s" % won)
        return won
Ejemplo n.º 14
0
    def recalculate_total(self):
        """Przelicza calkowita moc wlasnych ludzi"""
        logging.debug("recalculate_total() for %s" % self.profile.user)

        totals = [int(self.profile.base_attack), int(self.profile.base_defense), int(self.profile.base_respect)]

        # myself + inventory
        if not hasattr(self.engine, 'item'):
            self.engine.register('item')
        self.engine.item.set_item_type('item')

        items_list = []
        [items_list.extend(x) for x in self.engine.item.active_inventory.itervalues()]
        for item in items_list:
            totals[0] += item.attack
            totals[1] += item.defense
            totals[2] += item.respect

        # garage
        self.engine.item.set_item_type('vehicle')
        for car in self.engine.item.garage[:int(self.engine.user.profile.max_cars)]:
            totals[2] += car.respect

        # minus
        self.profile.team_attack -= self.profile.total_attack
        self.profile.team_defense -= self.profile.total_defense
        self.profile.team_respect -= self.profile.total_respect

        # new values
        self.profile.total_attack = totals[0]
        self.profile.total_defense = totals[1]
        self.profile.total_respect = totals[2]
        self.profile.team_attack += self.profile.total_attack
        self.profile.team_defense += self.profile.total_defense
        self.profile.team_respect += self.profile.total_respect

        # max_heat
        max_should_be = int(self.profile.total_respect / 100) + 100
        if self.profile.max_heat < max_should_be:
            self.profile.max_heat = max_should_be

        self.profile.pref_lang = self.engine.pref_lang
        self.profile.save()
Ejemplo n.º 15
0
    def add_per_day(self, source, amount, source_id=None, is_limited=None, valid_until=None):
        """Dodaje wpis do tabeli z dziennymi zarobkami/wydatkami"""
        pay = UserPerDay()
        pay.user = self.user

        pay.source = source
        if source_id is not None:
            pay.source_id = source_id
        pay.amount = amount
        if is_limited is not None:
            pay.is_limited = is_limited
        if valid_until is not None:
            pay.valid_until = valid_until

        pay.save()
        logging.debug(
            "%s: pay-per-day added from source: %s(id:%s) with amount: %s"
            % (pay.user, pay.source, pay.source_id, pay.amount)
        )
Ejemplo n.º 16
0
    def deactivate(self):
        user_id = str(self.user.id)
        subject = str(self.bonus_subject)

        logging.debug("%s: deactivating %s" % (user_id, subject))

        profile = UserProfile.objects.get_by_id(self.user.id)
        profile.__dict__["%s_mod" % self.bonus_subject] = "1.0"
        profile.save()

        # archive bonus
        # from django.db import connection
        # sql = """INSERT INTO archive.crims_user_bonus_archive VALUES ('%s', '%s', '%s', '%s', '%s', '%s')""" % (str(self.user.id), str(self.bonus_subject), str(self.bonus_name), str(self.start_at), str(self.end_at), str(datetime.datetime.now())[:19])
        # cursor = connection.cursor()
        # cursor.execute(sql)

        # remove
        self.delete()

        # any bonuses left?
        user_bonuses = UserBonus.objects.get_by_user(user_id=user_id)
        if user_bonuses.has_key(subject) and len(user_bonuses[subject]) > 0:
            user_bonuses[subject][0].activate(profile)
Ejemplo n.º 17
0
    def calc_tribute(self):
        tribute_groups = {}
        for job in JobTribute.objects.all():
            if not tribute_groups.has_key(job.type): tribute_groups[job.type] = []
            tribute_groups[job.type].append(int(job.id))

        logging.debug("%s tributes being recalculated" % (str(self.profile.user)))

        user_tribute_groups = {}
        for group_type, group_items in tribute_groups.iteritems():
            user_tribute_groups[group_type] = {}
            user_tribute_groups[group_type]['todo'] = []
            user_tribute_groups[group_type]['done'] = []

            done_group = self.city_building.items.get(group_type)
            if done_group is None:
                user_tribute_groups[group_type]['todo'] = group_items
                continue

            done = []
            [done.extend(x) for x in done_group.values()]
            for item in group_items:
                if str(item) in done:
                    user_tribute_groups[group_type]['done'].append(str(item))
                else:
                    user_tribute_groups[group_type]['todo'].append(str(item))

        in_list_count = 0
        in_list_notify = []
        out_list_count = 0
        out_list_notify = []
        list_report = {}
        for group_type, group_items in user_tribute_groups.iteritems():
            total = len(group_items['done'])

            try:
                ratio = float(self.city_map.population) / (total * settings.BIZ_PER_CAPITA[group_type])
            except ZeroDivisionError:
                ratio = float(self.city_map.population) / (1 * settings.BIZ_PER_CAPITA[group_type])

            # print '--->', group_type, '<---'
            # print 'GOT:', total, group_items['done']
            # print 'RATIO:', ratio, '(1 per capita',settings.BIZ_PER_CAPITA[group_type],')'

            if ratio < 0.8:  # remove tributes
                to_out = total - int(math.floor(float(self.city_map.population) / settings.BIZ_PER_CAPITA[group_type]))
                if len(group_items['done']) == 0 or to_out == 0: continue

                out_list = []
                for i in xrange(0, to_out):
                    choice = random.choice(group_items['done'])
                    if choice not in out_list: out_list.append(choice)
                # specjalnie nie ponawiamy randoma
                out_list_notify.append(self.city_building.remove(group_type, out_list))
                out_list_count += len(out_list)
                list_report[group_type] = -(len(out_list))
            # print 'out:', out_list

            elif ratio > 1.0:  # add tributes
                to_in = int(math.floor(float(self.city_map.population) / settings.BIZ_PER_CAPITA[group_type])) - total
                in_list = []

                if to_in == 0 or len(group_items['todo']) == 0: continue

                if to_in >= len(tribute_groups[group_type]):
                    in_list = [str(x) for x in tribute_groups[group_type]]
                    in_list_count += len(in_list)
                    list_report[group_type] = len(in_list)

                    self.city_building.add(group_type, in_list)
                    continue

                for i in xrange(0, to_in):
                    choice = str(random.choice(group_items['todo']))
                    if choice not in in_list: in_list.append(choice)
                    # specjalnie nie ponawiamy randoma
                    if len(group_items['done']) + len(in_list) >= len(tribute_groups[group_type]): break
                self.city_building.add(group_type, in_list)

                in_list_count += len(in_list)
                list_report[group_type] = len(in_list)
            # print 'in:', in_list
            else:
                continue

        if in_list_count != 0: in_list_notify.append(str(self.profile.user))
        return (list_report, set(in_list_notify))
Ejemplo n.º 18
0
 def kill_units(self, how_many):
     logging.debug('kill %s units' % str(how_many))
     for x in xrange(0, how_many):
         self.rem_unit(random.choice(self.units.keys()))