Esempio n. 1
0
 def getPOV(self, varlist):
     """Returns the corresponding POV_* class variable
 for the reaction of the dockedat faction to the status
 of the event."""
     relatdef = VS.GetRelation(self.dockedat_faction,
                               varlist[self.DEFENDER_INDEX])
     relatagg = VS.GetRelation(self.dockedat_faction,
                               varlist[self.AGGRESSOR_INDEX])
     success = varlist[NewsManager.AGGRESSOR_SUCCESS_INDEX]
     if (relatdef <= -self.POV_CUTOFF and relatagg <= -self.POV_CUTOFF) or (
             relatdef >= self.POV_CUTOFF and relatagg >= self.POV_CUTOFF):
         return self.POV_NEUTRAL
     elif relatdef > relatagg:
         if success == self.SUCCESS_WIN:
             return self.POV_BAD
         elif success == self.SUCCESS_LOSS:
             return self.POV_GOOD
         elif success == self.SUCCESS_DRAW:
             return self.POV_GOOD
     elif relatdef < relatagg:
         if success == self.SUCCESS_WIN:
             return self.POV_GOOD
         elif success == self.SUCCESS_LOSS:
             return self.POV_BAD
         elif success == self.SUCCESS_DRAW:
             return self.POV_BAD
     else:
         debug.debug(
             "ERROR:  VS is returning -0 for relationship relatagg number")
         return self.POV_NEUTRAL
 def Check(self):
     dead=not self.un
     if (not dead):
         dead = self.un.GetHull()<=0
     if (dead):
         debug.debug("Uunit died")
         if (VS.systemInMemory (self.starsystem)):
             if fg_util.RemoveShipFromFG(self.fgname,self.faction,self.type)!=0:
               if (VS.getPlayerX(0)):
                   debug.debug('unit died for real')
                   if (VS.GetRelation(self.faction,VS.getPlayerX(0).getFactionName())>0):
                       dynamic_battle.rescuelist[self.starsystem]=(self.faction,"Shadow",faction_ships.get_enemy_of(self.faction))
                       debug.debug("friend in trouble")
               global dnewsman_
               numships = updatePlayerKillList(0,self.faction)
               debug.debug("num ships killed ")
               debug.debug(numships)
               if ((numships>0 and VS.getPlayer()) or fg_util.NumShipsInFG(self.fgname,self.faction)==0): #generate news here fg killed IRL
                   varList=[str(Director.getSaveData(0,"stardate",0)),dnewsman_.TYPE_DESTROYED,dnewsman_.STAGE_END,"unknown",self.faction,dnewsman_.SUCCESS_WIN,str(dynamic_battle.getImportanceOfType(self.type)),self.starsystem,dnewsman_.KEYWORD_DEFAULT,"unknown","unknown",self.fgname,self.type]
                   if (numships>0 and VS.getPlayer()):
                       varList=[str(Director.getSaveData(0,"stardate",0)),dnewsman_.TYPE_DESTROYED,dnewsman_.STAGE_END,VS.getPlayer().getFactionName(),self.faction,dnewsman_.SUCCESS_WIN,str(dynamic_battle.getImportanceOfType(self.type)),self.starsystem,dnewsman_.KEYWORD_DEFAULT,VS.getPlayer().getFlightgroupName(),VS.getPlayer().getName(),self.fgname,self.type]
                   dnewsman_.writeDynamicString(varList)
                   debug.debug('news about unit dying')
         else:
             fg_util.LandShip(self.fgname,self.faction,self.type)
         return 0
     else:
         sys=self.un.getUnitSystemFile()
         if (len(sys)):
             self.starsystem=sys
     return 1
Esempio n. 3
0
def get_relations_text(player):
    str_relations = "Cash:  %s\n\nKill breakdown:\n" % (int(
        player.getCredits()))

    # length of faction_kills = VS.GetNumFactions() + 1
    # could the last entry be the total?  or maybe the number of times the user has died?
    faction_kills = []
    for i in range(Director.getSaveDataLength(VS.getCurrentPlayer(), 'kills')):
        faction_kills.append(
            Director.getSaveData(VS.getCurrentPlayer(), 'kills', i))

    displayed_factions = [
        'confed', 'kilrathi', 'merchant', 'retro', 'pirates', 'hunter',
        'militia'
    ]

    for i in range(VS.GetNumFactions()):
        # VS.GetFactionIndex(s) expects a string
        # VS.GetFactionIndex(s) expects a name
        faction = VS.GetFactionName(i)
        if faction in displayed_factions:
            # note: the following calls do not always return equal values:
            #   VS.GetRelation(a, b)
            #   VS.GetRelation(b, a)
            relation = int(
                VS.GetRelation(faction, player.getFactionName()) * 100)
            if relation > 100:
                relation = 100
            elif relation < -100:
                relation = -100

            # not sure if the AI or Friend/Foe radar agree with these figures, but this ought to work, mostly
            if relation > 20:
                str_relation = "friendly"
            elif relation < -20:
                str_relation = "hostile"
            else:
                str_relation = "neutral"

            try:
                kills = int(faction_kills[i])
            except:
                kills = 0

            # try to pad the columns
            # (this doesn't work perfectly, since we're using a variable-width font)
            str_pad = "    "
            int_pad_len = len(str_pad) - len(str(kills))
            if int_pad_len < 1:
                str_pad = ""
            else:
                str_pad = str_pad[:int_pad_len]

            # add current faction to the output string
            str_relations = str_relations + "%s%s  %s\t(%s: %s)\n" % (
                str_pad, kills, faction.capitalize(), str_relation, relation)

    return str_relations
Esempio n. 4
0
def CreateRandomMission(whichnum):
    """ This function gets a random mission and saves the information in
    an array as the which element. Returns the sprite file and text."""
    which = str(whichnum)
    missiontype = vsrandom.random()
    fac = VS.GetGalaxyFaction(VS.getSystemFile())
    if fac == "pirates":
        if (missiontype > .5):
            return None
        missiontype *= .2
    elif (VS.GetRelation(fac, "pirates") < -.8 and missiontype < .1):
        missiontype = 0.1 + 0.9 * missiontype
    plr = getMissionPlayer()
    if (missiontype < .05):
        return MakePlunder(which)
    elif (missiontype < .1):
        return MakeContraband(which)
    else:
        goodlist = []
        for indx in range(Director.getSaveStringLength(plr,
                                                       "mission_scripts")):
            script = Director.getSaveString(plr, "mission_scripts", indx)
            if script.find("#F#") != -1:
                goodlist.append(indx)
        goodlist.sort()
        goodlist.reverse()
        if len(goodlist):
            i = goodlist[vsrandom.randrange(len(goodlist))]
            script = Director.getSaveString(plr, "mission_scripts", i)
            desc = Director.getSaveString(plr, "mission_descriptions", i)
            vars = PickleTools.decodeMap(
                Director.getSaveString(plr, "mission_vars", i))
            vars.setdefault('MISSION_SHORTDESC',
                            Director.getSaveString(plr, "mission_names", i))
            Director.eraseSaveString(plr, "misson_scripts", i)
            Director.eraseSaveString(plr, "misson_descriptions", i)
            Director.eraseSaveString(plr, "misson_names", i)
            Director.eraseSaveString(plr, "misson_vars", i)
            mylist = script.split(
                "#"
            )  ###Skip the first two because first is always '' and second is always 'F'
            try:
                vars['MISSION_ID'] = vars['MISSION_ID']
            except:
                vars['MISSION_ID'] = which
            description = vars['MISSION_SHORTDESC'].split("/")[1]
            vars['MISSION_NAME'] = description
            AddNewMission(description, script, None, desc, mylist[4], vars,
                          vars)
            return (mylist[2], mylist[3], which, description)
        else:
            # It should only get here if no fixer missions were found
            return None  # Fixer code will generate a NoFixer hopefully.
Esempio n. 5
0
def randomMovement(fg,fac):
    import universe
    import fg_util
    citizen=VS.isCitizen(fac)
    sys=fg_util.FGSystem(fg,fac)
    convoywhere=fg.find("->")
    if (convoywhere!=-1):
        endpoints=[fg[0:convoywhere],fg[convoywhere+2:]]
        
    if fg.find("Insys")!=-1:
        return#can't go about moving insys fgs away
    if (sys!='nil' and fg!=fg_util.BaseFGInSystemName(sys)):
        l = universe.getAdjacentSystemList(sys)
        nthis = fg_util.NumFactionFGsInSystem(fac,sys)
        if (len(l)):
            suggestednewsys = l[vsrandom.randrange(0,len(l))]
            sugfac=VS.GetGalaxyFaction(suggestednewsys)
            sugrel=VS.GetRelation(fac,sugfac)
            
            if convoywhere==-1 and (((fac.find(sugfac)!=-1 or sugrel>.5) and citizen) or not citizen):
                fg_util.TransferFG( fg,fac,suggestednewsys);
                #debug.debug('moving '+fg+' from '+sys+' to '+ suggestednewsys)
            else:
                for i in l:
                    ifac = VS.GetGalaxyFaction(i)
                    #if (ifac==fac and nthis > fg_util.NumFactionFGsInSystem(fac,i)):
                    #    suggestednewsys = i
                    likes=False
                    if convoywhere!=-1:
                        if endpoints[0]==i or endpoints[1]==i:
                            likes=True
                    elif VS.GetRelation(fac,ifac)>.5:
                        likes=True
                    if (likes):
                        fg_util.TransferFG(fg,fac,i)
                        return
                #debug.debug('moving '+fg+' from '+sys+' to '+ suggestednewsys)
                fg_util.TransferFG( fg,fac,suggestednewsys);
        else:
            pass #debug.debug("flightgroup "+fg+" in system "+sys + " is stuck")
Esempio n. 6
0
def CreateRandomMission(whichnum):
    """This function gets a random mission and saves the infomation in
an array as the which element. Returns the sprite file and text"""
    which = str(whichnum)
    missiontype = vsrandom.random()
    fac = VS.GetGalaxyFaction(VS.getSystemFile())
    if fac == "pirates":
        if (missiontype > .5):
            return ()
        missiontype *= .2
    elif (VS.GetRelation(fac, "pirates") < -.8 and missiontype < .1):
        missiontype = .1 + .9 * missiontype
    plr = VS.getPlayer().isPlayerStarship()
    #   while (len (last_constructor)<=whichnum):
    #       last_constructor[which]=(patrol.patrol)
    #       last_args[which]=(saved_args)
    #       last_briefing[0][which]=('ERROR in mission_lib.py.')
    #       last_briefing[1][which]=('ERROR in mission_lib.py.')
    if (missiontype < .05):
        return MakePlunder(which)
    elif (missiontype < .1):  ####CONTRABAND
        return MakeContraband(which)
    else:
        goodlist = []
        for indx in range(Director.getSaveStringLength(plr,
                                                       "mission_scripts")):
            script = Director.getSaveString(plr, "mission_scripts", indx)
            if script.find("#F#") != -1:
                goodlist.append(indx)
        goodlist.sort()
        goodlist.reverse()
        if len(goodlist):
            i = goodlist[vsrandom.randrange(len(goodlist))]
            script = Director.getSaveString(plr, "mission_scripts", i)
            desc = Director.getSaveString(plr, "mission_descriptions", i)
            Director.eraseSaveString(plr, "misson_scripts", i)
            Director.eraseSaveString(plr, "misson_descriptions", i)
            Director.eraseSaveString(plr, "misson_names", i)
            last_constructor[which] = None
            last_args[which] = script
            last_briefing[0][which] = desc
            mylist = script.split(
                "#"
            )  ###Skip the first two because first is always '' and second is always 'F'
            last_briefing[1][which] = mylist[4]
            return (mylist[2], mylist[3])
        else:
            # It should only get here if no fixer missions were found
            return ()  # Fixer code will generate a NoFixer hopefully.
def getSystemsNAway (start,k,preferredfaction):
    l = getSystemsKAwayNoFaction(start,k)
    if (preferredfaction==None):
        return l
    lbak=l
    if (preferredfaction==''):
        preferredfaction=VS.GetGalaxyFaction(start)
    i=0
    while i <len(l):
        if (VS.GetRelation(preferredfaction,VS.GetGalaxyFaction(l[i][-1]))<0):
            del l[i]
            i-=1
        i+=1
    if (len(l)):
        return l
    return lbak
Esempio n. 8
0
 def __init__ (self,factionname,numsystemsaway, enemyquantity,  waves, distance_from_base, creds, incoming, protectivefactionname='',jumps=(),var_to_set='',dynamic_flightgroup='',dynamic_type='', dynamic_defend_fg='',dynamic_defend_type='',greetingText=['Escort: give up while you still can...','If you let us ravage our target then we grant you passage today.']):
     Director.Mission.__init__(self)
     self.greetingText=greetingText
     self.dedicatedattack=vsrandom.randrange(0,2)*vsrandom.randrange(0,2)
     if (VS.GetRelation(factionname,protectivefactionname)>=0.0):
         self.dedicatedattack=1
     self.arrived=0
     self.todock=VS.Unit()
     self.launchedfriend=0
     self.protectivefaction = protectivefactionname
     self.var_to_set=var_to_set
     self.quantity=0
     self.mplay="all"
     self.gametime=VS.GetGameTime()
     self.waves=waves
     self.incoming=incoming
     self.dynatkfg = dynamic_flightgroup
     self.dynatktype = dynamic_type
     self.dyndeffg = dynamic_defend_fg
     self.dyndeftype = dynamic_defend_type
     self.attackers = []
     self.objective= 0
     self.targetiter = 0
     self.ship_check_count=0
     self.faction = factionname
     self.jp=VS.Unit()
     self.cred=creds
     self.quantity=enemyquantity
     self.savedquantity=enemyquantity
     self.distance_from_base=distance_from_base
     self.defendee=VS.Unit()
     self.difficulty=1
     self.you=VS.getPlayer()
     self.respawn=0
     name = self.you.getName ()
     self.successdelay=0
     self.objectivezero=0
     self.mplay=universe.getMessagePlayer(self.you)
     self.adjsys = go_to_adjacent_systems(self.you,numsystemsaway,jumps)
     VS.IOmessage (0,"escort mission",self.mplay,"Your mission is as follows:")
     self.adjsys.Print("You are in the %s system,","Proceed swiftly to %s.","Your arrival point is %s.","escort mission",1)
Esempio n. 9
0
 def launch_near(self, un):
     if (VS.GetGameTime() < 10):
         debug.debug("launch_near called too soon!")
         return
     cursys = VS.getSystemFile()
     #numsigs=universe.GetNumSignificantsForSystem(cursys)
     for factionnum in range(faction_ships.getMaxFactions() - 1):
         faction = faction_ships.intToFaction(factionnum)
         fglist = fg_util.FGsInSystem(faction, cursys)
         if not len(fglist):
             debug.debug('no flight group for faction: ' + faction +
                         ' in system ' + cursys + '.')
             continue
         num = len(fglist)
         debug.info(
             'Probability numbers: %d %d' %
             (num, fg_util.MaxNumFlightgroupsInSystem(cursys)))  #,numsigs
         avg = float(num) / float(
             fg_util.MaxNumFlightgroupsInSystem(cursys))  #/float(numsigs)
         fortress_level = 0
         if cursys in faction_ships.fortress_systems:
             foretress_level = faction_ships.fortress_systems[cursys]
             avg *= (not (
                 VS.GetRelation(VS.GetGalaxyFaction(cursys), faction) < 0
                 and cursys in faction_ships.fortress_systems)
                     ) * fortress_level + (1 - fortress_level)
         debug.debug('Chance for %s ship: %g' % (faction, avg))
         rndnum = vsrandom.random()
         debug.debug('Random number: %g; will generate ship: %d' %
                     (rndnum, rndnum < avg))
         if rndnum < avg:
             #now we know that we will generate some ships!
             flightgroup = fglist[vsrandom.randrange(len(fglist))]
             typenumbers = fg_util.GetShipsInFG(flightgroup, faction)
             debug.debug('FG Name: "%s", ShipTypes: %s' %
                         (flightgroup, str(typenumbers)))
             launch_recycle.launch_types_around(
                 flightgroup, faction, typenumbers, 'default',
                 self.generation_distance * vsrandom.random() * 0.9, un,
                 self.generation_distance * vsrandom.random() * 2, '')
Esempio n. 10
0
def PlayMusik(forcechange=1, hostile_dist=0):
    un = VS.getPlayer()
    if not __enabled:
        return
    elif not un:
        mpl(PEACELIST, PEACELIST, forcechange)
        debug.debug("Ppeace")
    elif un.DockedOrDocking() not in [1, 2]:
        perfect = 1
        threat = 0
        around_sig = 0
        iter = VS.getUnitList()
        target = iter.current()
        unfcount = {}
        siglist = []
        asteroid = 0
        while (iter.notDone()):
            if (target):
                ftmp = 2 * target.getRelation(un)
                nam = target.getName().lower()
                fact = target.getFactionName()
                if un.getSignificantDistance(target) <= 2 * target.rSize(
                ) and ('afield' == nam[:6] or 'asteroid' == nam[:8]):
                    asteroid = 1
                hdis = HOSTILE_AUTODIST
                if (hostile_dist != 0):
                    hdis = hostile_dist
                if (target.GetTarget() == un
                        or (ftmp < 0 and un.getDistance(target) < hdis)):
                    unfcount[fact] = unfcount.get(fact, 0) + 1
                    perfect = 0
                    if ((target.GetTarget() == un)
                            and (ftmp < 0 and un.getDistance(target) < hdis)):
                        threat = 1
                if (target.isSignificant() and
                    (un.getSignificantDistance(target) <
                     (SIGNIFICANT_DISTANCE_OFFSET +
                      SIGNIFICANT_DISTANCE_MULTIPLY * target.rSize()))):
                    around_sig = 1
            iter.advance()
            target = iter.current()
        if (perfect):
            if asteroid and asteroidlist != -1 and vsrandom.random() < .7:
                mpl(asteroidlist, PEACELIST, forcechange)
                return
            sys = VS.getSystemFile()
            fact = VS.GetGalaxyFaction(sys)
            ufact = un.getFactionName()
            if (around_sig):
                mpl(LookupTable(peacearoundsiglist, fact), PEACESITUATION,
                    forcechange)
                debug.debug("peace-around-significant " + fact)
            else:
                if (VS.GetRelation(ufact, fact) >= 0):
                    mpl(LookupTable(peaceawayfriendlylist, fact),
                        PEACESITUATION, forcechange)
                    debug.debug("peace-away-frienly " + fact)
                else:
                    mpl(LookupTable(peaceawayhostilelist, fact),
                        PEACESITUATION, forcechange)
                    debug.debug("peace-away-hostile " + fact)
        else:
            ftmp = un.FShieldData() + 2 * un.GetHullPercent() + un.RShieldData(
            ) - 2 + 0.5
            mfname = None
            mfcount = 0
            for (fname, fcount) in unfcount.iteritems():
                if fcount > mfcount:
                    mfname = fname
                    mfcount = fcount
            if (threat):
                if (ftmp < 0):
                    mpl(LookupTable(paniclist, mfname), PANICSITUATION,
                        forcechange)
                    debug.debug("panic " + mfname)
                else:
                    mpl(LookupTable(battlelist, mfname), BATTLESITUATION,
                        forcechange)
                    debug.debug("battle " + mfname)
            else:
                mpl(LookupTable(threatlist, mfname), THREATSITUATION,
                    forcechange)
                debug.debug("threat " + mfname)
Esempio n. 11
0
 def Launch(self, you):
     if (self.havelaunched == 0):
         for i in range(len(self.faction)):
             faction = self.faction[i]
             if len(self.numenemies) > i:
                 numenemies = self.numenemies[i]
             else:
                 numenemies = self.numenemies[0]
             if type(self.AdjustFaction) != bool:
                 try:
                     if len(self.AdjustFaction) > i:
                         self.AdjustFaction = self.AdjustFaction[i]
                     else:
                         self.AdjustFaction = self.AdjustFaction[0]
                 except:
                     AjdustFaction = True
             if len(self.fgname) > i:
                 fgname = self.fgname[i]
             else:
                 fgname = self.fgname[0]
             if fgname == "":
                 fgname = "Shadow"
             if len(self.dyntype) > i:
                 dyntype = self.dyntype[i]
             else:
                 dyntype = self.dyntype[0]
             for z in range(numenemies):
                 debug.info('Ambush: Launch ships!')
                 self.havelaunched = 1
                 import launch
                 L = launch.Launch()
                 L.fg = fgname
                 L.dynfg = ""  # dynfg tells launch to load flightgroup from SaveString
                 if dyntype == "":
                     import faction_ships
                     dyntype = faction_ships.getRandomFighter(faction)
                 L.type = dyntype
                 L.num = 1
                 if z == 0:
                     L.fgappend = ""
                 else:
                     L.fgappend = "_" + str(z)
                 L.minradius = 6000
                 L.maxradius = 8000
                 try:
                     import faction_ships
                     L.minradius *= faction_ships.launch_distance_factor
                     L.maxradius *= faction_ships.launch_distance_factor
                 except:
                     pass
                 L.faction = faction
                 import universe
                 enemy = L.launch(you)
                 lead = enemy.getFlightgroupLeader()
                 enemy.SetTarget(you)
                 if lead:
                     lead.SetTarget(you)
                 else:
                     enemy.setFlightgroupLeader(enemy)
                 enemy.setFgDirective("A.")
                 self.enemy = lead
                 rel = VS.GetRelation(faction, "privateer")
                 if self.AdjustFaction and rel >= 0:
                     VS.AdjustRelation(faction, "privateer", -.02 - rel,
                                       1.0)
                     rel = VS.GetRelation("privateer", faction)
                     VS.AdjustRelation("privateer", faction, -.02 - rel,
                                       1.0)
                 if i == 0 and z == 0:
                     universe.greet(self.greetingText, enemy, you)
                 debug.info('Ambush: Ships have been launched. Exiting...')
Esempio n. 12
0
def Siege(fac):
    global siegenumber
    global siegenumtimes
    global siegeprob
    #       turns_till_siege_effective=100
    if (not fac in faction_ships.siegingfactions):
        return
    numfg= fg_util.NumAllFlightgroups(fac)
    if (numfg):
        if (siegenumber==0):
            siegeprob = float(numfg)/float(faction_ships.siegingfactions[fac]);
            siegenumtimes = int (siegeprob)
            if (siegenumtimes==0):
                siegenumtimes=1
            else:
                siegeprob =1
        if siegenumber>=siegenumtimes:
            siegenumber=0
            return 0
        else:
            if (vsrandom.uniform(0,1)<siegeprob):
                fg =fg_util.RandomFlightgroup(fac)
                sys = fg_util.FGSystem(fg,fac)
                enfac=VS.GetGalaxyFaction(sys)
                if (not sys in faction_ships.invincible_systems):
                    #fg_util.CheckAllShips(fac)
                    #fg_util.CheckAllShips(enfac)
                    if enfac == "unknown":
                        debug.debug("exploration: "+sys)
                        fgleader = fg_util.getFgLeaderType(fg,fac)
                        exploration = 1

                    else:
                        exploration = 0
                    if (VS.GetRelation(fac,enfac)<0 and neighborFaction(sys,fac)):#FIXME maybe even less than that
                        numenemyfg = fg_util.NumFactionFGsInSystem(enfac,sys)
                        numfriendfg = fg_util.NumFactionFGsInSystem(fac,sys)
                        #debug.debug('siegarol enemioes '+str(numenemyfg)+ ' friends '+str(numfriendfg))
                        global dnewsman_
                        if exploration:
                            if sys != 'nil':
                                generate_dyn_universe.TakeoverSystem(fac,sys)
                                #HACK, regenerate bases instnatly
                                dnewsman_.writeDynamicString([str(Director.getSaveData(0,"stardate",0)),dnewsman_.TYPE_EXPLORATION,dnewsman_.STAGE_END,fac,enfac,dnewsman_.SUCCESS_WIN,str(getImportanceOfSystem(sys)),sys,dnewsman_.KEYWORD_DEFAULT,fg,fgleader,"unknown","unknown"])
                                                                        #FIXME use keyword (ignore
                                                                        #keyword for now Daniel)

                        elif (numenemyfg==0 and numfriendfg==0): #If both annihalate each other completely (unlikely but possible)
                            facnum = VS.GetFactionIndex (fac)
                            debug.debug('cehcking started')
                            debug.error("DRAW error "+fg+" sys has "+sys+" has " +str(fg_util.NumFactionFGsInSystem(fac,sys))+" String is "+Director.getSaveString(0,fg_util.MakeStarSystemFGKey(sys),facnum))
                            if sys != 'nil':
                                dnewsman_.writeDynamicString([str(Director.getSaveData(0,"stardate",0)),dnewsman_.TYPE_SIEGE,dnewsman_.STAGE_END,fac,enfac,dnewsman_.SUCCESS_WIN,str(getImportanceOfSystem(sys)),sys,dnewsman_.KEYWORD_DEFAULT,fg,"unknown","unknown","unknown"])
                                                                        #FIXME use keyword (ignore
                                                                        #keyword for now Daniel)

                        elif (numenemyfg==0 and (fg_util.CapshipInFG(fg,fac) or moveSurroundingCapshipsToSiege(fac,sys))):      #If aggressor succeeded
                            debug.debug(fac + ' took over '+ sys + ' originally owned by '+enfac)
                            #ok now we have him... while the siege is going on the allies had better initiate the battle--because we're now defending the place...  so that means if the owners are gone this place is ours at this point in time
                            fgs = fg_util.FGsInSystem(fac,sys)
                            if (len(fgs)>0):
                                fgs=fgs[0]
                            else:
                                fgs = "unknown"
                            if sys != 'nil':
                                dnewsman_.writeDynamicString([str(Director.getSaveData(0,"stardate",0)),dnewsman_.TYPE_SIEGE,dnewsman_.STAGE_END,fac,enfac,dnewsman_.SUCCESS_WIN,str(getImportanceOfSystem(sys)),sys,dnewsman_.KEYWORD_DEFAULT,fgs,"unknown","unknown","unknown"])
                                                                        #FIXME use keyword (ignore
                                                                        #keyword for now Daniel)

                            generate_dyn_universe.TakeoverSystem(fac,sys)
                            #HACK, regenerate bases instnatly

                        elif (numfriendfg==0):  #If aggressor lost
                            debug.error('wtf!!')
                            fgs = fg_util.FGsInSystem(enfac,sys)
                            if (len(fgs)>0):
                                fgs=fgs[0]
                            else:
                                fgs = "unknown"
                            if sys != 'nil':
                                dnewsman_.writeDynamicString([str(Director.getSaveData(0,"stardate",0)),dnewsman_.TYPE_SIEGE,dnewsman_.STAGE_END,fac,enfac,dnewsman_.SUCCESS_LOSS,str(getImportanceOfSystem(sys)),sys,dnewsman_.KEYWORD_DEFAULT,"unknown","unknown",fgs,"unknown"])
                                                                        #FIXME use keyword (ignore
                                                                        #keyword for now Daniel)


                        #FIXME add if statements if there is instead a (non appocalyptic) draw (if waring factions have relations "almost neutral" you could have a cease fire, or if the two factions are evenly matched and go nowhere a withdraw of the attackers might occur)!!!
            siegenumber+=1
        return 1
    else:
        return 0
Esempio n. 13
0
def launchUnits(sys):
    debug.info("Launching units for %s", sys)
    
    import faction_ships
    import launch_recycle
    import universe
    sig_units=universe.significantUnits()
    ownerfac= VS.GetGalaxyFaction(sys)
    jumpcount=0
    planetcount=0
#    asteroidcount=0
    basecount=0
    farlen=0
    for sig in sig_units:
      if sig.isJumppoint():
         jumpcount+=1
      elif sig.isPlanet():
         planetcount+=1
#      elif sig.isAsteroid():
#         asteroidcount+=1
      else:
         basecount+=1
      tmplen=Vector.Mag(sig.Position())
      if tmplen>farlen:
          farlen=tmplen

    for factionnum in xrange(0,faction_ships.getMaxFactions()-1):
      faction=faction_ships.intToFaction(factionnum)
      fglist=filterLaunchedFGs(FGsInSystem(faction,sys))
      isHostile=VS.GetRelation(ownerfac,faction)<0
      isForeign=faction.find(ownerfac)==-1
      
      if isForeign:
        if basecount+jumpcount:
           frac=len(fglist)/float(basecount+jumpcount)
        else:
           frac=0.0
      else:
        if basecount+planetcount+jumpcount:
           frac=len(fglist)/float(planetcount+basecount+jumpcount)
        else:
           frac=0.0
      if isHostile:
         for flightgroup in fglist:
            X=incr_by_abs(vsrandom.uniform(-1.0,1.0),1)*farlen
            Y=incr_by_abs(vsrandom.uniform(-1.0,1.0),1)*farlen
            Z=incr_by_abs(vsrandom.uniform(-1.0,1.0),1)*farlen
            XYZ = (X,Y,Z)
            typenumbers=ShipsInFG(flightgroup,faction)
            debug.debug("Really Far Apart around   %s and 10000",XYZ)
            debug.debug(" launching %s for %s at %s", typenumbers, faction, XYZ)
            launch_recycle.launch_types_around(flightgroup,faction,typenumbers,'default',1,XYZ,0,'','',1,10000)
      else:
         for flightgroup in fglist:
            #jp = sig.isJumppoint()
            #if sig.isPlanet() or not isForeign:
            sig = sig_units[vsrandom.randrange(0,len(sig_units))]
            typenumbers=ShipsInFG(flightgroup,faction)
            debug.debug(" launching %s for %s", typenumbers, faction)

            launch_recycle.launch_types_around(flightgroup,faction,typenumbers,'default',sig.rSize()*vsrandom.randrange(10,100),sig,0,'','',1,10000)
def AddSysDict(cursys):
    global _generatedsys, _last_progress_percent
    #pick random fighter from insysenemies with .3 probability OR pick one from the friendlies list.
    #       debug.debug('Addsysdict')
    sysfaction = VS.GetGalaxyFaction(cursys)

    numflightgroups = 1 + vsrandom.randrange(
        fg_util.MinNumFlightgroupsInSystem(cursys) - 1,
        fg_util.MaxNumFlightgroupsInSystem(cursys))

    #debug.debug("Initializing system %s with %d flightgroups... " % (cursys,numflightgroups))
    progress_percent = (_generatedsys / getSystemCount())
    if progress_percent - _last_progress_percent > 0.01:
        ShowProgress.setProgressBar("loading", progress_percent)
        ShowProgress.setProgressMessage(
            "loading",
            "Generating dynamic universe (%.2f%%)" % (100 * progress_percent))
        _last_progress_percent = progress_percent
    _generatedsys += 1

    global fgnames, fglists
    i = 0
    AddBasesToSystem(sysfaction, cursys)
    adjsystems = getAdjacentSystemList(cursys)
    for i in range(len(faction_ships.factions)):
        thisfac = faction_ships.factions[i]
        thisfactionnr = faction_ships.factionToInt(thisfac)
        rel = VS.GetRelation(sysfaction, thisfac)
        iscit = VS.isCitizen(thisfac)
        if iscit and thisfac.find(sysfaction) != -1:
            #debug.debug("generating spc civilian for "+cursys+" faction "+thisfac)
            #do somethign special for this military faction
            if thisfac == sysfaction:
                pass
            elif iscit:
                for neighbor in adjsystems:
                    if (VS.GetRelation(thisfac, VS.GetGalaxyFaction(neighbor))
                            > -.05):
                        #fgname=cursys+"->"+neighbor
                        fgname = "(CivReg) " + GetNewFGName(thisfac)
                        typenumbertuple = GenerateCivilianFgShips(
                            thisfac, thisfactionnr, True)
                        fg_util.AddShipsToFG(fgname, thisfac, typenumbertuple,
                                             cursys)
                fgname = "Insystem_" + cursys
                typenumbertuple = GenerateCivilianFgShips(
                    thisfac, thisfactionnr, False)
        if iscit:
            #debug.debug("generating gen civilian for "+cursys+" faction "+thisfac)
            if VS.GetRelation(
                    thisfac,
                    sysfaction) > -.05:  #brave citizens of the new order...
                fgname = GetNewFGName(thisfac)
                typenumbertuple = GenerateCivilianFgShips(
                    thisfac, thisfactionnr, True)
                fg_util.AddShipsToFG(fgname, thisfac, typenumbertuple, cursys)
    friendlychance = .7
    if cursys in faction_ships.fortress_systems:
        friendlychance = faction_ships.fortress_systems[cursys]
        #debug.debug('enemy chance for '+cursys +'= '+str(friendlychance))
    for i in range(numflightgroups):  #number of fgs in a system.
        faction = sysfaction
        friendly = 0
        if not sysfaction or sysfaction == 'unknown' or vsrandom.random(
        ) > friendlychance:
            faction = faction_ships.get_rabble_of_no_citizen(
                sysfaction)  #why even have citizens on the list then
        else:
            faction = faction_ships.get_friend_of_no_citizen(
                sysfaction
            )  #likewise--- maybe this should be a faction_ships fix
            if (faction == sysfaction):
                friendly = 1
            if (sysfaction in faction_ships.production_centers):
                if (cursys in faction_ships.production_centers[sysfaction]):
                    friendly = 2
            #if (friendly):
            #    debug.debug(faction+" "+sysfaction+" "+cursys)
        factionnr = faction_ships.factionToInt(faction)
        global maxshipsinfg
        typenumbertuple = GenerateFgShips(
            vsrandom.randrange(maxshipsinfg) + 1, factionnr, friendly)
        fgname = GetNewFGName(faction)
        fg_util.AddShipsToFG(fgname, faction, typenumbertuple, cursys)
    return i
Esempio n. 15
0
 def Launch(self, you):
     if (self.havelaunched == 0):
         if (type(self.numenemies) == type(1)):
             self.numenemies = (self.numenemies, )
             self.faction = (self.faction, )
             self.dyntype = (self.dyntype, )
             self.dynfg = (self.dynfg, )
         if (type(self.AdjustFaction) != type(())
                 and type(self.AdjustFaction) != type([])):
             self.AdjustFaction = (self.AdjustFaction, )
         for i in range(len(self.faction)):
             numenemies = self.numenemies[i]
             faction = self.faction[i]
             for z in range(numenemies):
                 AdjustFaction = self.AdjustFaction[-1]
                 if (i < len(self.AdjustFaction)):
                     AdjustFaction = self.AdjustFaction[i]
                 dynfg = ""
                 if (len(self.dynfg) > i):
                     dynfg = self.dynfg[i]
                 dyntype = ""
                 if (len(self.dyntype) > i):
                     dyntype = self.dyntype[i]
                 print('Ambush: Launch ships!')
                 self.havelaunched = 1
                 L = launch.Launch()
                 L.fg = "Shadow"
                 if (dyntype == ""):
                     dyntype = faction_ships.getRandomFighter(faction)
                 L.dynfg = dynfg
                 L.type = dyntype
                 L.num = 1
                 L.fgappend = "X"
                 L.minradius = 6000
                 L.maxradius = 8000
                 try:
                     L.minradius *= faction_ships.launch_distance_factor
                     L.maxradius *= faction_ships.launch_distance_factor
                 except:
                     pass
                 L.faction = faction
                 enemy = L.launch(you)
                 lead = enemy.getFlightgroupLeader()
                 enemy.SetTarget(you)
                 if (lead):
                     lead.SetTarget(you)
                 else:
                     enemy.setFlightgroupLeader(enemy)
                 enemy.setFgDirective("A.")
                 self.enemy = lead
                 rel = VS.GetRelation(faction, "privateer")
                 if (AdjustFaction and rel >= 0):
                     VS.AdjustRelation(faction, "privateer", -.02 - rel,
                                       1.0)
                     rel = VS.GetRelation("privateer", faction)
                     VS.AdjustRelation("privateer", faction, -.02 - rel,
                                       1.0)
                 if (i == len(self.faction) - 1 and z == 0):
                     universe.greet(self.greetingText, enemy, you)
                 #print "launchin"
                 print('Ambush: Ships have been launched. Exiting...')
def contractMissionsFor(fac, minsysaway, maxsysaway):
    global totalMissionNumber
    global insysMissionNumber
    totalMissionNumber = 0
    insysMissionNumber = 0
    facnum = faction_ships.factionToInt(fac)
    enemies = list(faction_ships.enemies[facnum])
    script = ''
    cursystem = VS.getSystemFile()
    thisfaction = VS.GetGalaxyFaction(cursystem)
    preferredfaction = None
    if (VS.GetRelation(fac, thisfaction) >= 0):
        preferredfaction = thisfaction  #try to stay in this territory
    l = []
    num_wingmen = 2
    num_rescue = 2
    num_defend = 1
    num_idefend = 2
    num_bounty = 1
    num_ibounty = 1
    num_patrol = 1
    num_ipatrol = 1
    num_escort = 1
    num_iescort = 1
    mincount = 2
    usedcats = {}
    plr = VS.getPlayer()
    if plr:
        for i in range(plr.numCargo()):
            usedcats[plr.GetCargoIndex(i).GetCategory()] = 1
    for i in range(minsysaway, maxsysaway + 1):
        for j in getSystemsNAway(cursystem, i, preferredfaction):
            import dynamic_battle
            if (i < 2 and num_rescue > 0):
                if j[-1] in dynamic_battle.rescuelist:
                    generateRescueMission(j, dynamic_battle.rescuelist[j[-1]])
                    if checkCreatedMission():
                        num_rescue -= 1
#            if (0 and i==0):
#                generateRescueMission(j,("confed","Shadow","pirates"))
            l = dynamic_battle.BattlesInSystem(j[-1])
            nodefend = 1
            for k in l:
                if (VS.GetRelation(fac, k[1][1]) >= 0):
                    if ((j[-1] == VS.getSystemFile() and num_idefend <= 0) or
                        (j[-1] != VS.getSystemFile() and num_defend <= 0)):
                        mungeFixerPct()
                        debug.debug("Munged")
                    else:
                        nodefend = 0
                    generateDefendMission(j, k[1][0], k[1][1], k[0][0],
                                          k[0][1])
                    restoreFixerPct()
                    if checkInsysNum():
                        num_idefend -= 1
                    if checkMissionNum():
                        num_defend -= 1
                    debug.debug("Generated defendX with insys at: " +
                                str(num_idefend) + " and outsys at " +
                                str(num_defend))
            (m, nummerchant,
             numthisfac) = GetFactionToDefend(thisfaction, fac, j[-1])

            if preferredfaction:
                for kk in faction_ships.enemies[
                        faction_ships.factiondict[thisfaction]]:
                    k = faction_ships.intToFaction(kk)
                    for mm in fg_util.FGsInSystem(k, j[-1]):
                        if (i == 0 or vsrandom.randrange(0, 4)
                                == 0):  #fixme betterthan 4
                            if nodefend and len(m) and vsrandom.random() < .4:
                                if 1:  #for i in range(vsrandom.randrange(1,3)):
                                    insys = (j[-1] == VS.getSystemFile())
                                    if (insys and num_idefend <= 0):
                                        mungeFixerPct()
                                    elif (num_defend <= 0 and not insys):
                                        mungeFixerPct()
                                    rnd = vsrandom.randrange(0, len(m))
                                    def_fg = m[rnd]
                                    def_fac = "merchant"
                                    if rnd >= nummerchant:
                                        def_fac = thisfaction
                                    if rnd >= numthisfac:
                                        def_fac = fac
                                    generateDefendMission(
                                        j, def_fg, def_fac, mm, k)
                                    restoreFixerPct()
                                    if checkInsysNum():
                                        num_idefend -= 1
                                    if checkMissionNum():
                                        num_defend -= 1
                                    debug.debug(
                                        "Generated defendY with insys at: " +
                                        str(num_idefend) + " and outsys at " +
                                        str(num_defend))
                                nodefend = 0
                            elif ((i == 0 or vsrandom.random() < .5)):
                                if ((j[-1] == VS.getSystemFile()
                                     and num_ibounty <= 0)
                                        or (j[-1] != VS.getSystemFile()
                                            and num_bounty <= 0)):
                                    mungeFixerPct()
                                generateBountyMission(j, mm, k)
                                restoreFixerPct()
                                if checkInsysNum():
                                    debug.debug(
                                        " decrementing INSYS bounty to " +
                                        str(num_ibounty))
                                    num_ibounty -= 1
                                if checkMissionNum():
                                    debug.debug(" decrementing bounty to " +
                                                str(num_bounty))
                                    num_bounty -= 1

            mincount = -2
            if i == 0:
                mincount = 1
            for k in range(vsrandom.randrange(
                    mincount, 4)):  ###FIXME: choose a better number than 4.
                if k < 0:
                    k = 0
                rnd = vsrandom.random()
                if (rnd < .15):  # 15% - nothing
                    pass
                if (rnd < .5 or i == 0):  # 35% - Patrol Mission
                    if ((j[-1] == VS.getSystemFile() and num_ipatrol <= 0) or
                        (j[-1] != VS.getSystemFile() and num_patrol <= 0)):
                        mungeFixerPct()
                    if (vsrandom.randrange(0, 2)
                            or j[-1] in faction_ships.fortress_systems):
                        generatePatrolMission(j, vsrandom.randrange(4, 10))
                    else:
                        generateCleansweepMission(
                            j, vsrandom.randrange(4, 10),
                            faction_ships.get_enemy_of(fac))
                    restoreFixerPct()
                    if checkInsysNum():
                        num_ipatrol -= 1
                    if checkMissionNum():
                        num_patrol -= 1

                else:  # 50% - Cargo mission
                    numcargos = vsrandom.randrange(1, 25)
                    if numcargos > 20:
                        numcargos = 20
                    category = ''
                    if (rnd > .87 and fac != 'confed' and fac != "ISO"
                            and fac != "militia" and fac != "homeland-security"
                            and fac != "kilrathi" and fac != "merchant"
                            and fac != "klkk"):
                        category = 'Contraband'
                    else:
                        for myiter in range(100):
                            carg = VS.getRandCargo(numcargos, category)
                            category = carg.GetCategory()
                            if ((not category in usedcats)
                                    and category[:9] != 'Fragments'
                                    and category[:10] != 'Contraband'
                                    and category.find('upgrades') != 0
                                    and (category.find('starships') != 0
                                         or rnd > .999)):
                                break
                            if (myiter != 99):
                                category = ''


#                    debug.debug("CATEGORY OK "+category)
                    if not category in usedcats:
                        generateCargoMission(j, numcargos, category, fac)
                        usedcats[category] = 1
                numescort = vsrandom.randrange(0, 2)
                if (numescort > len(m)):
                    numescort = len(m)
                count = 0
                for k in m:
                    if (i == 0):
                        if vsrandom.random() < .92:
                            count += 1
                            continue
                    elif (vsrandom.random() < .97):
                        count += 1
                        continue
                    f = "merchant"
                    if count >= nummerchant:
                        f = thisfaction
                    if count >= numthisfac:
                        f = fac
                    if (vsrandom.random() < .25):
                        if (num_wingmen > 0):
                            generateWingmanMission(k, f)
                            num_wingmen -= 1
                    elif (i == 0):
                        if (vsrandom.random() < .25):
                            if num_iescort <= 0:
                                mungeFixerPct()
                            generateEscortLocal(j, k, f)
                            restoreFixerPct()
                            if checkCreatedMission():
                                num_iescort -= 1
                    else:
                        if num_escort <= 0:
                            mungeFixerPct()
                        generateEscortMission(j, k, f)
                        restoreFixerPct()
                        if checkCreatedMission():
                            num_escort -= 1

                    count += 1
def isNotWorthy(fac):
    return VS.GetRelation(fac, VS.getPlayer().getFactionName()) < 0
    def launch_near(self, un, forceLaunch=False):
        if (VS.GetGameTime() < 10 and not forceLaunch):
            debug.debug("hola!")
            return
        cursys = VS.getSystemFile()
        cursysfaction = VS.GetGalaxyFaction(cursys)

        #   Computing probability numbers is relatively expensive,
        # accessing multiple times FG/Galaxy/Universe API.
        #   Although with some optimization it becomes acceptable on
        # a director loop, this is still much better: we compute
        # probabilities roughly once per system entry, and then just
        # launch a single flightgroup per director execution (to spread
        # launch load in time and make it less intrusive on gameplay -
        # ie, stutter less noticeably). Outside code will take care
        # of ceasing to call this function when no more flightgroups
        # are needed.

        # Validate probability cache
        if    (cursysfaction != self.probability_cache[0]) \
           or (cursys != self.probability_cache[1]) \
           or (faction_ships.getMaxFactions() != len(self.probability_cache[2])):
            debug.debug('Probability numbers:')
            psum = 0
            probs = []
            for factionnum in range(faction_ships.getMaxFactions()):
                faction = faction_ships.intToFaction(factionnum)
                num = fg_util.NumFactionFGsInSystem(
                    faction,
                    cursys)  # will count bases... but... much quicker.
                if num == 1:
                    #cannot accept counting bases in this case...
                    num = len(fg_util.FGsInSystem(faction, cursys))

                avg = float(num) / float(
                    fg_util.MaxNumFlightgroupsInSystem(
                        cursys))  #/float(numsigs)
                fortress_level = 0
                if cursys in faction_ships.fortress_systems:
                    foretress_level = faction_ships.fortress_systems[cursys]
                    avg *= (not (VS.GetRelation(cursysfaction, faction) < 0
                                 and cursys in faction_ships.fortress_systems)
                            ) * fortress_level + (1 - fortress_level)
                debug.debug('Chance for %s ship: %g' % (faction, avg))
                probs.append(avg)
                psum += avg
            self.probability_cache = (cursysfaction, cursys, probs, psum)
        else:
            debug.debug('Probability numbers cached.')

        # Launch a single random flightgroup in the bunch
        rnd = vsrandom.random() * self.probability_cache[3]
        p = 0
        for factionnum in range(len(self.probability_cache[2])):
            p += self.probability_cache[2][factionnum]
            if (p >= rnd):
                #now we know that we will generate some ships!
                faction = faction_ships.intToFaction(factionnum)
                fglist = fg_util.FGsInSystem(faction, cursys)
                for k in range(10):  #try 10 times
                    flightgroup = fglist[vsrandom.randrange(len(fglist))]
                    typenumbers = fg_util.GetShipsInFG(flightgroup, faction)
                    if not len(typenumbers):
                        continue
                    debug.debug('FG Name: "%s", ShipTypes: %s' %
                                (flightgroup, str(typenumbers)))
                    launch_recycle.launch_types_around(
                        flightgroup, faction, typenumbers, 'default',
                        self.generation_distance * vsrandom.random() * 0.9, un,
                        self.generation_distance * vsrandom.random() * 2, '',
                        '', 100)
                    break
                # assume after 10 tries we launched a flightgroup, we're done here
                break

        # Update DJ
        dj_lib.PlayMusik(0, dj_lib.HOSTILE_NEWLAUNCH_DISTANCE)