Пример #1
0
 def caprate(self, attacker=None):
     maxcap = PA.getfloat("roids", "maxcap")
     mincap = PA.getfloat("roids", "mincap")
     if not attacker or not self.value:
         return maxcap
     modifier = (float(self.value) / float(attacker.value)) ** 0.5
     return max(mincap, min(maxcap * modifier, maxcap))
Пример #2
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)
Пример #3
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 will cost %s metal, %s crystal and %s eonium."%(num,ship.name,
             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(ship.metal*(1+bonus)*num),
                     self.num2short(ship.crystal*(1+bonus)*num),
                     self.num2short(ship.eonium*(1+bonus)*num))
     
     reply+=" It will add %s value"%(self.num2short(ship.total_cost*num/100),)
     message.reply(reply)
Пример #4
0
Файл: scan.py Проект: JDD/merlin
 def planet(self, message, user, params):
     planet = Planet.load(*params.group(1,3,5))
     if planet is None:
         message.reply("No planet with coords %s:%s:%s found" % params.group(1,3,5))
         return
     
     # List of last 10 scans
     if params.group(6) == "o":
         scans = planet.scans.filter_by(scantype=self.type).order_by(desc(Scan.id))[:10]
         if len(scans) < 1:
             message.reply("No %s Scans of %s:%s:%s found"%(PA.get(self.type,"name"),planet.x,planet.y,planet.z))
             return
         prev = []
         for scan in scans:
             prev.append("(pt%s %s)" % (scan.tick, scan.pa_id,))
         reply = "Last 10 %s Scans on %s:%s:%s "%(PA.get(self.type,"name"),planet.x,planet.y,planet.z) + " ".join(prev)
         message.reply(reply)
         return
     
     # Latest scan
     scan = planet.scan(self.type)
     if scan is None:
         message.reply("No %s Scans of %s:%s:%s found"%(PA.get(self.type,"name"),planet.x,planet.y,planet.z))
         return
     
     # Link to scan
     if params.group(7) == "l":
         reply = "%s on %s:%s:%s " % (scan.type,planet.x,planet.y,planet.z,)
         reply+= self.url(scan.link, user)
         message.reply(reply)
         return
     
     # Display the scan
     message.reply(self.url(str(scan), user))
Пример #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):
     
     p = Planet.load(*params.group(1,3,5))
     if p is None:
         message.reply("No planet with coords %s:%s:%s found" % params.group(1,3,5))
         return
     ship = Ship.load(name=params.group(6))
     if ship is None:
         message.alert("No Ship called: %s" % (params.group(6),))
         return
     
     scan = p.scan("P")
     if scan is None:
         message.reply("No planet scans available on %s:%s:%s" % (p.x,p.y,p.z,))
         return
     
     planetscan = scan.planetscan
     tick=scan.tick
     res_m=planetscan.res_metal
     res_c=planetscan.res_crystal
     res_e=planetscan.res_eonium
     prod_res=planetscan.prod_res
     rand_id=scan.pa_id
     
     cost_m=ship.metal
     cost_c=ship.crystal
     cost_e=ship.eonium
     total_cost=ship.total_cost
     
     class_factory_table = {'Fighter': 'factory_usage_light', 'Corvette': 'factory_usage_light', 'Frigate': 'factory_usage_medium',
                            'Destroyer': 'factory_usage_medium', 'Cruiser': 'factory_usage_heavy', 'Battleship': 'factory_usage_heavy'}
     prod_modifier_table = {'None': 0, 'Low': 33, 'Medium': 66, 'High': 100}
     
     capped_number=min(res_m/cost_m, res_c/cost_c, res_e/cost_e)
     overflow=res_m+res_c+res_e-(capped_number*(cost_m+cost_c+cost_e))
     buildable = capped_number + ((overflow*.95)/total_cost)
     
     demo = 1/(1+PA.getfloat("demo","prodcost"))
     total = 1/(1+PA.getfloat("total","prodcost"))
     reply="Newest planet scan on %s:%s:%s (id: %s, pt: %s)" % (p.x,p.y,p.z,rand_id,tick)
     reply+=" can purchase %s: %s | Demo: %s | Total: %s"%(ship.name,int(buildable),int(buildable*demo),int(buildable*total))
     
     if prod_res > 0:
         factory_usage=getattr(planetscan,class_factory_table[ship.class_])
         max_prod_modifier=prod_modifier_table[factory_usage]
         buildable_from_prod = buildable + max_prod_modifier*(prod_res)/100/total_cost
         reply+=" Counting %d res in prod at %s usage:" % (prod_res,factory_usage)
         reply+=" %s | Demo: %s | Total: %s "%(int(buildable_from_prod), int(buildable_from_prod*demo),int(buildable*total))
     
     message.reply(reply)
Пример #8
0
Файл: scans.py Проект: JDD/DLR
 def robocop(self, message, scantype, pa_id, x, y, z, names):
     nicks = []
     [nicks.extend(nick) for nick in [CUT.list_user_nicks(name) for name in names.split(",")]]
     
     reply = "%s on %s:%s:%s " % (PA.get(scantype,"name"),x,y,z,)
     reply+= Config.get("URL","viewscan") % (pa_id,)
     for nick in nicks:
         message.privmsg(reply, nick)
     
     reply = "%s on %s:%s:%s " % (PA.get(scantype,"name"),x,y,z,)
     reply+= "delivered to: "
     reply+= ", ".join(nicks)
     from Hooks.scans.request import request
     message.privmsg(reply, request().scanchan())
Пример #9
0
 def execute(self, message, user, params):
     
     # Planet
     if len(params.groups()) > 1:
         planet = Planet.load(*params.group(1,3,5))
         if planet is None:
             message.reply("No planet with coords %s:%s:%s found" % params.group(1,3,5))
             return
         
         # List of last 10 scans
         if params.group(6) == "o":
             scans = planet.scans.filter_by(scantype=self.type).order_by(desc(Scan.id))[:10]
             if len(scans) < 1:
                 message.reply("No %s Scans of %s:%s:%s found"%(PA.get(self.type,"name"),planet.x,planet.y,planet.z))
                 return
             prev = []
             for scan in scans:
                 prev.append("(pt%s %s)" % (scan.tick, scan.pa_id,))
             reply = "Last 10 %s Scans on %s:%s:%s "%(PA.get(self.type,"name"),planet.x,planet.y,planet.z) + " ".join(prev)
             message.reply(reply)
             return
         
         # Latest scan
         scan = planet.scan(self.type)
         if scan is None:
             message.reply("No %s Scans of %s:%s:%s found"%(PA.get(self.type,"name"),planet.x,planet.y,planet.z))
             return
         
         # Link to scan
         if params.group(7) == "l":
             reply = "%s on %s:%s:%s " % (PA.get(self.type,"name"),planet.x,planet.y,planet.z,)
             reply+= Config.get("URL","viewscan") % (scan.pa_id,)
             message.reply(reply)
             return
         
         # Display the scan
         message.reply(str(scan))
     
     # ID
     else:
         Q = session.query(Scan)
         Q = Q.filter(Scan.pa_id.ilike("%"+params.group(1)+"%"))
         Q = Q.order_by(desc(Scan.id))
         scan = Q.first()
         if scan is None:
             message.reply("No Scans matching ID '%s'"%(params.group(1),))
             return
         # Display the scan
         message.reply(str(scan))
Пример #10
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)
Пример #11
0
 def link(self):
     return Config.get("URL", "reqscan") % (
         PA.get(self.scantype, "type"),
         self.target.x,
         self.target.y,
         self.target.z,
     )
Пример #12
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))
Пример #13
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)
Пример #14
0
 def robocop(self, message, scantype, pa_id, x, y, z, names):
     nicks = []
     reply = "%s on %s:%s:%s " % (PA.get(scantype,"name"),x,y,z,)
     reply+= Config.get("URL","viewscan") % (pa_id,)
     
     for name in names.split(","):
         user = User.load(name)
         for nick in CUT.get_user_nicks(name):
             nicks.append(nick)
             message.privmsg(self.url(reply, user), nick)
     
     reply = "%s on %s:%s:%s " % (PA.get(scantype,"name"),x,y,z,)
     reply+= "delivered to: "
     reply+= ", ".join(nicks) if not Config.getboolean("Misc", "anonscans") else "Anon"
     from Hooks.scans.request import request
     message.privmsg(reply, request().scanchan())
Пример #15
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)
Пример #16
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
            )
        )
Пример #17
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))
Пример #18
0
 def execute(self, request, user, page="1", sort="score", race="all"):
     page = int(page)
     offset = (page - 1)*50
     order =  {"score" : (asc(Planet.score_rank),),
               "value" : (asc(Planet.value_rank),),
               "size"  : (asc(Planet.size_rank),),
               "xp"    : (asc(Planet.xp_rank),),
               "race"  : (asc(Planet.race), asc(Planet.size_rank),),
               }
     if sort not in order.keys():
         sort = "score"
     order = order.get(sort)
     
     tick = Updates.midnight_tick()
     
     Q = session.query(Planet, PlanetHistory, Intel.nick, Alliance.name)
     Q = Q.outerjoin(Planet.intel)
     Q = Q.outerjoin(Intel.alliance)
     Q = Q.outerjoin((PlanetHistory, and_(Planet.id == PlanetHistory.id, PlanetHistory.tick == tick)))
     Q = Q.filter(Planet.active == True)
     
     if race.lower() in PA.options("races"):
         Q = Q.filter(Planet.race.ilike(race))
     else:
         race = "all"
     
     count = Q.count()
     pages = count/50 + int(count%50 > 0)
     pages = range(1, 1+pages)
     
     for o in order:
         Q = Q.order_by(o)
     Q = Q.limit(50).offset(offset)
     return render("planets.tpl", request, planets=Q.all(), offset=offset, pages=pages, page=page, sort=sort, race=race)
Пример #19
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)
Пример #20
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 = gov = None
        pop = 0
        for p in (params.group(4) or "").split():
            m=self.racere.match(p)
            if m and not race:
                race=m.group(1).lower()
                continue
            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

        cost = ship.total_cost
        bonus = 1 + pop/100.0
        if gov:
            cost *= (1+PA.getfloat(gov,"prodcost"))
            bonus += PA.getfloat(gov,"prodtime")
        if race:
            bonus += PA.getfloat(race,"prodtime")

        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/100), 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)
Пример #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 = gov = None
        pop = 0
        for p in (params.group(4) or "").split():
            m=self.racere.match(p)
            if m and not race:
                race=m.group(1).lower()
                continue
            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

        cost = ship.total_cost
        bonus = 1 + pop/100.0
        if gov:
            cost *= (1+PA.getfloat(gov,"prodcost"))
            bonus += PA.getfloat(gov,"prodtime")
        if race:
            bonus += PA.getfloat(race,"prodtime")

        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/100))
        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):
     
     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))
Пример #23
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/100
        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)
Пример #24
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)
Пример #25
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
Пример #26
0
 def execute(self, message, user, params):
     
     p = Planet.load(*params.group(1,3,5))
     if p is None:
         message.reply("No planet with coords %s:%s:%s found" % params.group(1,3,5))
         return
     ship = Ship.load(name=params.group(6))
     if ship is None:
         message.alert("No Ship called: %s" % (params.group(6),))
         return
     
     scan = p.scan("P")
     if scan is None:
         message.reply("No planet scans available on %s:%s:%s" % (p.x,p.y,p.z,))
         return
     
     planetscan = scan.planetscan
     tick=scan.tick
     res_m=planetscan.res_metal
     res_c=planetscan.res_crystal
     res_e=planetscan.res_eonium
     prod_res=planetscan.prod_res
     rand_id=scan.pa_id
     
     cost_m=ship.metal
     cost_c=ship.crystal
     cost_e=ship.eonium
     total_cost=ship.total_cost
     
     class_factory_table = {'Fighter': 'factory_usage_light', 'Corvette': 'factory_usage_light', 'Frigate': 'factory_usage_medium',
                            'Destroyer': 'factory_usage_medium', 'Cruiser': 'factory_usage_heavy', 'Battleship': 'factory_usage_heavy'}
     prod_modifier_table = {'None': 0.0, 'Low': 0.33, 'Medium': 0.66, 'High': 1.0}
     
     capped_number = min(res_m/cost_m, res_c/cost_c, res_e/cost_e)
     overflow = res_m+res_c+res_e-(capped_number*(cost_m+cost_c+cost_e))
     buildable = capped_number + ((overflow*.95)/total_cost)
     
     reply="Newest planet scan on %s:%s:%s (id: %s, pt: %s)" % (p.x,p.y,p.z,rand_id,tick)
     reply+=" can purchase %s: %s"%(ship.name,int(buildable))
     
     for gov in PA.options("govs"):
         bonus = PA.getfloat(gov, "prodcost")
         if bonus == 0:
             continue
         reply+=" | %s: %s"%(PA.get(gov, "name"),int(buildable/(1+bonus)))
     
     factory_usage=getattr(planetscan,class_factory_table[ship.class_])
     if prod_res > 0 and factory_usage != "None":
         max_prod_modifier=prod_modifier_table[factory_usage]
         buildable_from_prod = buildable + max_prod_modifier*prod_res/total_cost
         reply+=" Counting %s res in prod at %s usage:" % (self.num2short(prod_res),factory_usage)
         reply+=" %s"%(int(buildable_from_prod))
         
         for gov in PA.options("govs"):
             bonus = PA.getfloat(gov, "prodcost")
             if bonus == 0:
                 continue
             reply+=" | %s: %s"%(PA.get(gov, "name"),int(buildable_from_prod/(1+bonus)))
     
     message.reply(reply)
Пример #27
0
Файл: info.py Проект: JDD/merlin
 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)
Пример #28
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)
Пример #29
0
 def robocop(self, message, scantype, pa_id, x, y, z, names, scanner, reqs, old=False):
     nicks = []
     reply = "Old " if old else ""
     reply += "%s on %s:%s:%s " % (PA.get(scantype,"name"),x,y,z,)
     if ("showscanner" in Config.options("Misc") and Config.getboolean("Misc", "showscanner") and scanner != 'None'):
         reply+= "from %s " % (User.load(id=scanner).name) if User.load(id=scanner) not in (None, 'None') else ""
     reply += Config.get("URL","viewscan") % (pa_id,)
     if old:
         reply += " !request cancel %s if this is suitable." % (reqs)
     
     for name in names.split(","):
         user = User.load(name)
         for nick in CUT.get_user_nicks(name):
             nicks.append(nick)
             message.privmsg(self.url(reply, user), nick)
     
     if not old:
         reply = "[-%s] %s on %s:%s:%s " % (reqs,PA.get(scantype,"name"),x,y,z,)
         reply+= "delivered to: "
         reply+= ", ".join(nicks) if not Config.getboolean("Misc", "anonscans") else "Anon"
         if Config.getboolean("Misc", "showurls"):
             reply += " (%s)" % (Config.get("URL","viewscan") % (pa_id,))
         from Hooks.scans.request import request
         message.privmsg(reply, request().scanchan())
Пример #30
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)
Пример #31
0
 def execute(self, request, user, params=""):
     
     Q = session.query(Planet, Intel.nick, Alliance.name)
     Q = Q.outerjoin(Planet.intel)
     Q = Q.outerjoin(Intel.alliance)
     Q = Q.join(Planet.galaxy)
     Q = Q.filter(Planet.active == True)
     
     query = False
     
     page = 1
     
     search = {
                 "ruler" : "", "planet" : "", "galaxy" : "", "nick" : "", "alliance" : "",
                 "ter" : 'checked="checked"', "cat" : 'checked="checked"', "xan" : 'checked="checked"', "zik" : 'checked="checked"', "etd" : 'checked="checked"',
                 "sizemin" : "", "sizemax" : "", "valuemin" : "", "valuemax" : "", "scoremin" : "", "scoremax" : "", "x" : "",
                 "galsizemin" : "", "galsizemax" : "", "galvaluemin" : "", "galvaluemax" : "", "galscoremin" : "", "galscoremax" : "", "planets" : "",
                 "bash" : "" if params else 'checked="checked"',
                 "rankmin" : "", "rankmax" : "", "galrankmin" : "", "galrankmax" : "",
                 "ratiomin" : "", "ratiomax" : "", "galratiomin" : "", "galratiomax" : "",
                 "order1" : "", "order1o" : "", "order2" : "", "order2o" : "",
              }
     
     intfilts = {
                 "score" : Planet.score,
                 "value" : Planet.value,
                 "size" : Planet.size,
                 "xp" : Planet.xp,
                 "galscore" : Galaxy.score,
                 "galreal_score" : Galaxy.real_score,
                 "galvalue" : Galaxy.value,
                 "galsize" : Galaxy.size,
                 "galxp" : Galaxy.xp,
                 "idle" : Planet.idle,
                 "x" : Planet.x,
                 "y" : Planet.y,
                 "planets" : Galaxy.members,
                 "totalroundroids" : Planet.totalroundroids,
                 "totallostroids" : Planet.totallostroids,
                 "ticksroiding" : Planet.ticksroiding,
                 "ticksroided" : Planet.ticksroided,
                 "tickroids" : Planet.tickroids,
                 }
     
     floatfilts = {
                 "ratio" : Planet.ratio,
                 "galratio" : Galaxy.ratio,
                 "avroids" : Planet.avroids,
                 }
     
     rankfilts = {
                 "rank" : Planet.score_rank,
                 "valuerank" : Planet.value_rank,
                 "sizerank" : Planet.size_rank,
                 "xprank" : Planet.xp_rank,
                 "galrank" : Galaxy.score_rank,
                 "galrealrank" : Galaxy.real_score_rank,
                 "galvaluerank" : Galaxy.value_rank,
                 "galsizerank" : Galaxy.size_rank,
                 "galxprank" : Galaxy.xp_rank,
                 }
     
     filters = {}
     filters.update(intfilts)
     filters.update(floatfilts)
     filters.update(rankfilts)
     
     order = {
                 "xyz"   : (Planet.x, Planet.y, Planet.z,),
                 "score_growth" : Planet.score_growth,
                 "value_growth" : Planet.value_growth,
                 "size_growth"  : Planet.size_growth,
                 "xp_growth"    : Planet.xp_growth,
                 "score_growth_pc" : Planet.score_growth_pc,
                 "value_growth_pc" : Planet.value_growth_pc,
                 "size_growth_pc"  : Planet.size_growth_pc,
                 "xp_growth_pc"    : Planet.xp_growth_pc,
                 "galscore_growth" : Galaxy.score_growth,
                 "galreal_score_growth" : Galaxy.real_score_growth,
                 "galvalue_growth" : Galaxy.value_growth,
                 "galsize_growth"  : Galaxy.size_growth,
                 "galxp_growth"    : Galaxy.xp_growth,
                 "galscore_growth_pc" : Galaxy.score_growth_pc,
                 "galreal_score_growth_pc" : Galaxy.real_score_growth_pc,
                 "galvalue_growth_pc" : Galaxy.value_growth_pc,
                 "galsize_growth_pc"  : Galaxy.size_growth_pc,
                 "galxp_growth_pc"    : Galaxy.xp_growth_pc,
                 }
     
     order.update(filters)
     orders = []
     
     wordfilts = {
                 "ruler" : Planet.rulername,
                 "planet" : Planet.planetname,
                 "galaxy" : Galaxy.name,
                 }
     
     if request.REQUEST.get("search"):
         r = request.REQUEST
         search = "/search/"
         
         for word in wordfilts.keys() + ["nick", "alliance"]:
             filt = (r.get(word) or "").strip()
             if not filt:
                 continue
             search += "%s:%s/" %(word,filt,)
         
         for filt in filters.keys():
             one = (r.get("min"+filt) or "").strip()
             two = (r.get("max"+filt) or "").strip()
             if not one and not two:
                 continue
             
             if one and one == two:
                 search += "%s:%s/" %(filt,one,)
             elif one and not two:
                 search += "%s:%s|/" %(filt,one,)
             elif two and not one:
                 search += "%s:|%s/" %(filt,two,)
             elif one and two:
                 search += "%s:%s|%s/" %(filt,one,two,)
         
         races = []
         for race in PA.options("races"):
             if (r.get(race) or "").strip():
                 races.append(race)
         if len(races) != len(PA.options("races")):
             search += "race:%s/" %("|".join(races),)
         
         if (r.get("bash") or "").strip():
             search += "bash/"
         
         o1 = (r.get("order1") or "").strip()
         o1o = (r.get("order1o") or "").strip()
         o2 = (r.get("order2") or "").strip()
         o2o = (r.get("order2o") or "").strip()
         if o1 not in order:
             o1, o1o = o2, o2o
         if o1 in order and (o1 == o2 or o2 not in order):
             if o1 == "score" and o1o == "desc":
                 pass
             else:
                 o1o = "^" if o1o == "asc" else "_"
                 search += "order:%s%s/" %(o1o,o1,)
         elif o1 in order and o2 in order:
             o1o = "^" if o1o == "asc" else "_"
             o2o = "^" if o2o == "asc" else "_"
             search += "order:%s%s|%s%s/" %(o1o,o1,o2o,o2,)
         
         return HttpResponseRedirect(search)
     
     for param in params.lower().split("/"):
         if param == "bash" and user.planet is not None:
             Q = Q.filter(or_(Planet.value.op(">")(user.planet.value*PA.getfloat("bash","value")),
                              Planet.score.op(">")(user.planet.score*PA.getfloat("bash","score"))))
             Q = Q.filter(Planet.x < 200)
             search[param] = 'checked="checked"'
             continue
         
         arg, sep, val = param.partition(":")
         if not (arg and val):
             continue
         
         if arg in filters:
             one, two = "", ""
             if "|" not in val:
                 one, two = val, val
             elif val[-1] == "|":
                 one, two = val[:-1], ""
             elif val[0] == "|":
                 one, two = "", val[1:]
             elif "|" in val:
                 one, two = val.split("|",1)
             else:
                 continue
             
             try:
                 if one:
                     one = float(one) if arg in floatfilts else int(one)
                 if two:
                     two = float(two) if arg in floatfilts else int(two)
             except ValueError:
                 continue
             
             if one and one == two:
                 Q = Q.filter(filters[arg] == one)
             elif one and not two:
                 Q = Q.filter(filters[arg] <= one) if arg in rankfilts else Q.filter(filters[arg] >= one)
             elif two and not one:
                 Q = Q.filter(filters[arg] >= two) if arg in rankfilts else Q.filter(filters[arg] <= two)
             elif one and two:
                 Q = Q.filter(filters[arg].between(min(one,two), max(one,two)))
             else:
                 continue
             
             search[arg+"min"], search[arg+"max"] = one, two
             query = True
         
         elif arg in wordfilts:
             Q = Q.filter(wordfilts[arg].ilike("%"+val+"%"))
             search[arg] = val
             query = True
         
         elif arg == "nick" and getattr(user, "is_" + Config.get("Arthur", "intel"))():
             Q = Q.filter(Intel.nick.ilike("%"+val+"%"))
             search["nick"] = val
             query = True
         
         elif arg == "alliance" and getattr(user, "is_" + Config.get("Arthur", "intel"))():
             if val[0] == "!":
                 val = val[1:]
                 inv = True
             else:
                 inv = False
             alliance = Alliance.load(val)
             if alliance:
                 Q = Q.filter(Intel.alliance == alliance) if not inv else Q.filter(Intel.alliance != alliance)
                 search["alliance"] = ["","!"][inv] + alliance.name
                 query = True
         
         elif arg == "race":
             races = []
             for race in val.split("|"):
                 if race in PA.options("races") and race not in races:
                     races.append(Planet.race.ilike(race))
                     search[race] = True
             if len(races):
                 Q = Q.filter(or_(*races))
                 for race in PA.options("races"):
                     search[race] = 'checked="checked"' if search[race] is True else ""
                 query = True
         
         elif arg == "order":
             for sort in val.split("|"):
                 if sort[0] == "^":
                     f = asc
                 elif sort[0] == "_":
                     f = desc
                 else:
                     continue
                 if sort[1:] in order:
                     orders.append((f, sort[1:],))
                     query = True
         
         elif arg == "page" and val.isdigit():
             page = int(val)
     
     if len(orders) < 1:
         orders.append((desc, "score",))
     if len(orders) < 2:
         orders.append((desc, "score",))
     search["order1"] = orders[0][1]
     search["order1o"] = orders[0][0].__name__
     search["order2"] = orders[1][1]
     search["order2o"] = orders[1][0].__name__
     for d, os in orders:
         if type(order[os]) is tuple:
             for o in order[os]:
                 Q = Q.order_by(d(o))
         else:
             Q = Q.order_by(d(order[os]))
     
     showsort = True if search["order1"] not in ("xyz","size","value","score","ratio","xp",
                                                 "size_growth","value_growth","score_growth",
                                                 "size_growth_pc","value_growth_pc","score_growth_pc",) else False
     
     count = Q.count()
     pages = count/50 + int(count%50 > 0)
     pages = range(1, 1+pages)
     
     offset = (page - 1)*50
     Q = Q.limit(50).offset(offset)
     
     results = Q.all() if query else None
     
     return render("search.tpl", request, planets=results, sort=search["order1"],
                             showsort=showsort, s=search, params=params,
                             offset=offset, pages=pages, page=page)
Пример #32
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 == "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() == "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":
                if ship.init < target.init:
                    killed = int(efficiency * ship.guns * num *
                                 float(100 - target.empres) / 100)
                else:
                    target_num = 0
                    while 1:
                        target_num += 1
                        killed = int(efficiency * target.guns * target_num *
                                     float(100 - ship.empres) / 100)
                        if killed >= num:
                            break
                    killed = target_num
            else:
                if ship.init < target.init:
                    killed = int(efficiency * total_damage / target.armor)
                else:
                    target_num = 0
                    while 1:
                        target_num += 1
                        killed = int(efficiency * target.damage * target_num /
                                     ship.armor)
                        if killed >= num:
                            break
                    killed = target_num
            reply += "%s: %s (%s) " % (target.name, killed,
                                       self.num2short(
                                           target.total_cost * killed /
                                           PA.getint("numbers", "ship_value")))
        message.reply(reply)