Esempio n. 1
0
def initrandom(minns,
               maxns,
               credsmin,
               credsmax,
               run_away,
               minshipdifficulty,
               maxshipdifficulty,
               jumps=(),
               var_to_set=''):
    you = VS.getPlayer()
    tempfaction = 'aera'
    if (you):
        name = you.getFactionName()
        factionname = vsrandom.randrange(0, faction_ships.getMaxFactions())
        tempfaction = faction_ships.intToFaction(factionname)
        i = 0
        while ((name == tempfaction or name == "unknown") and i < 10):
            factionname = vsrandom.randrange(0, faction_ships.getMaxFactions())
            tempfaction = faction_ships.intToFaction(factionname)
            i += 1
        sd = vsrandom.random() * (maxshipdifficulty -
                                  minshipdifficulty) + minshipdifficulty
        return bounty(minns, maxns, (1.0 + (sd * 0.5)) *
                      (vsrandom.random() * (credsmax - credsmin) + credsmin),
                      run_away, sd, tempfaction, jumps, var_to_set)
    else:
        print "aborting bounty initrandom"
        VS.terminateMission(0)
    def launch_near(self,un):
        if (VS.GetGameTime()<10):
            print "hola!"
            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):
                print 'no flight group for faction: '+faction+' in system '+cursys+'.'
                continue
            num=len(fglist)
            print 'Probability numbers: ',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)
            print 'Chance for %s ship: %g'%(faction, avg)
            rndnum=vsrandom.random()
            print '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)
                print '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,'')
def launchUnits(sys):
    print "Launching units for "+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 range(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
            typenumbers=ShipsInFG(flightgroup,faction)
            #print "Really Far Apart around "+"  "+str(X)+"  "+str(Y)+"  "+str(Z)+" and 10000"
            debug.debug(" launching "+str(typenumbers) +" for "+faction+" at "+str((X,Y,Z)))
            launch_recycle.launch_types_around(flightgroup,faction,typenumbers,'default',1,(X,Y,Z),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(" XXlaunching "+str(typenumbers) +" for "+faction)

            print "LALALAUNCHING "+str(typenumbers)+" t "+sig.getName()+":"+sig.getFullname()
            launch_recycle.launch_types_around(flightgroup,faction,typenumbers,'default',sig.rSize()*vsrandom.randrange(10,100),sig,0,'','',1,10000)
Esempio n. 4
0
def initrandom (minns, maxns, credsmin, credsmax, run_away, minshipdifficulty, maxshipdifficulty,jumps=(),var_to_set=''):
    you=VS.getPlayer()
    tempfaction='aera'
    if (you):
        name = you.getFactionName ()
        factionname=vsrandom.randrange(0,faction_ships.getMaxFactions())
        tempfaction=faction_ships.intToFaction(factionname)
        i=0
        while ((name==tempfaction or name=="unknown") and i<10):
            factionname=vsrandom.randrange(0,faction_ships.getMaxFactions())
            tempfaction=faction_ships.intToFaction(factionname)
            i+=1
        sd = vsrandom.random()*(maxshipdifficulty-minshipdifficulty)+minshipdifficulty
        return bounty (minns,maxns,(1.0+(sd*0.5))*(vsrandom.random ()*(credsmax-credsmin)+credsmin),run_away,sd,tempfaction,jumps,var_to_set)
    else:
        print "aborting bounty initrandom"
        VS.terminateMission(0)
def GenerateFgShips (shipinfg,factionnr,friendly):
    lst=[]
    capship=()
    fac = faction_ships.intToFaction(factionnr)
    fpr=XProductionRate(fac,faction_ships.fighterProductionRate)
    cpr=XProductionRate(fac,faction_ships.capitalProductionRate)
    if cpr>0 and (friendly==2 or (friendly==1 and vsrandom.random()<cpr/fpr)):
        capship=((faction_ships.getRandomCapitolInt(factionnr),1),)
        debug.debug("Generating capital "+str(capship))
    return ((faction_ships.getRandomFighterInt(factionnr),shipinfg),)+capship
Esempio n. 6
0
def GenerateFgShips(shipinfg, factionnr, friendly):
    lst = []
    capship = ()
    fac = faction_ships.intToFaction(factionnr)
    fpr = XProductionRate(fac, faction_ships.fighterProductionRate)
    cpr = XProductionRate(fac, faction_ships.capitalProductionRate)
    if cpr > 0 and (friendly == 2 or
                    (friendly == 1 and vsrandom.random() < cpr // fpr)):
        capship = ((faction_ships.getRandomCapitolInt(factionnr), 1), )
        debug.debug("Generating capital " + str(capship))
    return (
        (faction_ships.getRandomFighterInt(factionnr), shipinfg), ) + capship
Esempio n. 7
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. 8
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)
Esempio n. 9
0
def contractMissionsFor(fac,baseship,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
    for i in range (minsysaway,maxsysaway+1):
        for j in getSystemsNAway(cursystem,i,preferredfaction):
            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)
                    playership=VS.getPlayer().getName()
                    try:
                        hold=int(VS.LookupUnitStat(playership,"privateer","Hold_Volume"))
                    except:
                        hold=10;
                    if hold<10:
                        hold=10;
                    if hold > 32000:
                        hold = 32000
                    numcargos=vsrandom.randrange(hold//5, hold//2)
                    if numcargos < 20:
                        numcargos=vsrandom.randrange(hold//2, hold)
                    category=''
                    if (rnd>.87 and fac!='confed' and fac != "ISO" and fac!="militia" and fac!="homeland-security" and fac!="kilrathi" and fac!="merchant"):
                        category='Contraband'
                    else:
                        for myiter in range (100):
                            carg=VS.getRandCargo(numcargos,category)
                            category=carg.GetCategory()
                            if (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=''
                        if baseship:
                            faction=fac
                            name=baseship.getName()
                            if baseship.isPlanet():
                                faction="planets"
                                name=baseship.getFullname()
                            debug.info("TRADING")
                            debug.debug("getFullname(): %s, getName(): %s, faction: %s" % (baseship.getFullname(), baseship.getName(), faction))
                            exports=trading.getNoStarshipExports(name,faction,20)
                            debug.debug("exports:\n%s" % (debug.pp(exports)))
                            if (category.find("assengers")==-1 and len(exports)):
                                category=exports[vsrandom.randrange(0,len(exports))][0]
                    #debug.debug("CATEGORY OK "+category)
                    generateCargoMission(j,numcargos,category,fac)
                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
Esempio n. 10
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
	
	# Update DJ
        dj_lib.PlayMusik(0,dj_lib.HOSTILE_NEWLAUNCH_DISTANCE)
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 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)
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 list(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() < 0.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() < 0.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 < 0.15:  # 15% - nothing
                    pass
                if rnd < 0.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 > 0.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 > 0.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() < 0.92:
                            count += 1
                            continue
                    elif vsrandom.random() < 0.97:
                        count += 1
                        continue
                    f = "merchant"
                    if count >= nummerchant:
                        f = thisfaction
                    if count >= numthisfac:
                        f = fac
                    if vsrandom.random() < 0.25:
                        if num_wingmen > 0:
                            generateWingmanMission(k, f)
                            num_wingmen -= 1
                    elif i == 0:
                        if vsrandom.random() < 0.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