Пример #1
0
    def execute(self, message, user, params):

        num, name = params.groups()

        ship = Ship.load(name=name)
        if ship is None:
            message.alert("No Ship called: %s" % (name, ))
            return

        num = self.short2num(num)
        reply = "Buying %s %s (%s) will cost %s metal, %s crystal and %s eonium." % (
            num, ship.name,
            self.num2short(
                ship.total_cost * num // PA.getint("numbers", "ship_value")),
            self.num2short(ship.metal * num), self.num2short(
                ship.crystal * num), self.num2short(ship.eonium * num))

        for gov in PA.options("govs"):
            bonus = PA.getfloat(gov, "prodcost")
            if bonus == 0:
                continue

            reply += " %s: %s metal, %s crystal and %s eonium." % (
                PA.get(gov, "name"),
                self.num2short(floor(ship.metal * (1 + bonus)) * num),
                self.num2short(floor(ship.crystal * (1 + bonus)) * num),
                self.num2short(floor(ship.eonium * (1 + bonus)) * num))

        reply += " It will add %s value" % (self.num2short(
            ship.total_cost * num *
            (1.0 / PA.getint("numbers", "ship_value") -
             1.0 / PA.getint("numbers", "res_value"))), )
        message.reply(reply)
Пример #2
0
Файл: cost.py Проект: JDD/merlin
 def execute(self, message, user, params):
     
     num, name = params.groups()
     
     ship = Ship.load(name=name)
     if ship is None:
         message.alert("No Ship called: %s" % (name,))
         return
     
     num = self.short2num(num)
     reply="Buying %s %s (%s) will cost %s metal, %s crystal and %s eonium."%(num,ship.name,
             self.num2short(ship.total_cost*num//PA.getint("numbers", "ship_value")),
             self.num2short(ship.metal*num),
             self.num2short(ship.crystal*num),
             self.num2short(ship.eonium*num))
     
     for gov in PA.options("govs"):
         bonus = PA.getfloat(gov, "prodcost")
         if bonus == 0:
             continue
         
         reply += " %s: %s metal, %s crystal and %s eonium."%(
                     PA.get(gov, "name"),
                     self.num2short(floor(ship.metal*(1+bonus))*num),
                     self.num2short(floor(ship.crystal*(1+bonus))*num),
                     self.num2short(floor(ship.eonium*(1+bonus))*num))
     
     reply+=" It will add %s value"%(self.num2short(ship.total_cost*num*(1.0/PA.getint("numbers", "ship_value") - 1.0/PA.getint("numbers", "res_value"))),)
     message.reply(reply)
Пример #3
0
    def execute(self, message, user, params):

        roids, cost, bonus = params.groups()
        roids, cost, bonus = int(roids), self.short2num(cost), int(bonus or 0)
        mining = PA.getint("roids", "mining")

        if roids == 0:
            message.reply("Another NewDawn landing, eh?")
            return

        mining = mining * ((float(bonus) + 100) / 100)

        ticks = (cost * PA.getint("numbers", "ship_value")) / (roids * mining)
        reply = "Capping %s roids at %s value with %s%% bonus will repay in %s ticks (%s days)" % (
            roids,
            self.num2short(cost),
            bonus,
            int(ticks),
            int(ticks / 24),
        )

        for gov in PA.options("govs"):
            bonus = PA.getfloat(gov, "prodcost")
            if bonus == 0:
                continue
            ticks_b = ticks * (1 + bonus)
            reply += " %s: %s ticks (%s days)" % (PA.get(gov, "name"), int(ticks_b), int(ticks_b / 24))

        message.reply(reply)
Пример #4
0
    def execute(self, message, user, params):

        roids, cost, bonus = params.groups()
        roids, cost, bonus = int(roids), self.short2num(cost), int(bonus or 0)
        mining = PA.getint("roids", "mining")

        if roids == 0:
            message.reply("Another NewDawn landing, eh?")
            return

        mining = mining * ((float(bonus) + 100) / 100)

        ticks = (cost * PA.getint("numbers", "ship_value")) // (roids * mining)
        reply = "Capping %s roids at %s value with %s%% bonus will repay in %s ticks (%s days)" % (
            roids, self.num2short(cost), bonus, int(ticks), int(ticks / 24))

        for gov in PA.options("govs"):
            bonus = PA.getfloat(gov, "prodcost")
            if bonus == 0:
                continue
            ticks_b = ticks * (1 + bonus)
            reply += " %s: %s ticks (%s days)" % (PA.get(
                gov, "name"), int(ticks_b), int(ticks_b / 24))

        message.reply(reply)
Пример #5
0
 def execute(self, request, user, x, y, z, h=False, hs=False, ticks=None):
     planet = Planet.load(x,y,z)
     if planet is None:
         return HttpResponseRedirect(reverse("planet_ranks"))
     
     ticks = int(ticks or 0) if (h or hs) else 12
     
     if not hs:
         sizediffvalue = PlanetHistory.rdiff * PA.getint("numbers", "roid_value")
         valuediffwsizevalue = PlanetHistory.vdiff - sizediffvalue
         resvalue = valuediffwsizevalue * PA.getint("numbers", "res_value")
         shipvalue = valuediffwsizevalue * PA.getint("numbers", "ship_value")
         xpvalue = PlanetHistory.xdiff * PA.getint("numbers", "xp_value")
         Q = session.query(PlanetHistory,
                             sizediffvalue,
                             valuediffwsizevalue,
                             resvalue, shipvalue,
                             xpvalue,
                             )
         Q = Q.filter(PlanetHistory.current == planet)
         Q = Q.order_by(desc(PlanetHistory.tick))
         history = Q[:ticks] if ticks else Q.all()
     else:
         history = None
     
     if not (h or hs):
         landings = session.query(PlanetLandings.hour, count()).filter(PlanetLandings.planet==planet).group_by(PlanetLandings.hour).all()
         landed = session.query(PlanetLandedOn.hour, count()).filter(PlanetLandedOn.planet==planet).group_by(PlanetLandedOn.hour).all()
         vdrops = session.query(PlanetValueDrops.hour, count()).filter(PlanetValueDrops.planet==planet).group_by(PlanetValueDrops.hour).all()
         idles = session.query(PlanetIdles.hour, count()).filter(PlanetIdles.planet==planet).group_by(PlanetIdles.hour).all()
         hourstats = {
                         'landings' : dict(landings), 'landingsT' : sum([c for hour,c in landings]),
                         'landed'   : dict(landed),   'landedT'   : sum([c for hour,c in landed]),
                         'vdrops'   : dict(vdrops),   'vdropsT'   : sum([c for hour,c in vdrops]),
                         'idles'    : dict(idles),    'idlesT'    : sum([c for hour,c in idles]),
                         }
     else:
         hourstats = None
     
     if not h:
         Q = session.query(PlanetHistory)
         Q = Q.filter(or_(PlanetHistory.hour == 23, PlanetHistory.tick == Updates.current_tick()))
         Q = Q.filter(PlanetHistory.current == planet)
         Q = Q.order_by(desc(PlanetHistory.tick))
         hsummary = Q.all() if hs else Q[:14]
     else:
         hsummary = None
     
     return render(["planet.tpl",["hplanet.tpl","hsplanet.tpl"][hs]][h or hs],
                     request,
                     planet = planet,
                     history = history,
                     hour = datetime.utcnow().hour, hourstats = hourstats,
                     hsummary = hsummary,
                     ticks = ticks,
                   )
Пример #6
0
 def execute(self, request, user, x, y, h=False, hs=False, ticks=None):
     galaxy = Galaxy.load(x,y)
     if galaxy is None:
         return HttpResponseRedirect(reverse("galaxy_ranks"))
     
     ticks = int(ticks or 0) if (h or hs) else 12
     
     if not (h or hs):
         Q = session.query(Planet, Intel.nick, Alliance.name)
         Q = Q.outerjoin(Planet.intel)
         Q = Q.outerjoin(Intel.alliance)
         Q = Q.filter(Planet.active == True)
         Q = Q.filter(Planet.galaxy == galaxy)
         Q = Q.order_by(asc(Planet.z))
         planets = Q.all()
         exiles = galaxy.exiles[:10]
     else:
         planets, exiles = None, None
     
     if not hs:
         sizediffvalue = GalaxyHistory.rdiff * PA.getint("numbers", "roid_value")
         valuediffwsizevalue = GalaxyHistory.vdiff - sizediffvalue
         resvalue = valuediffwsizevalue * PA.getint("numbers", "res_value")
         shipvalue = valuediffwsizevalue * PA.getint("numbers", "ship_value")
         xpvalue = GalaxyHistory.xdiff * PA.getint("numbers", "xp_value")
         Q = session.query(GalaxyHistory,
                             sizediffvalue,
                             valuediffwsizevalue,
                             resvalue, shipvalue,
                             xpvalue,
                             )
         Q = Q.filter(GalaxyHistory.current == galaxy)
         Q = Q.order_by(desc(GalaxyHistory.tick))
         history = Q[:ticks] if ticks else Q.all()
     else:
         history = None
     
     if not h:
         Q = session.query(GalaxyHistory)
         Q = Q.filter(or_(GalaxyHistory.hour == 23, GalaxyHistory.tick == Updates.current_tick()))
         Q = Q.filter(GalaxyHistory.current == galaxy)
         Q = Q.order_by(desc(GalaxyHistory.tick))
         hsummary = Q.all() if hs else Q[:14]
     else:
         hsummary = None
     
     return render(["galaxy.tpl",["hgalaxy.tpl","hsgalaxy.tpl"][hs]][h or hs],
                     request,
                     galaxy = galaxy,
                     planets = planets,
                     exiles = exiles,
                     history = history,
                     hsummary = hsummary,
                     ticks = ticks,
                   )
Пример #7
0
 def execute(self, message, user, params):
     
     num, name, attacker = params.groups()
     attacker = (attacker or "t1").lower()
     
     num = self.short2num(num)
     ship = Ship.load(name=name)
     if ship is not None:
         pass
     elif "asteroids".rfind(name.lower()) > -1:
         ship = Ship(name="Asteroids",class_="Roids",armor=50,total_cost=PA.getint("numbers", "roid_value")*PA.getint("numbers", "ship_value"))
     elif "constructions".rfind(name.lower()) > -1:
         ship = Ship(name="Constructions",class_="Struct",armor=500,total_cost=PA.getint("numbers", "cons_value")*PA.getint("numbers", "ship_value"))
     else:
         message.alert("No Ship called: %s" % (name,))
         return
     efficiency = PA.getfloat("teffs",attacker.lower())
     attacker_class = getattr(Ship, attacker)
     attackers = session.query(Ship).filter(attacker_class == ship.class_)
     if attackers.count() == 0:
         message.reply("%s are not hit by anything as that category (%s)" % (ship.name,attacker))
         return
     if ship.class_ == "Roids":
         reply="Capturing"
     elif ship.class_ == "Struct":
         reply="Destroying"
     else:
         reply="Stopping"
     reply+=" %s %s (%s) as %s requires " % (num, ship.name,self.num2short(num*ship.total_cost/PA.getint("numbers", "ship_value")),attacker)
     for attacker in attackers:
         if attacker.type.lower() == "emp" :
           if attacker.init < ship.init:
               needed=int((math.ceil(num/(float(100-ship.empres)/100)/attacker.guns))/efficiency)
           else:
               ship_num = 0
               while 1:
                 ship_num += 1
                 needed = int(efficiency * ship.damage * ship_num / attacker.armor)
                 if needed >= num:
                   break
               needed = ship_num
         else:
           if attacker.init < ship.init:
               needed=int((math.ceil(float(ship.armor*num)/attacker.damage))/efficiency)
           else:
               ship_num = 0
               while 1:
                 ship_num += 1
                 needed = int(efficiency * ship.damage * ship_num / attacker.armor)
                 if needed >= num:
                   break
               needed = ship_num
         reply+="%s: %s (%s) " % (attacker.name,needed,self.num2short(attacker.total_cost*needed/PA.getint("numbers", "ship_value")))
     message.reply(reply)
Пример #8
0
 def tick(self, message, user, params):
     tick = Updates.load(params.group(1)) or Updates.current_tick()
     if tick is None:
         message.reply("Ticks haven't started yet, go back to masturbating.")
     elif isinstance(tick, Updates):
         message.reply(str(tick))
     else:
         diff = int(params.group(1)) - tick
         now = datetime.utcnow()
         tick_length = PA.getint("numbers", "tick_length")
         tdiff = timedelta(seconds=tick_length*diff)-timedelta(minutes=now.minute%(tick_length/60))
         seconds = 0
         retstr  = "%sd " % abs(tdiff.days) if tdiff.days else ""
         retstr += "%sh " % abs(tdiff.seconds/3600) if tdiff.seconds/3600 else ""
         retstr += "%sm " % abs(tdiff.seconds%3600/60) if tdiff.seconds%3600/60 else ""
             
         if diff == 1:
             retstr = "Next tick is %s (in %s" % (params.group(1), retstr)
         elif diff > 1:
             retstr = "Tick %s is expected to happen in %s ticks (in %s" % (params.group(1), diff, retstr)
         elif diff <= 0:
             retstr = "Tick %s was expected to happen %s ticks ago but was not scraped (%s ago" % (params.group(1), -diff, retstr)
         
         time = now + tdiff
         retstr += " - %s)" % (time.strftime("%a %d/%m %H:%M"),)
         message.reply(retstr)
Пример #9
0
 def execute(self, request, user, id, x, y, z, when):
     planet = Planet.load(x,y,z)
     if planet is None:
         return self.attack(request, user, id, "No planet with coords %s:%s:%s" %(x,y,z,))
     
     tick = Updates.current_tick()
     when = int(when)
     if when < PA.getint("numbers", "protection"):
         eta = when
         when += tick
     elif when <= tick:
         return self.attack(request, user, id, "Can not book targets in the past. You wanted tick %s, but current tick is %s." % (when, tick,))
     else:
         eta = when - tick
     if when > 32767:
         when = 32767        
     
     if planet.intel and planet.alliance and planet.alliance.name == Config.get("Alliance","name"):
         return self.attack(request, user, id, "%s:%s:%s is %s in %s. Quick, launch before they notice!" % (x,y,z, planet.intel.nick or 'someone', Config.get("Alliance","name"),))
     
     try:
         planet.bookings.append(Target(user=user, tick=when))
         session.commit()
     except IntegrityError:
         session.rollback()
         target = planet.bookings.filter(Target.tick == when).first()
         if target is not None:
             return self.attack(request, user, id, "Target %s:%s:%s is already booked for landing tick %s by user %s" % (x,y,z, when, target.user.name,))
     else:
         return self.attack(request, user, id, "Booked landing on %s:%s:%s tick %s (eta %s) for user %s" % (x,y,z, when, (when-tick), user.name,))
     
     return self.attack(request, user, id)
Пример #10
0
    def bonus(self, message, user, params):

        # Check if tick is provided
        tick = int(params.group(1) or 0)

        if tick > PA.getint("numbers", "last_tick"):
            message.reply("Use your bonus during the round, not after.")
            return

        # If there is no tick provided in the command then check what the current tick is.
        if not tick:
            # Retrieve current tick
            tick = Updates.current_tick()
            if not tick:
                # Game not ticking yet.
                message.reply("Game is not ticking yet!")
                return

        resources = 10000 + tick * 4800
        roids = int(6 + tick * 0.15)
        research = 4000 + tick * 24
        construction = 2000 + tick * 18

        message.reply(
            "Upgrade Bonus calculation for tick {} | Resources: {:,} EACH | Roids: {:,} EACH | Research Points: {:,} | Construction Units: {:,}".format(
                tick, resources, roids, research, construction
            )
        )
Пример #11
0
    def new(self, message, user, params):
        tick = Updates.current_tick()
        comment = params.group(3) or ""
        when = int(params.group(1))
        if when < PA.getint("numbers", "protection"):
            eta = when
            when += tick
        elif when <= tick:
            message.alert(
                "Can not create attacks in the past. You wanted tick %s, but current tick is %s." % (when, tick)
            )
            return
        else:
            eta = when - tick
        if when > 32767:
            when = 32767

        attack = Attack(landtick=when, comment=comment)
        session.add(attack)

        for coord in re.findall(loadable.coord, params.group(2)):
            if not coord[4]:
                galaxy = Galaxy.load(coord[0], coord[2])
                if galaxy:
                    attack.addGalaxy(galaxy)

            else:
                planet = Planet.load(coord[0], coord[2], coord[4])
                if planet:
                    attack.addPlanet(planet)

        session.commit()
        message.reply(str(attack))
Пример #12
0
 def land(self, message, user, params):
     id = int(params.group(1))
     attack = Attack.load(id)
     if attack is None:
         message.alert("No attack exists with id %d" %(id))
         return
     
     tick = Updates.current_tick()
     when = int(params.group(2))
     
     if when == 0:
         session.delete(attack)
         session.commit()
         message.reply("Deleted Attack %d LT: %d | %s" %(attack.id,attack.landtick,attack.comment,))
         return
     
     if when < PA.getint("numbers", "protection"):
         eta = when
         when += tick
     elif when <= tick:
         message.alert("Can not create attacks in the past. You wanted tick %s, but current tick is %s." % (when, tick,))
         return
     else:
         eta = when - tick
     if when > 32767:
         when = 32767
     
     old = attack.landtick
     attack.landtick = when
     
     session.commit()
     message.reply("Changed LT for attack %d from %d to %d"%(id,old,when))
Пример #13
0
    def tick(self, message, user, params):
        tick = Updates.load(params.group(1)) or Updates.current_tick()
        if tick is None:
            message.reply("Ticks haven't started yet, go back to masturbating.")
        elif isinstance(tick, Updates):
            message.reply(str(tick))
        else:
            diff = int(params.group(1)) - tick
            now = datetime.utcnow()
            tick_length = PA.getint("numbers", "tick_length")
            tdiff = timedelta(seconds=tick_length * diff) - timedelta(minutes=now.minute % (tick_length / 60))
            seconds = 0
            retstr = "%sd " % abs(tdiff.days) if tdiff.days else ""
            retstr += "%sh " % abs(tdiff.seconds / 3600) if tdiff.seconds / 3600 else ""
            retstr += "%sm " % abs(tdiff.seconds % 3600 / 60) if tdiff.seconds % 3600 / 60 else ""

            if diff == 1:
                retstr = "Next tick is %s (in %s" % (params.group(1), retstr)
            elif diff > 1:
                retstr = "Tick %s is expected to happen in %s ticks (in %s" % (params.group(1), diff, retstr)
            elif diff <= 0:
                retstr = "Tick %s was expected to happen %s ticks ago but was not scraped (%s ago" % (
                    params.group(1),
                    -diff,
                    retstr,
                )

            time = now + tdiff
            retstr += " - %s)" % (time.strftime("%a %d/%m %H:%M"),)
            message.reply(retstr)
Пример #14
0
    def execute(self, message, user, params):

        eta, land_tick = params.groups()
        land_tick = int(land_tick)

        if eta.lower() in self.class_eta.keys():
            eta = self.class_eta[eta.lower()]
        else:
            try:
                eta = int(eta)
            except ValueError:
                message.alert("Invalid class or eta '%s'" % (eta, ))
                return

        current_tick = Updates.current_tick()

        current_time = datetime.datetime.utcnow()
        tick_length = PA.getint("numbers", "tick_length")
        launch_tick = land_tick - eta
        launch_time = current_time + datetime.timedelta(
            seconds=tick_length *
            (launch_tick - current_tick + 1)) - datetime.timedelta(
                minutes=current_time.minute % (tick_length / 60) + 5)
        prelaunch_tick = land_tick - eta + 1
        prelaunch_mod = launch_tick - current_tick

        message.reply(
            "eta %d landing pt %d (currently %d) must launch at pt %d (%s), or with prelaunch tick %d (currently %+d)"
            % (eta, land_tick, current_tick, launch_tick,
               (launch_time.strftime("%m-%d %H:%M")), prelaunch_tick,
               prelaunch_mod))
Пример #15
0
 def execute(self, message, user, params):
     
     num, name, target = params.groups()
     target = (target or "t1").lower()
     
     ship = Ship.load(name=name)
     num = self.short2num(num)
     if ship is None:
         message.alert("No Ship called: %s" % (name,))
         return
     efficiency = PA.getfloat("teffs",target.lower())
     target_class = getattr(ship, target)
     if ship.damage:
         total_damage = ship.damage * num
     if ship.t1 == "Roids":
         killed = total_damage/50
         message.reply("%s %s (%s) will capture Asteroid: %s (%s)" % (
             num, ship.name, self.num2short(num*ship.total_cost/100),
             killed, self.num2short(killed*PA.getint("numbers", "roid_value")),))
         return
     if ship.t1 == "Struct":
         killed = total_damage/500
         message.reply("%s %s (%s) will destroy Structure: %s (%s)" % (
             num, ship.name, self.num2short(num*ship.total_cost/100),
             killed, self.num2short(killed*PA.getint("numbers", "cons_value")),))
         return
     targets = session.query(Ship).filter(Ship.class_ == target_class)
     if targets.count() == 0:
         message.reply("%s does not have any targets in that category (%s)" % (ship.name,target))
         return
     reply="%s %s (%s) hitting %s will " % (num, ship.name,self.num2short(num*ship.total_cost/100),target_class)
     if ship.type.lower() == "norm" or ship.type.lower() == 'cloak':
         reply+="destroy "
     elif ship.type.lower() == "emp":
         reply+="hug "
     elif ship.type.lower() == "steal":
         reply+="steal "
     else:
         raise Exception("Erroneous type %s" % (ship.type,))
     for target in targets:
         if ship.type.lower() == "emp" :
             killed=int(efficiency * ship.guns*num*float(100-target.empres)/100)
         else:
             killed=int(efficiency * total_damage/target.armor)
         reply+="%s: %s (%s) " % (target.name,killed,self.num2short(target.total_cost*killed/100))
     message.reply(reply)
Пример #16
0
    def execute(self, message, user, params):

        target = Planet.load(*params.group(1, 3, 5))
        if target is None:
            message.reply("No planet matching '%s:%s:%s' found" %
                          params.group(1, 3, 5))
            return
        replies = [str(target)]

        if self.user_has_planet(user):
            attacker = user.planet
            reply = "Target "

            reply += "%s:%s:%s (%s|%s) " % (target.x, target.y, target.z,
                                            self.num2short(target.value),
                                            self.num2short(target.score))
            reply += "| Attacker %s:%s:%s (%s|%s) " % (
                attacker.x, attacker.y, attacker.z,
                self.num2short(attacker.value), self.num2short(attacker.score))

            reply += "| Bravery: %.2f " % (attacker.bravery(target), )

            cap = target.maxcap(attacker)
            xp = attacker.calc_xp(target)
            reply += "| Roids: %s | XP: %s | Score: %s" % (
                cap, xp, xp * PA.getint("numbers", "xp_value"))
            replies.append(reply)

        if target.intel is not None:
            replies.append(
                ("Information stored for %s:%s:%s -" + str(target.intel) if
                 str(target.intel) else "No information stored for %s:%s:%s") %
                (
                    target.x,
                    target.y,
                    target.z,
                ))

        bookings = target.bookings.filter(
            Target.tick > Updates.current_tick()).all()
        if len(bookings) < 1:
            replies.append("No bookings matching planet %s:%s:%s" % (
                target.x,
                target.y,
                target.z,
            ))
        else:
            prev = []
            for booking in bookings:
                prev.append("(%s user:%s)" % (booking.tick, booking.user.name))
            replies.append("Status for %s:%s:%s - " % (
                target.x,
                target.y,
                target.z,
            ) + ", ".join(prev))

        message.reply("\n".join(replies))
Пример #17
0
 def execute(self, message, user, params):
     
     alliance = Alliance(name="Unknown") if params.group(1).lower() == "unknown" else Alliance.load(params.group(1))
     if alliance is None:
         message.reply("No alliance matching '%s' found"%(params.group(1),))
         return
     
     tick = Updates.current_tick()
     
     when = int(params.group(2) or 0)
     if when and when < PA.getint("numbers", "protection"):
         when += tick
     elif when and when <= tick:
         message.alert("Can not check status on the past. You wanted tick %s, but current tick is %s." % (when, tick,))
         return
     
     Q = session.query(Planet, User.name, Target.tick)
     Q = Q.join(Target.planet)
     Q = Q.join(Planet.intel) if alliance.id else Q.outerjoin(Planet.intel)
     Q = Q.join(Target.user)
     Q = Q.filter(Planet.active == True)
     Q = Q.filter(Intel.alliance == (alliance if alliance.id else None))
     Q = Q.filter(Target.tick == when) if when else Q.filter(Target.tick > tick)
     Q = Q.order_by(asc(Planet.x))
     Q = Q.order_by(asc(Planet.y))
     Q = Q.order_by(asc(Planet.z))
     result = Q.all()
     
     if len(result) < 1:
         reply="No active bookings matching alliance %s" %(alliance.name)
         if when:
             reply+=" for tick %s."%(when,)
         message.reply(reply)
         return
     
     reply="Target information for %s"%(alliance.name)
     reply+=" landing on tick %s (eta %s): "%(when,when-tick) if when else ": "
     
     ticks={}
     for planet, user, land in result:
         if not ticks.has_key(land):
             ticks[land]=[]
         ticks[land].append((planet, user,))
     sorted_keys=ticks.keys()
     sorted_keys.sort()
     
     replies = []
     for land in sorted_keys:
         prev=[]
         for planet, user in ticks[land]:
             prev.append("(%s:%s:%s %s)" % (planet.x,planet.y,planet.z,user))
         replies.append("Tick %s (eta %s) "%(land,land-tick) +", ".join(prev))
     replies[0] = reply + replies[0]
     
     message.reply("\n".join(replies))
Пример #18
0
    def execute(self, message, user, params):
        
        roids=int(params.group(1))
        ticks=int(params.group(2))
        bonus=int(params.group(3) or 0)
        mining = PA.getint("roids","mining")

        mining = mining *(float(bonus+100)/100)

        value = ticks*roids*mining/PA.getint("numbers", "ship_value")
        reply = "In %s ticks (%s days) %s roids with %s%% bonus will mine %s value" % (ticks,ticks//24,roids,bonus,self.num2short(value))
        
        for gov in PA.options("govs"):
            bonus = PA.getfloat(gov, "prodcost")
            if bonus == 0:
                continue
            value_b = value/(1+bonus)
            reply += " %s: %s value" % (PA.get(gov, "name"), self.num2short(value_b))
        
        message.reply(reply)
Пример #19
0
    def new(self, message, user, params):
        tick = Updates.current_tick()
        comment = params.group(4) or ""
        when = int(params.group(1))
        waves = params.group(2) or Config.get("Misc", "attwaves")
        if when < PA.getint("numbers", "protection"):
            when += tick
        elif when <= tick:
            message.alert(
                "Can not create attacks in the past. You wanted tick %s, but current tick is %s."
                % (
                    when,
                    tick,
                ))
            return
        if when > 32767:
            when = 32767

        attack = Attack(landtick=when, comment=comment, waves=int(waves))
        session.add(attack)

        for coord in re.findall(loadable.coord, params.group(3)):
            if not coord[4]:
                galaxy = Galaxy.load(coord[0], coord[2])
                if galaxy:
                    attack.addGalaxy(galaxy)

            else:
                planet = Planet.load(coord[0], coord[2], coord[4])
                if planet:
                    attack.addPlanet(planet)

        session.commit()
        message.reply(str(attack))

        # Request scans
        if Config.has_option("Misc", "attscans"):
            scantypes = Config.get("Misc", "attscans")
        else:
            scantypes = ""

        for stype in scantypes:
            for p in attack.planets:
                scan = p.scan(stype)
                if scan and (int(tick) == scan.tick):
                    return
                else:
                    req = Request(target=p, scantype=stype, dists=0)
                    user.requests.append(req)
                    session.commit()
                    push("request", request_id=req.id, mode="request")
        if scantypes:
            message.reply("Scans requested: %s" % (scantypes))
Пример #20
0
 def execute(self, message, user, params, override):
     planet = Planet.load(*params.group(1,3,5))
     if planet is None:
         message.alert("No planet with coords %s:%s:%s" % params.group(1,3,5))
         return
     
     tick = Updates.current_tick()
     when = int(params.group(6) or 0)
     if 0 < when < PA.getint("numbers", "protection"):
         eta = when
         when += tick
     elif 0 < when <= tick:
         message.alert("Can not unbook targets in the past. You wanted tick %s, but current tick is %s." % (when, tick,))
         return
     else:
         eta = when - tick
     if when > 32767:
         when = 32767 
     
     Q = session.query(Target)
     Q = Q.join(Target.user)
     Q = Q.filter(Target.planet == planet)
     Q = Q.filter(Target.user == user) if override is False else Q
     Q = Q.filter(Target.tick == when) if when else Q.filter(Target.tick >= tick)
     Q = Q.order_by(asc(Target.tick))
     result = Q.all()
     for target in result:
         session.delete(target)
     count = len(result)
     session.commit()
     
     if count < 1:
         reply=("You have no " if override is False else "No ") +"bookings matching %s:%s:%s"%(planet.x,planet.y,planet.z,)
         if when:
             reply+=" for landing on tick %s"%(when,)
         reply+=". If you are trying to unbook someone else's target, you must confirm with 'yes'." if override is False else ""
     else:
         reply="You have unbooked %s:%s:%s"%(planet.x,planet.y,planet.z,)
         if when:
             reply+=" for landing pt %s"%(when,)
             if override:
                 reply+=" (previously held by user %s)"%(result[0].user.name)
         else:
             reply+=" for %d booking(s)"%(count,)
             if override:
                 prev=[]
                 for target in result:
                     prev.append("(%s user:%s)" % (target.tick,target.user.name))
                 reply+=": "+", ".join(prev)
                     
         reply+="."
     message.reply(reply)
     return
Пример #21
0
    def execute(self, message, user, params):

        num, name, factories = params.group(1, 2, 3)

        ship = Ship.load(name=name)
        if ship is None:
            message.alert("%s is not a ship." % name)
            return
        num = self.short2num(num)
        factories = int(factories)

        race = ship.race[:3].lower()
        race = "etd" if race == "eit" else race

        gov = None
        pop = 0
        for p in (params.group(4) or "").split():
            m = self.govre.match(p)
            if m and not gov:
                gov = m.group(1).lower()
                continue
            if p.isdigit() and not pop:
                pop = int(p)
                continue

        m = ship.metal
        c = ship.crystal
        e = ship.eonium
        bonus = 1 + pop / 100.0
        if gov:
            m *= (1 + PA.getfloat(gov, "prodcost"))
            c *= (1 + PA.getfloat(gov, "prodcost"))
            e *= (1 + PA.getfloat(gov, "prodcost"))
            bonus += PA.getfloat(gov, "prodtime")
        if race:
            bonus += PA.getfloat(race, "prodtime")
        cost = floor(m) + floor(c) + floor(e)
        print cost

        ticks = self.calc_ticks(cost, num, bonus, factories)

        reply = "It will take %s ticks to build %s %s (%s)" % (
            ticks, self.num2short(num), ship.name,
            self.num2short(
                num * ship.total_cost / PA.getint("numbers", "ship_value")))
        reply += " using %s factories" % (factories, ) if factories > 1 else ""
        reply += " with a" if race or gov else ""
        reply += " %s" % (PA.get(gov, "name"), ) if gov else ""
        reply += " %s" % (PA.get(race, "name"), ) if race else ""
        reply += " planet" if race or gov else ""
        reply += " with %s%% population" % (pop, ) if pop else ""
        message.reply(reply)
Пример #22
0
    def execute(self, message, user, params):

        roids = int(params.group(1))
        ticks = int(params.group(2))
        bonus = int(params.group(3) or 0)
        mining = PA.getint("roids", "mining")

        mining = mining * (float(bonus + 100) / 100)

        value = ticks * roids * mining / PA.getint("numbers", "ship_value")
        reply = "In %s ticks (%s days) %s roids with %s%% bonus will mine %s value" % (
            ticks, ticks // 24, roids, bonus, self.num2short(value))

        for gov in PA.options("govs"):
            bonus = PA.getfloat(gov, "prodcost")
            if bonus == 0:
                continue
            value_b = value / (1 + bonus)
            reply += " %s: %s value" % (PA.get(
                gov, "name"), self.num2short(value_b))

        message.reply(reply)
Пример #23
0
Файл: xp.py Проект: d7415/merlin
    def execute(self, message, target, attacker):
        reply="Target "

        reply+="%s:%s:%s (%s|%s) "%(target.x,target.y,target.z,
                                 self.num2short(target.value),self.num2short(target.score))
        reply+="| Attacker %s:%s:%s (%s|%s) "%(attacker.x,attacker.y,attacker.z,
                                            self.num2short(attacker.value),self.num2short(attacker.score))

        reply+="| Bravery: %.2f " % (attacker.bravery(target),)

        cap=target.maxcap(attacker)
        xp=attacker.calc_xp(target)
        reply+="| Roids: %s | XP: %s | Score: %s" % (cap,xp,xp*PA.getint("numbers", "xp_value"))
        message.reply(reply)
Пример #24
0
 def execute(self, message, user, params):
     
     tag_count = PA.getint("numbers", "tag_count")
     
     alliance = Alliance.load(params.group(1))
     if alliance is None:
         message.reply("No alliance matching '%s' found"%(params.group(1),))
         return
     
     Q = session.query(sum(Planet.value), sum(Planet.score),
                       sum(Planet.size), sum(Planet.xp),
                       count())
     Q = Q.join(Planet.intel)
     Q = Q.filter(Planet.active == True)
     Q = Q.filter(Intel.alliance==alliance)
     Q = Q.group_by(Intel.alliance_id)
     result = Q.first()
     if result is None:
         message.reply("No planets in intel match alliance %s"%(alliance.name,))
         return
     
     value, score, size, xp, members = result
     if members <= tag_count:
         reply="%s Members: %s/%s, Value: %s, Avg: %s," % (alliance.name,members,alliance.members,value,value//members)
         reply+=" Score: %s, Avg: %s," % (score,score//members) 
         reply+=" Size: %s, Avg: %s, XP: %s, Avg: %s" % (size,size//members,xp,xp//members)
         message.reply(reply)
         return
     
     Q = session.query(Planet.value, Planet.score, 
                       Planet.size, Planet.xp, 
                       Intel.alliance_id)
     Q = Q.join(Planet.intel)
     Q = Q.filter(Planet.active == True)
     Q = Q.filter(Intel.alliance==alliance)
     Q = Q.order_by(desc(Planet.score))
     Q = Q.limit(tag_count)
     Q = Q.from_self(sum(Planet.value), sum(Planet.score),
                     sum(Planet.size), sum(Planet.xp),
                     count())
     Q = Q.group_by(Intel.alliance_id)
     ts_result = Q.first()
     
     ts_value, ts_score, ts_size, ts_xp, ts_members = ts_result
     reply="%s Members: %s/%s (%s)" % (alliance.name,members,alliance.members,ts_members)
     reply+=", Value: %s (%s), Avg: %s (%s)" % (value,ts_value,value//members,ts_value//ts_members)
     reply+=", Score: %s (%s), Avg: %s (%s)" % (score,ts_score,score//members,ts_score//ts_members)
     reply+=", Size: %s (%s), Avg: %s (%s)" % (size,ts_size,size//members,ts_size//ts_members)
     reply+=", XP: %s (%s), Avg: %s (%s)" % (xp,ts_xp,xp//members,ts_xp//ts_members)
     message.reply(reply)
Пример #25
0
 def execute(self, message, user, params):
     
     num, name, attacker = params.groups()
     attacker = (attacker or "t1").lower()
     
     num = self.short2num(num)
     ship = Ship.load(name=name)
     if ship is not None:
         pass
     elif "asteroids".rfind(name.lower()) > -1:
         ship = Ship(name="Asteroids",class_="Roids",armor=50,total_cost=PA.getint("numbers", "roid_value")*100)
     elif "constructions".rfind(name.lower()) > -1:
         ship = Ship(name="Constructions",class_="Struct",armor=500,total_cost=PA.getint("numbers", "cons_value")*100)
     else:
         message.alert("No Ship called: %s" % (name,))
         return
     efficiency = PA.getfloat("teffs",attacker.lower())
     attacker_class = getattr(Ship, attacker)
     attackers = session.query(Ship).filter(attacker_class == ship.class_)
     if attackers.count() == 0:
         message.reply("%s are not hit by anything as that category (%s)" % (ship.name,attacker))
         return
     if ship.class_ == "Roids":
         reply="Capturing"
     elif ship.class_ == "Struct":
         reply="Destroying"
     else:
         reply="Stopping"
     reply+=" %s %s (%s) as %s requires " % (num, ship.name,self.num2short(num*ship.total_cost/100),attacker)
     for attacker in attackers:
         if attacker.type.lower() == "emp" :
             needed=int((math.ceil(num/(float(100-ship.empres)/100)/attacker.guns))/efficiency)
         else:
             needed=int((math.ceil(float(ship.armor*num)/attacker.damage))/efficiency)
         reply+="%s: %s (%s) " % (attacker.name,needed,self.num2short(attacker.total_cost*needed/100))
     message.reply(reply)
Пример #26
0
    def new(self, message, user, params):
        tick = Updates.current_tick()
        comment = params.group(4) or ""
        when = int(params.group(1))
        waves = params.group(2) or Config.get("Misc", "attwaves")
        if when < PA.getint("numbers", "protection"):
            when += tick
        elif when <= tick:
            message.alert("Can not create attacks in the past. You wanted tick %s, but current tick is %s." % (when, tick,))
            return
        if when > 32767:
            when = 32767
        
        attack = Attack(landtick=when,comment=comment,waves=int(waves))
        session.add(attack)
        
        for coord in re.findall(loadable.coord, params.group(3)):
            if not coord[4]:
                galaxy = Galaxy.load(coord[0],coord[2])
                if galaxy:
                    attack.addGalaxy(galaxy)
            
            else:
                planet = Planet.load(coord[0],coord[2],coord[4])
                if planet:
                    attack.addPlanet(planet)
        
        session.commit()
        message.reply(str(attack))

        # Request scans
        if Config.has_option("Misc", "attscans"):
            scantypes = Config.get("Misc", "attscans")
        else:
            scantypes = ""

        for stype in scantypes:
           for p in attack.planets:
               scan = p.scan(stype)
               if scan and (int(tick) == scan.tick):
                   return
               else:
                   req = Request(target=p, scantype=stype, dists=0)
                   user.requests.append(req)
                   session.commit()
                   push("request", request_id=req.id, mode="request")
        if scantypes:
            message.reply("Scans requested: %s" % (scantypes))
Пример #27
0
    def execute(self, message, user, params):
        
        roids=int(params.group(1))
        ticks=int(params.group(2))
        bonus=int(params.group(3) or 0)
        mining = PA.getint("roids","mining")

        mining = mining *(float(bonus+100)/100)

        cost=self.num2short(ticks*roids*mining/100)
        reply="In %s ticks (%s days) %s roids with %s%% bonus will mine %s value" % (ticks,ticks/24,roids,bonus,cost)

        cost=self.num2short(ticks*roids*mining/100*(1/(1+PA.getfloat("feud","prodcost"))))
        reply+=" Feudalism: %s value" % (cost)

        message.reply(reply)
Пример #28
0
    def execute(self, message, target, attacker):
        reply = "Target "

        reply += "%s:%s:%s (%s|%s) " % (target.x, target.y, target.z,
                                        self.num2short(target.value),
                                        self.num2short(target.score))
        reply += "| Attacker %s:%s:%s (%s|%s) " % (
            attacker.x, attacker.y, attacker.z, self.num2short(
                attacker.value), self.num2short(attacker.score))

        reply += "| Bravery: %.2f " % (attacker.bravery(target), )

        cap = target.maxcap(attacker)
        xp = attacker.calc_xp(target)
        reply += "| Roids: %s | XP: %s | Score: %s" % (
            cap, xp, xp * PA.getint("numbers", "xp_value"))
        message.reply(reply)
Пример #29
0
 def execute(self, request, user, id, x, y, z, when):
     print when
     planet = Planet.load(x,y,z)
     if planet is None:
         return self.attack(request, user, id, "No planet with coords %s:%s:%s" %(x,y,z,))
     
     tick = Updates.current_tick()
     when = int(when or 0)
     if 0 < when < PA.getint("numbers", "protection"):
         eta = when
         when += tick
     elif 0 < when <= tick:
         return self.attack(request, user, id, "Can not unbook targets in the past. You wanted tick %s, but current tick is %s." % (when, tick,))
     else:
         eta = when - tick
     if when > 32767:
         when = 32767        
     
     Q = session.query(Target)
     Q = Q.join(Target.user)
     Q = Q.filter(Target.planet == planet)
     Q = Q.filter(Target.user == user)
     Q = Q.filter(Target.tick == when) if when else Q.filter(Target.tick >= tick)
     Q = Q.order_by(asc(Target.tick))
     result = Q.all()
     for target in result:
         session.delete(target)
     count = len(result)
     session.commit()
     
     if count < 1:
         reply="You have no bookings matching %s:%s:%s"%(planet.x,planet.y,planet.z,)
         if when:
             reply+= " for landing on tick %s"%(when,)
     else:
         reply = "You have unbooked %s:%s:%s"%(planet.x,planet.y,planet.z,)
         if when:
             reply+=" for landing pt %s"%(when,)
         else:
             reply+=" for %d booking(s)"%(count,)
     
     return self.attack(request, user, id, reply)
Пример #30
0
    def execute(self, request, user, name, h=False, hs=False, ticks=None):
        alliance = Alliance.load(name)
        if alliance is None:
            return HttpResponseRedirect(reverse("alliance_ranks"))

        ticks = int(ticks or 0) if h else 12

        if not hs:
            sizediffvalue = AllianceHistory.rdiff * PA.getint(
                "numbers", "roid_value")
            scorediffwsizevalue = AllianceHistory.sdiff - sizediffvalue
            Q = session.query(
                AllianceHistory,
                sizediffvalue,
                scorediffwsizevalue,
            )
            Q = Q.filter(AllianceHistory.current == alliance)
            Q = Q.order_by(desc(AllianceHistory.tick))
            history = Q[:ticks] if ticks else Q.all()
        else:
            history = None

        if not h:
            Q = session.query(AllianceHistory)
            Q = Q.filter(
                or_(AllianceHistory.hour == 23,
                    AllianceHistory.tick == Updates.current_tick()))
            Q = Q.filter(AllianceHistory.current == alliance)
            Q = Q.order_by(desc(AllianceHistory.tick))
            hsummary = Q.all() if hs else Q[:14]
        else:
            hsummary = None

        return render(
            ["alliance.tpl", ["halliance.tpl", "hsalliance.tpl"][hs]][h or hs],
            request,
            alliance=alliance,
            members=alliance.intel_members,
            history=history,
            hsummary=hsummary,
            ticks=ticks,
        )
Пример #31
0
    def execute(self, message, user, params):
        
        roids, cost, bonus = params.groups()
        roids, cost, bonus = int(roids), self.short2num(cost), int(bonus or 0)
        mining = PA.getint("roids","mining")

        if roids == 0:
            message.reply("Another NewDawn landing, eh?")
            return

        mining=mining * ((float(bonus)+100)/100)

        repay=int((cost*100)/(roids*mining))

        reply="Capping %s roids at %s value with %s%% bonus will repay in %s ticks (%s days)" % (roids,self.num2short(cost),bonus,repay,repay/24)

        repay = int((cost*100)/(roids*mining*(1/(1+PA.getfloat("feud","prodcost")))))
        reply+=" Feudalism: %s ticks (%s days)" % (repay,repay/24)

        message.reply(reply)
Пример #32
0
Файл: details.py Проект: JDD/DLR
    def execute(self, message, user, params):
        
        target = Planet.load(*params.group(1,3,5))
        if target is None:
            message.reply("No planet matching '%s:%s:%s' found"%params.group(1,3,5))
            return
        replies = [str(target)]
        
        if self.user_has_planet(user):
            attacker = user.planet
            reply="Target "
            target_val = target.value
            attacker_val = attacker.value
            target_score = target.score
            attacker_score = attacker.score

            reply+="%s:%s:%s (%s|%s) "%(target.x,target.y,target.z,
                                     self.num2short(target.value),self.num2short(target.score))
            reply+="| Attacker %s:%s:%s (%s|%s) "%(attacker.x,attacker.y,attacker.z,
                                                self.num2short(attacker.value),self.num2short(attacker.score))

            reply+="| Bravery: %.2f " % (attacker.bravery(target),)

            cap=target.maxcap(attacker)
            xp=attacker.calc_xp(target)
            reply+="| Roids: %s | XP: %s | Score: %s" % (cap,xp,xp*PA.getint("numbers", "xp_value"))
            replies.append(reply)
        
#        if target.intel is not None:
#            replies.append(("Information stored for %s:%s:%s -"+str(target.intel) if str(target.intel) else "No information stored for %s:%s:%s") % (target.x, target.y, target.z,))

#        bookings = target.bookings.filter(Target.tick > Updates.current_tick()).all()
#        if len(bookings) < 1:
#            replies.append("No bookings matching planet %s:%s:%s" % (target.x, target.y, target.z,))
#        else:
#            prev = []
#            for booking in bookings:
#                prev.append("(%s user:%s)" % (booking.tick,booking.user.name))
 #           replies.append("Status for %s:%s:%s - " % (target.x, target.y, target.z,) + ", ".join(prev))
        
        message.reply("\n".join(replies))
Пример #33
0
    def execute(self, message, user, params):
        planet = Planet.load(*params.group(1, 3, 5))
        if planet is None:
            message.alert("No planet with coords %s:%s:%s" % params.group(1, 3, 5))
            return

        scan = params.group(6).upper()
        dists = int(params.group(7) or 0)

        request = self.request(message, user, planet, scan, dists)
        if message.get_chan() != self.scanchan():
            message.reply(
                "Requested a %s Scan of %s:%s:%s. !request cancel %s to cancel the request."
                % (request.type, planet.x, planet.y, planet.z, request.id)
            )

        scan = planet.scan(scan)
        if scan and request.tick - scan.tick < PA.getint(scan.scantype, "expire"):
            message.reply(
                "%s Scan of %s:%s:%s is already available from %s ticks ago: %s. !request cancel %s if this is suitable."
                % (scan.scantype, planet.x, planet.y, planet.z, request.tick - scan.tick, scan.link, request.id)
            )
Пример #34
0
 def execute(self, request, user, name, h=False, hs=False, ticks=None):
     alliance = Alliance.load(name)
     if alliance is None:
         return HttpResponseRedirect(reverse("alliance_ranks"))
     
     ticks = int(ticks or 0) if h else 12
     
     if not hs:
         sizediffvalue = AllianceHistory.rdiff * PA.getint("numbers", "roid_value")
         scorediffwsizevalue = AllianceHistory.sdiff - sizediffvalue
         Q = session.query(AllianceHistory,
                             sizediffvalue,
                             scorediffwsizevalue,
                             )
         Q = Q.filter(AllianceHistory.current == alliance)
         Q = Q.order_by(desc(AllianceHistory.tick))
         history = Q[:ticks] if ticks else Q.all()
     else:
         history = None
     
     if not h:
         Q = session.query(AllianceHistory)
         Q = Q.filter(or_(AllianceHistory.hour == 23, AllianceHistory.tick == Updates.current_tick()))
         Q = Q.filter(AllianceHistory.current == alliance)
         Q = Q.order_by(desc(AllianceHistory.tick))
         hsummary = Q.all() if hs else Q[:14]
     else:
         hsummary = None
     
     return render(["alliance.tpl",["halliance.tpl","hsalliance.tpl"][hs]][h or hs],
                     request,
                     alliance = alliance,
                     members = alliance.intel_members,
                     history = history,
                     hsummary = hsummary,
                     ticks = ticks,
                   )
Пример #35
0
    def execute(self, message, user, params):
        
        eta, land_tick = params.groups()
        land_tick = int(land_tick)

        if eta.lower() in self.class_eta.keys():
             eta = self.class_eta[eta.lower()]
        else:
            try:
                eta = int(eta)
            except ValueError:
                message.alert("Invalid class or eta '%s'" % (eta,))
                return

        current_tick=Updates.current_tick()

        current_time = datetime.datetime.utcnow()
        tick_length = PA.getint("numbers","tick_length")
        launch_tick = land_tick - eta
        launch_time = current_time + datetime.timedelta(seconds=tick_length*(launch_tick-current_tick+1)) - datetime.timedelta(minutes=current_time.minute%(tick_length/60)+5)
        prelaunch_tick = land_tick - eta + 1
        prelaunch_mod = launch_tick - current_tick

        message.reply("eta %d landing pt %d (currently %d) must launch at pt %d (%s), or with prelaunch tick %d (currently %+d)" % (eta, land_tick, current_tick, launch_tick, (launch_time.strftime("%m-%d %H:%M")), prelaunch_tick, prelaunch_mod))
Пример #36
0
    def execute(self, message, user, params):
        planet = Planet.load(*params.group(1, 3, 5))
        if planet is None:
            message.alert("No planet with coords %s:%s:%s" %
                          params.group(1, 3, 5))
            return

        scan = params.group(6).upper()
        dists = int(params.group(7) or 0)

        request = self.request(message, user, planet, scan, dists)
        if message.get_chan() != self.scanchan():
            message.reply(
                "Requested a %s Scan of %s:%s:%s. !request cancel %s to cancel the request."
                % (
                    request.type,
                    planet.x,
                    planet.y,
                    planet.z,
                    request.id,
                ))

        scan = planet.scan(scan)
        if scan and request.tick - scan.tick < PA.getint(
                scan.scantype, "expire"):
            message.reply(
                "%s Scan of %s:%s:%s is already available from %s ticks ago: %s. !request cancel %s if this is suitable."
                % (
                    scan.scantype,
                    planet.x,
                    planet.y,
                    planet.z,
                    request.tick - scan.tick,
                    scan.link,
                    request.id,
                ))
Пример #37
0
    def new(self, message, user, params):
        tick = Updates.current_tick()
        comment = params.group(3) or ""
        when = int(params.group(1))
        if when < PA.getint("numbers", "protection"):
            eta = when
            when += tick
        elif when <= tick:
            message.alert(
                "Can not create attacks in the past. You wanted tick %s, but current tick is %s."
                % (
                    when,
                    tick,
                ))
            return
        else:
            eta = when - tick
        if when > 32767:
            when = 32767

        attack = Attack(landtick=when, comment=comment)
        session.add(attack)

        for coord in re.findall(loadable.coord, params.group(2)):
            if not coord[4]:
                galaxy = Galaxy.load(coord[0], coord[2])
                if galaxy:
                    attack.addGalaxy(galaxy)

            else:
                planet = Planet.load(coord[0], coord[2], coord[4])
                if planet:
                    attack.addPlanet(planet)

        session.commit()
        message.reply(str(attack))
Пример #38
0
    def bonus(self, message, user, params):
 
        # Check if tick is provided
        tick = int(params.group(1) or 0)

        if tick > PA.getint("numbers","last_tick"):
            message.reply("Use your bonus during the round, not after.")
            return
 
        # If there is no tick provided in the command then check what the current tick is.
        if not tick:
            # Retrieve current tick
            tick = Updates.current_tick()
            if not tick:
                # Game not ticking yet.
                message.reply("Game is not ticking yet!")
                return
 
        resources = 10000 + tick * 4800
        roids = int(6 + tick * 0.15)
        research = 4000 + tick * 24
        construction = 2000 + tick * 18
 
        message.reply("Upgrade Bonus calculation for tick {} | Resources: {:,} EACH | Roids: {:,} EACH | Research Points: {:,} | Construction Units: {:,}".format(tick, resources, roids, research, construction))
Пример #39
0
    def execute(self, message, user, params):

        alliance = Alliance()
        race = None
        size_mod = None
        size = None
        value_mod = None
        value = None
        bash = False
        attacker = user.planet
        cluster = None

        params = params.group(1).split()

        for p in params:
            m = self.bashre.match(p)
            if m and not bash:
                bash = True
                continue
            m = self.clusterre.match(p)
            if m and not cluster:
                cluster = int(m.group(1))
            m = self.racere.match(p)
            if m and not race:
                race = m.group(1)
                continue
            m = self.rangere.match(p)
            if m and not size and int(m.group(2)) < 32768:
                size_mod = m.group(1) or '>'
                size = m.group(2)
                continue
            m = self.rangere.match(p)
            if m and not value:
                value_mod = m.group(1) or '<'
                value = m.group(2)
                continue
            m = self.alliancere.match(p)
            if m and not alliance.name and not self.clusterre.match(p):
                alliance = Alliance(name="Unknown") if m.group(
                    1).lower() == "unknown" else Alliance.load(m.group(1))
                if alliance is None:
                    message.reply("No alliance matching '%s' found" %
                                  (m.group(1), ))
                    return
                continue

        maxcap = PA.getfloat("roids", "maxcap")
        mincap = PA.getfloat("roids", "mincap")
        modifier = (cast(Planet.value,
                         Float).op("/")(float(attacker.value))).op("^")(0.5)
        caprate = func.float8larger(
            mincap, func.float8smaller(modifier.op("*")(maxcap), maxcap))
        maxcap = cast(func.floor(cast(Planet.size, Float).op("*")(caprate)),
                      Integer)

        bravery = (func.float8larger(
            0.0,
            (func.float8smaller(
                2.0,
                cast(Planet.value, Float).op("/")(float(attacker.value))) -
             0.1) * (func.float8smaller(
                 2.0,
                 cast(Planet.score, Float).op("/")(float(attacker.score))) -
                     0.2))).op("*")(10.0)
        xp_gain = cast(func.floor(maxcap.op("*")(bravery)), Integer)

        Q = session.query(Planet, Intel, xp_gain.label("xp_gain"))
        if alliance.id:
            Q = Q.join(Planet.intel)
            Q = Q.filter(Intel.alliance == alliance)
        else:
            Q = Q.outerjoin(Planet.intel)
            if alliance.name:
                Q = Q.filter(Intel.alliance == None)
        Q = Q.filter(Planet.active == True)
        if race:
            Q = Q.filter(Planet.race.ilike(race))
        if size:
            Q = Q.filter(Planet.size.op(size_mod)(size))
        if value:
            Q = Q.filter(Planet.value.op(value_mod)(value))
        if bash:
            Q = Q.filter(
                or_(
                    Planet.value.op(">")(attacker.value *
                                         PA.getfloat("bash", "value")),
                    Planet.score.op(">")(attacker.score *
                                         PA.getfloat("bash", "score"))))
        if cluster:
            Q = Q.filter(Planet.x == cluster)
        Q = Q.order_by(desc("xp_gain"))
        Q = Q.order_by(desc(Planet.idle))
        Q = Q.order_by(desc(Planet.value))
        result = Q[:6]

        if len(result) < 1:
            reply = "No"
            if race:
                reply += " %s" % (race, )
            reply += " planets"
            if alliance.name:
                reply += " in intel matching Alliance: %s" % (alliance.name, )
            else:
                reply += " matching"
            if size:
                reply += " Size %s %s" % (size_mod, size)
            if value:
                reply += " Value %s %s" % (value_mod, value)
            message.reply(reply)
            return

        replies = []
        for planet, intel, xp_gain in result[:5]:
            reply = "%s:%s:%s (%s)" % (planet.x, planet.y, planet.z,
                                       planet.race)
            reply += " Value: %s Size: %s Scoregain: %d" % (
                planet.value, planet.size,
                xp_gain * PA.getint("numbers", "xp_value"))
            if intel:
                if intel.nick:
                    reply += " Nick: %s" % (intel.nick, )
                if not alliance.name and intel.alliance:
                    reply += " Alliance: %s" % (intel.alliance.name, )
            replies.append(reply)
        if len(result) > 5:
            replies[
                -1] += " (Too many results to list, please refine your search)"
        message.reply("\n".join(replies))
Пример #40
0
    def execute(self, message, user, params):
        
        name, ticks, factories = params.group(1,2,3)

        ship = Ship.load(name=name)
        if ship is None:
            message.alert("%s is not a ship." % name)
            return
        ticks = int(ticks)
        factories = int(factories)

        race = ship.race[:3].lower()
        race = "etd" if race == "eit" else race

        gov = None
        pop = 0
        for p in (params.group(4) or "").split():
            m=self.govre.match(p)
            if m and not gov:
                gov=m.group(1).lower()
                continue
            if p.isdigit() and not pop:
                pop = int(p)
                continue

        m = ship.metal
        c = ship.crystal
        e = ship.eonium
        bonus = 1 + pop/100.0
        if gov:
            m *= (1+PA.getfloat(gov,"prodcost"))
            c *= (1+PA.getfloat(gov,"prodcost"))
            e *= (1+PA.getfloat(gov,"prodcost"))
            bonus += PA.getfloat(gov,"prodtime")
        if race:
            bonus += PA.getfloat(race,"prodtime")
        cost = floor(m)+floor(c)+floor(e)

        res = int(self.revprod(ticks, factories, bonus))
        ships = int(res / cost)

        reply = "You can build %s %s (%s) in %d ticks" % (self.num2short(ships), ship.name, self.num2short(ships*ship.total_cost//PA.getint("numbers", "ship_value")), ticks)
        reply += " using %s factories" % (factories,) if factories > 1 else ""
        reply += " with a" if race or gov else ""
        reply += " %s"%(PA.get(gov,"name"),) if gov else ""
        reply += " %s"%(PA.get(race,"name"),) if race else ""
        reply += " planet" if race or gov else ""
        reply += " with %s%% population"%(pop,) if pop else ""
        message.reply(reply)
Пример #41
0
           "P": self.parse_P,
           "D": self.parse_D,
           "U": self.parse_U,
           "A": self.parse_U,
           "J": self.parse_J,
           "N": self.parse_N,
          }.get(scantype)
 if parser is not None:
     parser(scan_id, scan, page)
 
 Q = session.query(Request)
 Q = Q.filter(Request.scantype==scantype)
 Q = Q.filter(Request.target==planet)
 Q = Q.filter(Request.scan==None)
 Q = Q.filter(Request.active==True)
 Q = Q.filter(Request.tick<=tick + PA.getint(scan.scantype,"expire"))
 result = Q.all()
 
 users = []
 req_ids = []
 for request in result:
     if tick >= request.tick:
         scanlog("Scan %s matches request %s for %s" %(pa_id, request.id, request.user.name,))
         request.scan_id = scan_id
         request.active = False
         users.append(request.user.name)
         req_ids.append(str(request.id))
     else:
         scanlog("Scan %s matches request %s for %s but is old." %(pa_id, request.id, request.user.name,))
         push("scans", scantype=scantype, pa_id=pa_id, x=planet.x, y=planet.y, z=planet.z, names=request.user.name, scanner=uid, reqs=request.id, old=True)
         
Пример #42
0
            "P": self.parse_P,
            "D": self.parse_D,
            "U": self.parse_U,
            "A": self.parse_U,
            "J": self.parse_J,
            "N": self.parse_N,
        }.get(scantype)
        if parser is not None:
            parser(scan_id, scan, page)

        Q = session.query(Request)
        Q = Q.filter(Request.scantype == scantype)
        Q = Q.filter(Request.target == planet)
        Q = Q.filter(Request.scan == None)
        Q = Q.filter(Request.active == True)
        Q = Q.filter(Request.tick <= tick + PA.getint(scan.scantype, "expire"))
        result = Q.all()

        users = []
        req_ids = []
        for request in result:
            if tick >= request.tick:
                scanlog("Scan %s matches request %s for %s" % (
                    pa_id,
                    request.id,
                    request.user.name,
                ))
                request.scan_id = scan_id
                request.active = False
                users.append(request.user.name)
                req_ids.append(str(request.id))
Пример #43
0
 def planet_galaxy(self, message, user, params):
     tick = Updates.current_tick()
     when = int(params.group(6) or 0)
     if when and when < PA.getint("numbers", "protection"):
         when += tick
     elif when and when <= tick:
         message.alert("Can not check status on the past. You wanted tick %s, but current tick is %s." % (when, tick,))
         return
     
     # Planet
     if params.group(5) is not None:
         planet = Planet.load(*params.group(1,3,5))
         if planet is None:
             message.alert("No planet with coords %s:%s:%s" % params.group(1,3,5))
             return
         
         Q = session.query(User.name, Target.tick)
         Q = Q.join(Target.user)
         Q = Q.filter(Target.planet == planet)
         Q = Q.filter(Target.tick == when) if when else Q.filter(Target.tick > tick)
         Q = Q.order_by(asc(Target.tick))
         result = Q.all()
         
         if len(result) < 1:
             reply="No bookings matching planet %s:%s:%s" % (planet.x, planet.y, planet.z,)
             if when:
                 reply+=" for tick %s"%(when,)
             message.reply(reply)
             return
         
         reply="Status for %s:%s:%s - " % (planet.x, planet.y, planet.z,)
         if when:
             user, land = result[0]
             reply+="booked for landing pt %s (eta %s) by %s"%(land,land-tick,user)
         else:
             prev=[]
             for user, land in result:
                 prev.append("(%s user:%s)" % (land,user))
             reply+=", ".join(prev)
         message.reply(reply)
         return
     
     # Galaxy
     else:
         galaxy = Galaxy.load(*params.group(1,3))
         if galaxy is None:
             message.alert("No galaxy with coords %s:%s" % params.group(1,3))
             return
         
         Q = session.query(Planet.z, User.name, Target.tick)
         Q = Q.join(Target.planet)
         Q = Q.join(Target.user)
         Q = Q.filter(Planet.active == True)
         Q = Q.filter(Planet.galaxy == galaxy)
         Q = Q.filter(Target.tick == when) if when else Q.filter(Target.tick > tick)
         Q = Q.order_by(asc(Planet.z))
         result = Q.all()
         
         if len(result) < 1:
             reply="No bookings matching galaxy %s:%s" % (galaxy.x, galaxy.y,)
             if when:
                 reply+=" for tick %s"%(when,)
             message.reply(reply)
             return
         
         reply="Target information for %s:%s" % (galaxy.x, galaxy.y,)
         reply+=" landing on tick %s (eta %s): "%(when,when-tick) if when else ": "
         
         ticks={}
         for z, user, land in result:
             if not ticks.has_key(land):
                 ticks[land]=[]
             ticks[land].append((z, user,))
         sorted_keys=ticks.keys()
         sorted_keys.sort()
         
         replies = []
         for land in sorted_keys:
             prev=[]
             for z, user in ticks[land]:
                 prev.append("(%s user:%s)" % (z,user))
             replies.append("Tick %s (eta %s) "%(land,land-tick) +", ".join(prev))
         replies[0] = reply + replies[0]
         
         message.reply("\n".join(replies))
         return
Пример #44
0
    def execute(self, message, user, params):

        planet = Planet.load(*params.group(1, 3, 5))
        if planet is None:
            message.alert("No planet with coords %s:%s:%s" %
                          params.group(1, 3, 5))
            return

        tick = Updates.load().current_tick()

        pscan = planet.scan("P")
        if pscan is None:
            message.reply("No Planet Scans of %s:%s:%s found" %
                          (planet.x, planet.y, planet.z))
            return
        else:
            p_age = tick - pscan.tick
            pscan = pscan.planetscan

        dscan = planet.scan("D")
        if dscan is None:
            message.reply("No Development Scans of %s:%s:%s found" %
                          (planet.x, planet.y, planet.z))
            return
        else:
            d_age = tick - dscan.tick
            dscan = dscan.devscan

        # Get government info from pa.cfg and intel
        gov_bonus = 0
        gov = "Unknown"
        gov_alert_max = 0.00
        gov_alert_min = 0.00
        int_gov = planet.intel.gov
        if int_gov is not None:
            int_gov = int_gov[0].lower()
        for gcode in PA.options("govs"):
            gov_alert = PA.getfloat(gcode, "alert")
            if int_gov and int_gov == gcode[0]:
                gov = PA.get(gcode, "name")
                gov_bonus = gov_alert
            if gov_alert > gov_alert_max:
                gov_alert_max = gov_alert
            if gov_alert < gov_alert_min:
                gov_alert_min = gov_alert

        alert_min = int(
            (50 + 5 * min(pscan.guards / (planet.size + 1), 15)) *
            (1 + dscan.security_centre * 2 / dscan.total +
             (gov_bonus if gov != "Unknown" else gov_alert_min) + 0.0))
        alert_max = int(
            (50 + 5 * min(pscan.guards / (planet.size + 1), 15)) *
            (1 + dscan.security_centre * 2 / dscan.total +
             (gov_bonus if gov != "Unknown" else gov_alert_max) + 0.5))

        message.reply(
            "Planet: %s:%s:%s  Government: %s  Alert: %s-%s  (Scan Age P:%s D:%s)"
            % (planet.x, planet.y, planet.z, gov, alert_min, alert_max, p_age,
               d_age))
        if params.group(6):
            agents = int(params.group(6))
            max_res = user.planet.resources_per_agent(planet)
            message.reply(
                "Results:   EF: %d roids (%dXP) AD: %d agents (%dXP) SGD: %d guards (%dXP) H:SD: %1.2f%% RP (%dXP) WDM: %d ship value (%dXP)"
                % (agents / 3, self.xpcalc(agents, 1), agents,
                   self.xpcalc(agents, 2), agents * 10, self.xpcalc(agents, 3),
                   agents * 0.25, self.xpcalc(agents, 4), agents *
                   (min(50 + 10 * planet.value / user.planet.value, 100)),
                   self.xpcalc(agents, 5)))
            message.reply(
                "           IB: %d amps+dists (%dXP) H: %d buildings (%dXP) H:RT: %dM %dC %dE (%dXP) GS: %d ticks (%dXP)"
                % (agents / 15, self.xpcalc(agents, 6), agents / 20,
                   self.xpcalc(agents, 7), min(max_res, pscan.res_metal / 10),
                   min(max_res, pscan.res_crystal / 10),
                   min(max_res, pscan.res_eonium / 10), self.xpcalc(
                       agents, 8), agents / 5, self.xpcalc(agents, 9)))

            # If stealth is supplied, calculate the probability of success.
            if params.group(7):
                stealth = int(params.group(7))
                stealth = stealth - 5 - int(agents / 2)
                t = 8 - alert_min
                prob = 100 * (t + stealth) / (t + alert_max)
                if prob < 0:
                    prob = 0
                elif prob > 100:
                    prob = 100

                growth = PA.getint(user.planet.race.lower(), "sgrowth")
                from math import ceil
                message.reply(
                    "New stealth: %s  Success rate: %s%%  Recovery time: %d ticks"
                    % (stealth, prob, ceil((5.0 + int(agents / 2)) / growth)))
Пример #45
0
    def execute(self, message, user, params):
        tick = Updates.current_tick()
        # Galaxy Scan
        if params.group(5) is None:

#            Access Control:
#            Uncomment this and change "group" to the lowest group that can request galscans.
#            if not user.is_group():
#                message.alert("Insufficient access for galaxy scans.")
#                return

            galaxy = Galaxy.load(*params.group(1,3))
            if galaxy is None:
                message.alert("No galaxy with coords %s:%s" % params.group(1,3))
                return
            planets = galaxy.planets
            galscan = Config.has_option("Misc", "galscans") and Config.getboolean("Misc", "galscans")
        else:
            planet = Planet.load(*params.group(1,3,5))
            if planet is None:
                message.alert("No planet with coords %s:%s:%s" % params.group(1,3,5))
                return
            planets = [planet]
            galscan = False

        # Scan Quota
        if Config.has_section("ScanQuota"):
            opts = Config.options("ScanQuota") 
            q = []
            for o in opts:
                if int(o) >= user.access:
                    q.append(int(o))
            if q:
                ScanQuota = Config.getint("ScanQuota", str(min(q)))
                reqs = session.query(Request.id).filter(Request.requester_id == user.id).filter(Request.tick == tick).count()
                if (reqs + len(planets) * len(params.group(6).upper())) > ScanQuota:
                    message.reply("This request will exceed your scan quota for this tick (%d scans remaining). " % (ScanQuota - reqs) +\
                                  "Try searching with !planet, !dev, !unit, !news, !jgp, !au.")
                    return

        dists = int(params.group(7) or 0)
        galdists = []

        mergescans = (not galscan) and (Config.has_option("Misc", "maxscans") and len(planets)*len(params.group(6)) > Config.getint("Misc", "maxscans"))

        for planet in planets:
            if galscan or mergescans:
                galdists.append(planet.intel.dists if planet.intel else 0)
                if len(galdists) < len(planets):
                    continue
            types = 0
            for scantype in params.group(6).upper():
                # Reject requests for incoming scans
                if not PA.getboolean(scantype, "request"):
                    message.alert("%s scans cannot be requested." % (PA.get(scantype, "name")))
                    continue
                types += 1
                if galscan or mergescans:
                    # Request the scans
                    for i in range(len(planets)):
                        request = self.request(message, user, planets[i], scantype, galdists[i], galscan or mergescans)
                    # Inform the requester    
                    if galscan and (message.get_chan() != self.scanchan()):
                        message.reply("Requested a Galaxy %s Scan of %s:%s. !request cancel %s:%s to cancel the request." % (request.type, planet.x, planet.y, 
                                                                                                                             request.id-len(planets)+1, request.id))
                    # Check for existing scans
                    scan = planet.scan(scantype)
                    if scan and request.tick - scan.tick < PA.getint(scantype,"expire"):
                        message.reply("%s Scan of %s:%s:%s is already available from %s ticks ago: %s. !request cancel %s if this is suitable." % (
                                                                        scantype, planet.x, planet.y, planet.z, request.tick - scan.tick, scan.link, request.id,))
                        # Cancel requests with a 0-tick old scan, if required
                        if (request.tick == scan.tick):
                            req0age = Config.getint("Misc", "req0agej") if request.scantype == "J" else Config.getint("Misc", "req0age")
                            if req0age == 1:
                               Q = session.query(Request).filter(Request.tick == request.tick).filter(Request.planet_id == request.planet_id)
                               Q = Q.filter(Request.scantype == request.scantype).filter(Request.requester_id == request.requester_id)
                               if Q.count() == 1:
                                   request.active = False
                                   message.reply("Request %s cancelled due to an existing scan. If you really need a newer one, repeat your scan request." % (request.id))
                                   message.privmsg("Cancelled scan request %s due to existing scan" % (request.id), self.scanchan())
                            elif req0age == 0:
                                request.active = False
                                message.reply("Request %s cancelled due to an existing scan." % (request.id))
                                message.privmsg("Cancelled scan request %s due to existing scan" % (request.id), self.scanchan())

                    # Tell the scanners
                    requester = user.name if not Config.getboolean("Misc", "anonscans") else "Anon"
                    if galscan:
                        message.privmsg("[%s:%s] %s requested a Galaxy %s Scan of %s:%s Max Dists(i:%s%s) " % (request.id-len(planets)+1, request.id, requester, 
                                        request.type, planet.x, planet.y, max(galdists), 
                                        "/r:%s" % dists if dists > 0 else "") + Config.get("URL", "reqgscan") % (planet.x, planet.y) , self.scanchan())
                else:
                    request = self.request(message, user, planet, scantype, dists)
                    if message.get_chan() != self.scanchan():
                        message.reply("Requested a %s Scan of %s:%s:%s. !request cancel %s to cancel the request." % (request.type, planet.x, planet.y, planet.z, request.id,))

                    # Check for existing scans
                    scan = planet.scan(scantype)
                    if scan and request.tick - scan.tick < PA.getint(scan.scantype,"expire"):
                        message.reply("%s Scan of %s:%s:%s is already available from %s ticks ago: %s. !request cancel %s if this is suitable." % (
                                                                        scantype, planet.x, planet.y, planet.z, request.tick - scan.tick, scan.link, request.id,))
                        # Cancel requests with a 0-tick old scan, if required
                        if (request.tick == scan.tick):
                            req0age = Config.getint("Misc", "req0agej") if request.scantype == "J" else Config.getint("Misc", "req0age")
                            if req0age == 1:
                               Q = session.query(Request).filter(Request.tick == request.tick).filter(Request.planet_id == request.planet_id)
                               Q = Q.filter(Request.scantype == request.scantype).filter(Request.requester_id == request.requester_id)
                               if Q.count() == 1:
                                   request.active = False
                                   message.reply("Request %s cancelled due to an existing scan. If you really need a newer one, repeat your scan request." % (request.id))
                                   message.privmsg("Cancelled scan request %s due to existing scan" % (request.id), self.scanchan())
                            elif req0age == 0:
                                request.active = False
                                message.reply("Request %s cancelled due to an existing scan." % (request.id))
                                message.privmsg("Cancelled scan request %s due to existing scan" % (request.id), self.scanchan())

            if mergescans:
                message.reply("Requested %d scans. !request cancel %s:%s to cancel the request." % (len(planets) * types, request.id-len(planets)*types+1, request.id))
                message.privmsg("[%s:%s] %s requested %d scans (%s) Max Dists(i:%s%s). !request links for details " % (request.id-len(planets)*types+1, request.id, 
                                requester, len(planets)*types, params.group(6).upper(), max(galdists), "/r:%s" % dists if dists > 0 else ""), self.scanchan())
        session.commit()
Пример #46
0
    def execute(self, message, user, params):
        tick = Updates.current_tick()
        # Galaxy Scan
        if params.group(5) is None:

            #            Access Control:
            #            Uncomment this and change "group" to the lowest group that can request galscans.
            #            if not user.is_group():
            #                message.alert("Insufficient access for galaxy scans.")
            #                return

            galaxy = Galaxy.load(*params.group(1, 3))
            if galaxy is None:
                message.alert("No galaxy with coords %s:%s" % params.group(1, 3))
                return
            planets = galaxy.planets
            galscan = Config.has_option("Misc", "galscans") and Config.getboolean("Misc", "galscans")
        else:
            planet = Planet.load(*params.group(1, 3, 5))
            if planet is None:
                message.alert("No planet with coords %s:%s:%s" % params.group(1, 3, 5))
                return
            planets = [planet]
            galscan = False

        # Scan Quota
        if Config.has_section("ScanQuota"):
            opts = Config.options("ScanQuota")
            q = []
            for o in opts:
                if int(o) >= user.access:
                    q.append(int(o))
            if q:
                ScanQuota = Config.getint("ScanQuota", str(min(q)))
                reqs = (
                    session.query(Request.id)
                    .filter(Request.requester_id == user.id)
                    .filter(Request.tick == tick)
                    .count()
                )
                if (reqs + len(planets) * len(params.group(6).upper())) > ScanQuota:
                    message.reply(
                        "This request will exceed your scan quota for this tick (%d scans remaining). "
                        % (ScanQuota - reqs)
                        + "Try searching with !planet, !dev, !unit, !news, !jgp, !au."
                    )
                    return

        dists = int(params.group(7) or 0)
        galdists = []

        mergescans = (not galscan) and (
            Config.has_option("Misc", "maxscans")
            and len(planets) * len(params.group(6)) > Config.getint("Misc", "maxscans")
        )

        for planet in planets:
            if galscan or mergescans:
                galdists.append(planet.intel.dists if planet.intel else 0)
                if len(galdists) < len(planets):
                    continue
            types = 0
            for scantype in params.group(6).upper():
                # Reject requests for incoming scans
                if not PA.getboolean(scantype, "request"):
                    message.alert("%s scans cannot be requested." % (PA.get(scantype, "name")))
                    continue
                types += 1
                if galscan or mergescans:
                    # Request the scans
                    for i in range(len(planets)):
                        request = self.request(message, user, planets[i], scantype, galdists[i], galscan or mergescans)
                    # Inform the requester
                    if galscan and (message.get_chan() != self.scanchan()):
                        message.reply(
                            "Requested a Galaxy %s Scan of %s:%s. !request cancel %s:%s to cancel the request."
                            % (request.type, planet.x, planet.y, request.id - len(planets) + 1, request.id)
                        )
                    # Check for existing scans
                    scan = planet.scan(scantype)
                    if scan and request.tick - scan.tick < PA.getint(scantype, "expire"):
                        message.reply(
                            "%s Scan of %s:%s:%s is already available from %s ticks ago: %s. !request cancel %s if this is suitable."
                            % (scantype, planet.x, planet.y, planet.z, request.tick - scan.tick, scan.link, request.id)
                        )
                        # Cancel requests with a 0-tick old scan, if required
                        if request.tick == scan.tick:
                            req0age = (
                                Config.getint("Misc", "req0agej")
                                if request.scantype == "J"
                                else Config.getint("Misc", "req0age")
                            )
                            if req0age == 1:
                                Q = (
                                    session.query(Request)
                                    .filter(Request.tick == request.tick)
                                    .filter(Request.planet_id == request.planet_id)
                                )
                                Q = Q.filter(Request.scantype == request.scantype).filter(
                                    Request.requester_id == request.requester_id
                                )
                                if Q.count() == 1:
                                    request.active = False
                                    message.reply(
                                        "Request %s cancelled due to an existing scan. If you really need a newer one, repeat your scan request."
                                        % (request.id)
                                    )
                                    message.privmsg(
                                        "Cancelled scan request %s due to existing scan" % (request.id), self.scanchan()
                                    )
                            elif req0age == 0:
                                request.active = False
                                message.reply("Request %s cancelled due to an existing scan." % (request.id))
                                message.privmsg(
                                    "Cancelled scan request %s due to existing scan" % (request.id), self.scanchan()
                                )

                    # Tell the scanners
                    requester = user.name if not Config.getboolean("Misc", "anonscans") else "Anon"
                    if galscan:
                        message.privmsg(
                            "[%s:%s] %s requested a Galaxy %s Scan of %s:%s Max Dists(i:%s%s) "
                            % (
                                request.id - len(planets) + 1,
                                request.id,
                                requester,
                                request.type,
                                planet.x,
                                planet.y,
                                max(galdists),
                                "/r:%s" % dists if dists > 0 else "",
                            )
                            + Config.get("URL", "reqgscan") % (planet.x, planet.y),
                            self.scanchan(),
                        )
                else:
                    request = self.request(message, user, planet, scantype, dists)
                    if message.get_chan() != self.scanchan():
                        message.reply(
                            "Requested a %s Scan of %s:%s:%s. !request cancel %s to cancel the request."
                            % (request.type, planet.x, planet.y, planet.z, request.id)
                        )

                    # Check for existing scans
                    scan = planet.scan(scantype)
                    if scan and request.tick - scan.tick < PA.getint(scan.scantype, "expire"):
                        message.reply(
                            "%s Scan of %s:%s:%s is already available from %s ticks ago: %s. !request cancel %s if this is suitable."
                            % (scantype, planet.x, planet.y, planet.z, request.tick - scan.tick, scan.link, request.id)
                        )
                        # Cancel requests with a 0-tick old scan, if required
                        if request.tick == scan.tick:
                            req0age = (
                                Config.getint("Misc", "req0agej")
                                if request.scantype == "J"
                                else Config.getint("Misc", "req0age")
                            )
                            if req0age == 1:
                                Q = (
                                    session.query(Request)
                                    .filter(Request.tick == request.tick)
                                    .filter(Request.planet_id == request.planet_id)
                                )
                                Q = Q.filter(Request.scantype == request.scantype).filter(
                                    Request.requester_id == request.requester_id
                                )
                                if Q.count() == 1:
                                    request.active = False
                                    message.reply(
                                        "Request %s cancelled due to an existing scan. If you really need a newer one, repeat your scan request."
                                        % (request.id)
                                    )
                                    message.privmsg(
                                        "Cancelled scan request %s due to existing scan" % (request.id), self.scanchan()
                                    )
                            elif req0age == 0:
                                request.active = False
                                message.reply("Request %s cancelled due to an existing scan." % (request.id))
                                message.privmsg(
                                    "Cancelled scan request %s due to existing scan" % (request.id), self.scanchan()
                                )

            if mergescans:
                message.reply(
                    "Requested %d scans. !request cancel %s:%s to cancel the request."
                    % (len(planets) * types, request.id - len(planets) * types + 1, request.id)
                )
                message.privmsg(
                    "[%s:%s] %s requested %d scans (%s) Max Dists(i:%s%s). !request links for details "
                    % (
                        request.id - len(planets) * types + 1,
                        request.id,
                        requester,
                        len(planets) * types,
                        params.group(6).upper(),
                        max(galdists),
                        "/r:%s" % dists if dists > 0 else "",
                    ),
                    self.scanchan(),
                )
        session.commit()
Пример #47
0
    def execute(self, message, user, params):

        num, name, target = params.groups()
        target = (target or "t1").lower()

        ship = Ship.load(name=name)
        num = self.short2num(num)
        if ship is None:
            message.alert("No Ship called: %s" % (name, ))
            return
        efficiency = PA.getfloat("teffs", target.lower())
        target_class = getattr(ship, target)
        if ship.damage:
            total_damage = ship.damage * num
        if ship.t1 == "Roids":
            killed = total_damage // 50
            message.reply("%s %s (%s) will capture Asteroid: %s (%s)" % (
                num,
                ship.name,
                self.num2short(num * ship.total_cost //
                               PA.getint("numbers", "ship_value")),
                killed,
                self.num2short(killed * PA.getint("numbers", "roid_value")),
            ))
            return
        if ship.t1 == "Resources":
            killed = total_damage * 50
            message.reply("%s %s (%s) will capture Resource: %s (%s)" % (
                num,
                ship.name,
                self.num2short(num * ship.total_cost //
                               PA.getint("numbers", "ship_value")),
                self.num2short(killed),
                self.num2short(killed // PA.getint("numbers", "res_value")),
            ))
            return
        if ship.t1[:6] == "Struct":
            killed = total_damage // 500
            message.reply("%s %s (%s) will destroy Structure: %s (%s)" % (
                num,
                ship.name,
                self.num2short(num * ship.total_cost //
                               PA.getint("numbers", "ship_value")),
                killed,
                self.num2short(killed * PA.getint("numbers", "cons_value")),
            ))
            return
        targets = session.query(Ship).filter(Ship.class_ == target_class)
        if targets.count() == 0:
            message.reply(
                "%s does not have any targets in that category (%s)" %
                (ship.name, target))
            return
        reply = "%s %s (%s) hitting %s will " % (
            num, ship.name,
            self.num2short(num * ship.total_cost //
                           PA.getint("numbers", "ship_value")), target_class)
        if ship.type.lower()[:4] == "norm" or ship.type.lower() == 'cloak':
            reply += "destroy "
        elif ship.type.lower() == "emp":
            reply += "hug "
        elif ship.type.lower() == "steal":
            reply += "steal "
        else:
            raise Exception("Erroneous type %s" % (ship.type, ))
        for target in targets:
            if ship.type.lower() == "emp":
                killed = int(efficiency * ship.guns * num *
                             float(100 - target.empres) / 100)
            else:
                killed = int(efficiency * total_damage / target.armor)
            reply += "%s: %s (%s) " % (target.name, killed,
                                       self.num2short(
                                           target.total_cost * killed //
                                           PA.getint("numbers", "ship_value")))
        message.reply(reply)
Пример #48
0
    def execute(self, request, user, id, x, y, z, when):
        planet = Planet.load(x, y, z)
        if planet is None:
            return self.attack(request, user, id,
                               "No planet with coords %s:%s:%s" % (
                                   x,
                                   y,
                                   z,
                               ))

        tick = Updates.current_tick()
        when = int(when or 0)
        if 0 < when < PA.getint("numbers", "protection"):
            eta = when
            when += tick
        elif 0 < when <= tick:
            return self.attack(
                request, user, id,
                "Can not unbook targets in the past. You wanted tick %s, but current tick is %s."
                % (
                    when,
                    tick,
                ))
        else:
            eta = when - tick
        if when > 32767:
            when = 32767

        Q = session.query(Target)
        Q = Q.join(Target.user)
        Q = Q.filter(Target.planet == planet)
        Q = Q.filter(Target.user == user)
        Q = Q.filter(Target.tick == when) if when else Q.filter(
            Target.tick >= tick)
        Q = Q.order_by(asc(Target.tick))
        result = Q.all()
        for target in result:
            session.delete(target)
        count = len(result)
        session.commit()

        if count < 1:
            reply = "You have no bookings matching %s:%s:%s" % (
                planet.x,
                planet.y,
                planet.z,
            )
            if when:
                reply += " for landing on tick %s" % (when, )
        else:
            reply = "You have unbooked %s:%s:%s" % (
                planet.x,
                planet.y,
                planet.z,
            )
            if when:
                reply += " for landing pt %s" % (when, )
            else:
                reply += " for %d booking(s)" % (count, )

        return self.attack(request, user, id, reply)
Пример #49
0
    def planet_galaxy(self, message, user, params):
        tick = Updates.current_tick()
        when = int(params.group(6) or 0)
        if when and when < PA.getint("numbers", "protection"):
            when += tick
        elif when and when <= tick:
            message.alert(
                "Can not check status on the past. You wanted tick %s, but current tick is %s."
                % (
                    when,
                    tick,
                ))
            return

        # Planet
        if params.group(5) is not None:
            planet = Planet.load(*params.group(1, 3, 5))
            if planet is None:
                message.alert("No planet with coords %s:%s:%s" %
                              params.group(1, 3, 5))
                return

            Q = session.query(User.name, Target.tick)
            Q = Q.join(Target.user)
            Q = Q.filter(Target.planet == planet)
            Q = Q.filter(Target.tick == when) if when else Q.filter(
                Target.tick > tick)
            Q = Q.order_by(asc(Target.tick))
            result = Q.all()

            if len(result) < 1:
                reply = "No bookings matching planet %s:%s:%s" % (
                    planet.x,
                    planet.y,
                    planet.z,
                )
                if when:
                    reply += " for tick %s" % (when, )
                message.reply(reply)
                return

            reply = "Status for %s:%s:%s - " % (
                planet.x,
                planet.y,
                planet.z,
            )
            if when:
                user, land = result[0]
                reply += "booked for landing pt %s (eta %s) by %s" % (
                    land, land - tick, user)
            else:
                prev = []
                for user, land in result:
                    prev.append("(%s user:%s)" % (land, user))
                reply += ", ".join(prev)
            message.reply(reply)
            return

        # Galaxy
        else:
            galaxy = Galaxy.load(*params.group(1, 3))
            if galaxy is None:
                message.alert("No galaxy with coords %s:%s" %
                              params.group(1, 3))
                return

            Q = session.query(Planet.z, User.name, Target.tick)
            Q = Q.join(Target.planet)
            Q = Q.join(Target.user)
            Q = Q.filter(Planet.active == True)
            Q = Q.filter(Planet.galaxy == galaxy)
            Q = Q.filter(Target.tick == when) if when else Q.filter(
                Target.tick > tick)
            Q = Q.order_by(asc(Planet.z))
            result = Q.all()

            if len(result) < 1:
                reply = "No bookings matching galaxy %s:%s" % (
                    galaxy.x,
                    galaxy.y,
                )
                if when:
                    reply += " for tick %s" % (when, )
                message.reply(reply)
                return

            reply = "Target information for %s:%s" % (
                galaxy.x,
                galaxy.y,
            )
            reply += " landing on tick %s (eta %s): " % (
                when, when - tick) if when else ": "

            ticks = {}
            for z, user, land in result:
                if not ticks.has_key(land):
                    ticks[land] = []
                ticks[land].append((
                    z,
                    user,
                ))
            sorted_keys = ticks.keys()
            sorted_keys.sort()

            replies = []
            for land in sorted_keys:
                prev = []
                for z, user in ticks[land]:
                    prev.append("(%s user:%s)" % (z, user))
                replies.append("Tick %s (eta %s) " % (land, land - tick) +
                               ", ".join(prev))
            replies[0] = reply + replies[0]

            message.reply("\n".join(replies))
            return
Пример #50
0
    def execute(self, message, user, params):
        
        alliance=Alliance()
        race=None
        size_mod=None
        size=None
        value_mod=None
        value=None
        bash=False
        attacker=user.planet
        cluster=None

        params=params.group(1).split()

        for p in params:
            m=self.bashre.match(p)
            if m and not bash:
                bash=True
                continue
            m=self.clusterre.match(p)
            if m and not cluster:
                cluster=int(m.group(1))
            m=self.racere.match(p)
            if m and not race:
                race=m.group(1)
                continue
            m=self.rangere.match(p)
            if m and not size and int(m.group(2)) < 32768:
                size_mod=m.group(1) or '>'
                size=m.group(2)
                continue
            m=self.rangere.match(p)
            if m and not value:
                value_mod=m.group(1) or '<'
                value=m.group(2)
                continue
            m=self.alliancere.match(p)
            if m and not alliance.name and not self.clusterre.match(p):
                alliance = Alliance(name="Unknown") if m.group(1).lower() == "unknown" else Alliance.load(m.group(1))
                if alliance is None:
                    message.reply("No alliance matching '%s' found" % (m.group(1),))
                    return
                continue

        maxcap = PA.getfloat("roids","maxcap")
        mincap = PA.getfloat("roids","mincap")
        modifier = (cast(Planet.value,Float).op("/")(float(attacker.value))).op("^")(0.5)
        caprate = func.greatest(mincap,func.least(modifier.op("*")(maxcap),maxcap))
        maxcap = cast(func.floor(cast(Planet.size,Float).op("*")(caprate)),Integer)
        
        bravery = (func.greatest(0.0,( func.least(2.0, cast(Planet.value,Float).op("/")(float(attacker.value)))-0.1) * (func.least(2.0, cast(Planet.score,Float).op("/")(float(attacker.score)))-0.2))).op("*")(10.0)
        xp_gain = cast(func.floor(maxcap.op("*")(bravery)),Integer)
        
        Q = session.query(Planet, Intel, xp_gain.label("xp_gain"))
        if alliance.id:
            Q = Q.join(Planet.intel)
            Q = Q.filter(Intel.alliance == alliance)
        else:
            Q = Q.outerjoin(Planet.intel)
            if alliance.name:
                Q = Q.filter(Intel.alliance == None)
        Q = Q.filter(Planet.active == True)
        if race:
            Q = Q.filter(Planet.race.ilike(race))
        if size:
            Q = Q.filter(Planet.size.op(size_mod)(size))
        if value:
            Q = Q.filter(Planet.value.op(value_mod)(value))
        if bash:
            Q = Q.filter(or_(Planet.value.op(">")(attacker.value*PA.getfloat("bash","value")),
                             Planet.score.op(">")(attacker.score*PA.getfloat("bash","score"))))
        if cluster:
            Q = Q.filter(Planet.x == cluster)
        Q = Q.order_by(desc("xp_gain"))
        Q = Q.order_by(desc(Planet.idle))
        Q = Q.order_by(desc(Planet.value))
        result = Q[:6]
        
        if len(result) < 1:
            reply="No"
            if race:
                reply+=" %s"%(race,)
            reply+=" planets"
            if alliance.name:
                reply+=" in intel matching Alliance: %s"%(alliance.name,)
            else:
                reply+=" matching"
            if size:
                reply+=" Size %s %s" % (size_mod,size)
            if value:
                reply+=" Value %s %s" % (value_mod,value)
            message.reply(reply)
            return
        
        replies = []
        for planet, intel, xp_gain in result[:5]:
            reply="%s:%s:%s (%s)" % (planet.x,planet.y,planet.z,planet.race)
            reply+=" Value: %s Size: %s Scoregain: %d" % (planet.value,planet.size, xp_gain*PA.getint("numbers", "xp_value"))
            if intel:
                if intel.nick:
                    reply+=" Nick: %s" % (intel.nick,)
                if not alliance.name and intel.alliance:
                    reply+=" Alliance: %s" % (intel.alliance.name,)
            replies.append(reply)
        if len(result) > 5:
            replies[-1]+=" (Too many results to list, please refine your search)"
        message.reply("\n".join(replies))
Пример #51
0
    def execute(self, request, user, x, y, z, h=False, hs=False, ticks=None):
        planet = Planet.load(x, y, z)
        if planet is None:
            return HttpResponseRedirect(reverse("planet_ranks"))

        ticks = int(ticks or 0) if (h or hs) else 12

        if not hs:
            sizediffvalue = PlanetHistory.rdiff * PA.getint(
                "numbers", "roid_value")
            valuediffwsizevalue = PlanetHistory.vdiff - sizediffvalue
            resvalue = valuediffwsizevalue * PA.getint("numbers", "res_value")
            shipvalue = valuediffwsizevalue * PA.getint(
                "numbers", "ship_value")
            xpvalue = PlanetHistory.xdiff * PA.getint("numbers", "xp_value")
            Q = session.query(
                PlanetHistory,
                sizediffvalue,
                valuediffwsizevalue,
                resvalue,
                shipvalue,
                xpvalue,
            )
            Q = Q.filter(PlanetHistory.current == planet)
            Q = Q.order_by(desc(PlanetHistory.tick))
            history = Q[:ticks] if ticks else Q.all()
        else:
            history = None

        if not (h or hs):
            landings = session.query(
                PlanetLandings.hour,
                count()).filter(PlanetLandings.planet == planet).group_by(
                    PlanetLandings.hour).all()
            landed = session.query(
                PlanetLandedOn.hour,
                count()).filter(PlanetLandedOn.planet == planet).group_by(
                    PlanetLandedOn.hour).all()
            vdrops = session.query(
                PlanetValueDrops.hour,
                count()).filter(PlanetValueDrops.planet == planet).group_by(
                    PlanetValueDrops.hour).all()
            idles = session.query(PlanetIdles.hour, count()).filter(
                PlanetIdles.planet == planet).group_by(PlanetIdles.hour).all()
            hourstats = {
                'landings': dict(landings),
                'landingsT': sum([c for hour, c in landings]),
                'landed': dict(landed),
                'landedT': sum([c for hour, c in landed]),
                'vdrops': dict(vdrops),
                'vdropsT': sum([c for hour, c in vdrops]),
                'idles': dict(idles),
                'idlesT': sum([c for hour, c in idles]),
            }
        else:
            hourstats = None

        if not h:
            Q = session.query(PlanetHistory)
            Q = Q.filter(
                or_(PlanetHistory.hour == 23,
                    PlanetHistory.tick == Updates.current_tick()))
            Q = Q.filter(PlanetHistory.current == planet)
            Q = Q.order_by(desc(PlanetHistory.tick))
            hsummary = Q.all() if hs else Q[:14]
        else:
            hsummary = None

        return render(
            ["planet.tpl", ["hplanet.tpl", "hsplanet.tpl"][hs]][h or hs],
            request,
            planet=planet,
            history=history,
            hour=datetime.utcnow().hour,
            hourstats=hourstats,
            hsummary=hsummary,
            ticks=ticks,
        )
Пример #52
0
    def execute(self, message, user, params):
        
        planet = Planet.load(*params.group(1,3,5))
        if planet is None:
            message.alert("No planet with coords %s:%s:%s" % params.group(1,3,5))
            return

        tick=Updates.load().current_tick()

        pscan = planet.scan("P")
        if pscan is None:
            message.reply("No Planet Scans of %s:%s:%s found"%(planet.x,planet.y,planet.z))
            return
        else:
            p_age = tick - pscan.tick
            pscan = pscan.planetscan

        dscan = planet.scan("D")
        if dscan is None:
            message.reply("No Development Scans of %s:%s:%s found"%(planet.x,planet.y,planet.z))
            return
        else:
            d_age = tick - dscan.tick
            dscan = dscan.devscan

        # Get government info from pa.cfg and intel
        gov_bonus = 0
        gov = "Unknown"
        gov_alert_max = 0.00
        gov_alert_min = 0.00
        int_gov = planet.intel.gov
        if int_gov is not None:
            int_gov = int_gov[0].lower()
        for gcode in PA.options("govs"):
            gov_alert = PA.getfloat(gcode, "alert")
            if int_gov and int_gov == gcode[0]:
                gov = PA.get(gcode, "name")
                gov_bonus = gov_alert
            if gov_alert > gov_alert_max:
                gov_alert_max = gov_alert
            if gov_alert < gov_alert_min:
                gov_alert_min = gov_alert


        alert_min = int((50+5*min(pscan.guards/(planet.size+1),15))*(1+dscan.security_centre*0.0275 + (gov_bonus if gov != "Unknown" else gov_alert_min) + 0.0))
        alert_max = int((50+5*min(pscan.guards/(planet.size+1),15))*(1+dscan.security_centre*0.0275 + (gov_bonus if gov != "Unknown" else gov_alert_max) + 0.5))

        message.reply("Planet: %s:%s:%s  Government: %s  Alert: %s-%s  (Scan Age P:%s D:%s)" % (planet.x, planet.y, planet.z, gov, alert_min, alert_max, p_age, d_age))
        if params.group(6):
            agents = int(params.group(6))
            max_res = user.planet.resources_per_agent(planet)
            message.reply("Results:   EF: %d roids (%dXP) AD: %d agents (%dXP) SGD: %d guards (%dXP) H:SD: %1.2f%% RP (%dXP) WDM: %d ship value (%dXP)" % (agents //3, 
                     self.xpcalc(agents,1), agents, self.xpcalc(agents,2), agents*10, self.xpcalc(agents,3), agents*0.25, self.xpcalc(agents,4), 
                     agents*(min(50+10*planet.value//user.planet.value, 100)), self.xpcalc(agents,5)))
            message.reply("           IB: %d amps+dists (%dXP) H: %d buildings (%dXP) H:RT: %dM %dC %dE (%dXP) GS: %d ticks (%dXP)" % (agents//15, self.xpcalc(agents,6),
                     agents//20, self.xpcalc(agents,7), min(max_res, pscan.res_metal//10), min(max_res, pscan.res_crystal//10), min(max_res, pscan.res_eonium//10),
                     self.xpcalc(agents,8), agents//5, self.xpcalc(agents,9)))

            # If stealth is supplied, calculate the probability of success.
            if params.group(7):
                stealth = int(params.group(7))
                stealth = stealth - 5 - int(agents/2)
                t=8-alert_min
                prob = 100*(t+stealth)//(t+alert_max)
                if prob < 0:
                    prob = 0
                elif prob > 100:
                    prob = 100

                growth = PA.getint(user.planet.race.lower(), "sgrowth")
                from math import ceil
                message.reply("New stealth: %s  Success rate: %s%%  Recovery time: %d ticks" % (stealth, prob, ceil((5.0+int(agents/2))/growth)))
Пример #53
0
    def execute(self, request, user, id, x, y, z, when):
        planet = Planet.load(x, y, z)
        if planet is None:
            return self.attack(request, user, id,
                               "No planet with coords %s:%s:%s" % (
                                   x,
                                   y,
                                   z,
                               ))

        tick = Updates.current_tick()
        when = int(when)
        if when < PA.getint("numbers", "protection"):
            eta = when
            when += tick
        elif when <= tick:
            return self.attack(
                request, user, id,
                "Can not book targets in the past. You wanted tick %s, but current tick is %s."
                % (
                    when,
                    tick,
                ))
        else:
            eta = when - tick
        if when > 32767:
            when = 32767

        if planet.intel and planet.alliance and planet.alliance.name == Config.get(
                "Alliance", "name"):
            return self.attack(
                request, user, id,
                "%s:%s:%s is %s in %s. Quick, launch before they notice!" % (
                    x,
                    y,
                    z,
                    planet.intel.nick or 'someone',
                    Config.get("Alliance", "name"),
                ))

        try:
            planet.bookings.append(Target(user=user, tick=when))
            session.commit()
        except IntegrityError:
            session.rollback()
            target = planet.bookings.filter(Target.tick == when).first()
            if target is not None:
                return self.attack(
                    request, user, id,
                    "Target %s:%s:%s is already booked for landing tick %s by user %s"
                    % (
                        x,
                        y,
                        z,
                        when,
                        target.user.name,
                    ))
        else:
            return self.attack(
                request, user, id,
                "Booked landing on %s:%s:%s tick %s (eta %s) for user %s" % (
                    x,
                    y,
                    z,
                    when,
                    (when - tick),
                    user.name,
                ))

        return self.attack(request, user, id)
Пример #54
0
    def execute(self, message, user, params, override):
        planet = Planet.load(*params.group(1, 3, 5))
        if planet is None:
            message.alert("No planet with coords %s:%s:%s" %
                          params.group(1, 3, 5))
            return

        tick = Updates.current_tick()
        when = int(params.group(6) or 0)
        if 0 < when < PA.getint("numbers", "protection"):
            when += tick
        elif 0 < when <= tick:
            message.alert(
                "Can not unbook targets in the past. You wanted tick %s, but current tick is %s."
                % (
                    when,
                    tick,
                ))
            return
        if when > 32767:
            when = 32767

        Q = session.query(Target)
        Q = Q.join(Target.user)
        Q = Q.filter(Target.planet == planet)
        Q = Q.filter(Target.user == user) if override is False else Q
        Q = Q.filter(Target.tick == when) if when else Q.filter(
            Target.tick >= tick)
        Q = Q.order_by(asc(Target.tick))
        result = Q.all()
        for target in result:
            session.delete(target)
        count = len(result)
        session.commit()

        if count < 1:
            reply = ("You have no " if override is False else
                     "No ") + "bookings matching %s:%s:%s" % (
                         planet.x,
                         planet.y,
                         planet.z,
                     )
            if when:
                reply += " for landing on tick %s" % (when, )
            reply += ". If you are trying to unbook someone else's target, you must confirm with 'yes'." if override is False else ""
        else:
            reply = "You have unbooked %s:%s:%s" % (
                planet.x,
                planet.y,
                planet.z,
            )
            if when:
                reply += " for landing pt %s" % (when, )
                if override:
                    reply += " (previously held by user %s)" % (
                        result[0].user.name)
            else:
                reply += " for %d booking(s)" % (count, )
                if override:
                    prev = []
                    for target in result:
                        prev.append("(%s user:%s)" %
                                    (target.tick, target.user.name))
                    reply += ": " + ", ".join(prev)

            reply += "."
        message.reply(reply)
        return
Пример #55
0
    def execute(self, message, user, params):

        alliance = Alliance(name="Unknown") if params.group(
            1).lower() == "unknown" else Alliance.load(params.group(1))
        if alliance is None:
            message.reply("No alliance matching '%s' found" %
                          (params.group(1), ))
            return

        tick = Updates.current_tick()

        when = int(params.group(2) or 0)
        if when and when < PA.getint("numbers", "protection"):
            when += tick
        elif when and when <= tick:
            message.alert(
                "Can not check status on the past. You wanted tick %s, but current tick is %s."
                % (
                    when,
                    tick,
                ))
            return

        Q = session.query(Planet, User.name, Target.tick)
        Q = Q.join(Target.planet)
        Q = Q.join(Planet.intel) if alliance.id else Q.outerjoin(Planet.intel)
        Q = Q.join(Target.user)
        Q = Q.filter(Planet.active == True)
        Q = Q.filter(Intel.alliance == (alliance if alliance.id else None))
        Q = Q.filter(Target.tick == when) if when else Q.filter(
            Target.tick > tick)
        Q = Q.order_by(asc(Planet.x))
        Q = Q.order_by(asc(Planet.y))
        Q = Q.order_by(asc(Planet.z))
        result = Q.all()

        if len(result) < 1:
            reply = "No active bookings matching alliance %s" % (alliance.name)
            if when:
                reply += " for tick %s." % (when, )
            message.reply(reply)
            return

        reply = "Target information for %s" % (alliance.name)
        reply += " landing on tick %s (eta %s): " % (when, when -
                                                     tick) if when else ": "

        ticks = {}
        for planet, user, land in result:
            if not ticks.has_key(land):
                ticks[land] = []
            ticks[land].append((
                planet,
                user,
            ))
        sorted_keys = ticks.keys()
        sorted_keys.sort()

        replies = []
        for land in sorted_keys:
            prev = []
            for planet, user in ticks[land]:
                prev.append("(%s:%s:%s %s)" %
                            (planet.x, planet.y, planet.z, user))
            replies.append("Tick %s (eta %s) " % (land, land - tick) +
                           ", ".join(prev))
        replies[0] = reply + replies[0]

        message.reply("\n".join(replies))
Пример #56
0
    def execute(self, message, user, params):
        planet = Planet.load(*params.group(1, 3, 5))
        if planet is None:
            message.alert("No planet with coords %s:%s:%s" %
                          params.group(1, 3, 5))
            return

        tick = Updates.current_tick()
        when = int(params.group(6))
        if when < PA.getint("numbers", "protection"):
            eta = when
            when += tick
        elif when <= tick:
            message.alert(
                "Can not book targets in the past. You wanted tick %s, but current tick is %s."
                % (
                    when,
                    tick,
                ))
            return
        else:
            eta = when - tick
        if when > 32767:
            when = 32767

        override = params.group(7)
        later = params.group(8)

        if planet.intel and planet.alliance and planet.alliance.name == Config.get(
                "Alliance", "name"):
            message.reply(
                "%s:%s:%s is %s in %s. Quick, launch before they notice the highlight."
                % (
                    planet.x,
                    planet.y,
                    planet.z,
                    planet.intel.nick or 'someone',
                    Config.get("Alliance", "name"),
                ))
            return

        free, book1, book2 = self.get_free_book(planet, when, later)

        if free is None:
            if later is None:
                message.reply(
                    "Target %s:%s:%s is already booked for landing tick %s by user %s"
                    % (
                        planet.x,
                        planet.y,
                        planet.z,
                        when,
                        book1.user.name,
                    ))
            else:
                message.reply(
                    "You cannot hit %s:%s:%s. Not even sloppy seconds. This target is more taken than your mum, amirite?"
                    % (
                        planet.x,
                        planet.y,
                        planet.z,
                    ))
            return

        if override is None and later is None:
            books = planet.bookings.filter(Target.tick >= when).order_by(
                asc(Target.tick)).all()
            if len(books) >= 1:
                reply = "There are already bookings for that target after landing pt %s (eta %s). To see status on this target, do !status %s:%s:%s." % (
                    when,
                    eta,
                    planet.x,
                    planet.y,
                    planet.z,
                )
                reply += " To force booking at your desired eta/landing tick, use !book %s:%s:%s %s yes (Bookers: " % (
                    planet.x,
                    planet.y,
                    planet.z,
                    when,
                )
                prev = []
                for book in books:
                    prev.append("(%s user:%s)" % (
                        book.tick,
                        book.user.name,
                    ))
                reply += ", ".join(prev) + ")"
                message.reply(reply)
                return

        if free == when:
            reply = "Booked landing on %s:%s:%s tick %s (eta %s) for user %s" % (
                planet.x,
                planet.y,
                planet.z,
                free,
                (free - tick),
                user.name,
            )
        elif free == when + 1:
            reply = "You have been beaten to %s:%s:%s by %s. You are now getting sloppy seconds at tick %s (eta %s)" % (
                planet.x,
                planet.y,
                planet.z,
                book1.user.name,
                free,
                (free - tick),
            )
        elif free == when + 2:
            reply = "You've been beaten to %s:%s:%s by %s and %s you slow retarded f****t. I feel sorry for you, so have tick %s (eta %s)" % (
                planet.x,
                planet.y,
                planet.z,
                book1.user.name,
                book2.user.name,
                free,
                (free - tick),
            )

        try:
            planet.bookings.append(Target(user=user, tick=free))
            session.commit()
            message.reply(reply)
            return
        except IntegrityError:
            session.rollback()
            raise Exception(
                "Integrity error? Unable to booking for pid %s and tick %s" % (
                    planet.id,
                    when,
                ))
            return