Example #1
0
def AddFighterTo(fgname,fac,isNew=False):
    sys = VS.getSystemFile()
    #debug.debug('add fighter')
    numsystems = generate_dyn_universe.systemcount[fac]
    if (VS.GetGalaxyFaction(sys)!=fac):
        try:
            homeworlds=faction_ships.production_centers
        except:
            homeworlds=faction_ships.homeworlds
        if fac in homeworlds:
            if type(homeworlds[fac])==type(""):
                sys=homeworlds[fac]
            else:
                sys=homeworlds[fac][vsrandom.randrange(0,len(homeworlds[fac]))]
    numfighters = int(generate_dyn_universe.XProductionRate(fac,faction_ships.fighterProductionRate)*numsystems)
    try:
        if fac in faction_ships.staticFighterProduction:
            numfighters+=faction_ships.staticFighterProduction[fac]
    except:
        pass
    if (numfighters<1):
        if (vsrandom.uniform(0,1)<numfighters):
            numfighters=1
    #debug.debug("Generating "+str(numfighters)+ " fighters for "+fac+" at "+sys)
    if isNew:
        fgk=fg_util.FGsInSystem(fac,sys)        
        if len(fgk):
            fgname=fgk[vsrandom.randrange(0,len(fgk))]
            stat=6
            if fac in faction_ships.fightersPerFG:
                stat=faction_ships.fightersPerFG[fac]
            elif "default" in faction_ships.fightersPerFG:
                stat=faction_ships.fightersPerFG["default"]
            if fg_util.NumShipsInFG(fgname,fac)+numfighters<=numfighters+stat:
                isNew=False
        if isNew:
            fgname=generate_dyn_universe.GetNewFGName(fac)
    if numfighters>=1:
        fg_util.AddShipsToFG (fgname,fac,((faction_ships.getRandomFighter(fac),int(numfighters)),),sys)
    numcapships = generate_dyn_universe.XProductionRate(fac,faction_ships.capitalProductionRate)*numsystems
    if (numcapships<1):
        if (vsrandom.uniform(0,1)>numcapships):
            return
        numcapships=1
    sys = fg_util.FGSystem(fgname,fac)
    if (1 or VS.GetGalaxyFaction(sys)!=fac):
        try:
            homeworlds=faction_ships.production_centers
        except:
            homeworlds=faction_ships.homeworlds
        if fac in homeworlds:
            if type(homeworlds[fac])==type(""):
                sys=homeworlds[fac]
            else:
                sys=homeworlds[fac][vsrandom.randrange(0,len(homeworlds[fac]))]
    cap =faction_ships.getRandomCapitol(fac)
    #debug.debug("Generating "+str(numcapships)+ " capship "+cap+" for "+fac+" at "+sys)
    fg_util.AddShipsToFG(fgname,fac,((cap,int(numcapships)),),sys)
def pathWarning(path, isFixer):
    global dnewsman_
    message = str()
    factions = list()
    if isFixer:
        message += "\nPrecautions to ensure the success of this mission should be taken at your expense."
    else:
        for system in path:
            sysfac = VS.GetGalaxyFaction(system)
            if sysfac not in factions:
                factions.append(sysfac)
        message += "\n\nYou are responsible for the success of this mission. Precautions taken to ensure this outcome will be at your expense. With that in mind, I will advise you that you will be travelling through systems dominated by the "
        if len(factions) == 1:
            message += dnewsman_.data.getFactionData(factions[0],
                                                     'full')[0] + "."
        else:
            message += "following factions: "
            jj = 0
            for fac in factions:
                jj += 1
                message += dnewsman_.data.getFactionData(fac, 'full')[0]
                if jj < len(factions) - 1:
                    message += ", "
                elif jj < len(factions):
                    message += " and "
    return message
Example #3
0
def CountSystems(sys):
    fac = VS.GetGalaxyFaction(sys)
    if fac in systemcount:
        systemcount[fac] += 1
    else:
        systemcount[fac] = 1
        debug.error("FATAL ERROR " + fac + " not in list;")
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
def pathWarning(path,isFixer):
    global dnewsman_
    message = str()
    factions = list()
    if isFixer:
        message+="\nAlle Vorkehrungen und Investitionen, die von Dir getroffen worden, um den Erfolg dieser Mission zu sichern, gehen auf Deine Kosten."
    else:
        for system in path:
            sysfac = VS.GetGalaxyFaction(system)
            if sysfac not in factions:
                factions.append(sysfac)
        message+="\n\nDu bist verantwortlich fuer den Erfolg dieser Mission. Alle Vorkehrungen und Investitionen, die von Dir getroffen worden, um den Erfolg dieser Mission zu sichern, gehen auf Deine Kosten. Mit diesem Wissen im Hinterkopf teile ich Dir mit, dass Du durch Systeme reisen wirst, die beherrscht werden von den "
        if len(factions) == 1:
            message+=dnewsman_.data.getFactionData(factions[0],'full')[0]+"."
        else:
            message+="folgenden Gruppierungen: "
            jj=0
            for fac in factions:
                jj+=1               
                message+=dnewsman_.data.getFactionData(fac,'full')[0]
                if jj<len(factions)-1:
                    message+=", "
                elif jj<len(factions):
                    message+=" und den "
    return message
def CountSystems(sys):
    fac = VS.GetGalaxyFaction(sys)
    if fac in systemcount:
        systemcount[fac] += 1
    else:
        systemcount[fac] = 1
    systemcount[None] += 1
Example #7
0
def AddSysDict(cursys):
    #pick random fighter from insysenemies with .3 probability OR pick one from the friendlies list.
    #       debug.debug('Addsysdict')
    sysfaction = VS.GetGalaxyFaction(cursys)
    global fgnames, fglists
    i = 0
    AddBasesToSystem(sysfaction, cursys)
    for i in range(1 + vsrandom.randrange(
            fg_util.MinNumFlightgroupsInSystem(cursys) -
            1, fg_util.MaxNumFlightgroupsInSystem(cursys))
                   ):  #number of fgs in a system.
        faction = sysfaction
        friendly = 0
        if vsrandom.random(
        ) < .3 or sysfaction == 'unknown' or sysfaction == '':
            faction = faction_ships.get_rabble_of(sysfaction)
        else:
            faction = faction_ships.get_friend_of(sysfaction)
            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
Example #8
0
def launchBases(sys):
    import universe
    print 'Launching bases for '+sys
    fac = VS.GetGalaxyFaction(sys)
    fgs = BaseFG (fac,sys)
    sig_units = universe.significantUnits()
    shipcount=zeros(len(sig_units)) 
    for fg in fgs:
        launchBase(fg[0],fg[1],fac,sys,sig_units,shipcount)
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.
Example #10
0
def PlayMusik(forcechange=1, hostile_dist=0):
    un = VS.getPlayer()
    if (not un):
        mpl(PEACELIST, PEACELIST, forcechange)
        debug.info("PlayMusik: Peace (not un)")
    else:
        perfect = 1
        #debug.debug("before 'uni = VS.getUnitList()'")
        uni = VS.getUnitList()
        #debug.debug("after 'uni = VS.getUnitList()'")
        unlist = []
        asteroid = 0
        while (not uni.isDone()):
            #debug.debug("before 'target = next(uni)'")
            target = next(uni)
            #debug.debug("after 'target = next(uni)'")
            if not target.isNull():
                #debug.debug("inside 'if not target.isNull():'")
                ftmp = 2 * target.getRelation(un)
                nam = target.getName().lower()
                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)):
                    unlist.append(target.getFactionName())
                    perfect = 0
        if (perfect):
            if asteroid and asteroidmisic != -1 and vsrandom.random() < .7:
                mpl(asteroidmisic, PEACELIST, forcechange)
                return
            sys = VS.getSystemFile()
            fact = VS.GetGalaxyFaction(sys)
            if vsrandom.random() < .5:
                fact = None
            mpl(LookupTable(peacelist, fact), PEACELIST, forcechange)
            debug.info("PlayMusik: Peace")
        else:
            ftmp = (un.FShieldData() + 2 * un.GetHullPercent() +
                    un.RShieldData() - 2.8) * 2
            fact = None
            if len(unlist) and vsrandom.random() < .5:
                fact = unlist[vsrandom.randrange(0, len(unlist))]
            debug.info("faction: %s" % (fact))
            if (ftmp < -.5):
                mpl(LookupTable(paniclist, fact), BATTLELIST, forcechange)
                debug.info("PlayMusik: Panic")
            else:
                mpl(LookupTable(battlelist, fact), BATTLELIST, forcechange)
                debug.info("PlayMusik: Battle")
Example #11
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")
Example #12
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.
Example #13
0
def CreateMissions(minsys=0, maxsys=4):
    eraseExtras()
    global plr, basefac, baseship
    plrun = VS.getPlayer()
    plr = plrun.isPlayerStarship()
    debug.debug("VS.getUnitList()")
    i = VS.getUnitList()
    un = i.current()
    while (not i.isDone() and not un.isDocked(plrun)):
        un = next(i)  # iterate until the docked player unit is found
    if (not un.isNull()):
        baseship = un
        basefac = un.getFactionName()
    if (basefac == 'neutral'):
        basefac = VS.GetGalaxyFaction(VS.getSystemFile())
    contractMissionsFor(basefac, baseship, minsys, maxsys)
    news.processNews(plr)
 def updateDockedAtFaction(self):
     """Updates the current self.dockedat_faction to its
 current value.  Should be called before translating
 a batch of stores."""
     i = VS.getUnitList()
     playa = VS.getPlayer()
     while i.notDone():
         un = i.current()
         i.advance()
         if (un.isDocked(playa) or playa.isDocked(un)):
             if not (un.isPlanet() or (un.getFactionName() == "neutral")):
                 fac = un.getFactionName()
                 # debug.debug('returning '+un.getName()+' s faction as '+fac+' from flightgroup '+un.getFlightgroupName())
                 self.dockedat_faction = fac
             break
     retfac = VS.GetGalaxyFaction(VS.getSystemFile())
     # debug.debug("Returning " + retfac + " as the systems faction")
     self.dockedat_faction = retfac
def CreateMissions(minsys=0,maxsys=4):
    eraseExtras()
    i=0
    global plr,basefac
    plrun=VS.getPlayer()
    plr=plrun.isPlayerStarship()
    un=VS.getUnit(i)
    while(un):
        i+=1
        if (un.isDocked(plrun)):
            break
        un=VS.getUnit(i)
    if (un):
        basefac=un.getFactionName()
    if (basefac=='neutral'):
        basefac=VS.GetGalaxyFaction(VS.getSystemFile())
    contractMissionsFor(basefac,minsys,maxsys)
    import news
    news.processNews(plr)
def CreateMissions(minsys=0, maxsys=4):
    generate_dyn_universe.KeepUniverseGenerated()
    if VS.networked():
        # No generating stuff while networked.
        return
    eraseExtras()
    global plr, basefac
    plrun = VS.getPlayer()
    plr = plrun.isPlayerStarship()
    i = VS.getUnitList()
    while (i.notDone() and not i.current().isDocked(plrun)):
        i.advance()
    if (i.notDone()):
        basefac = i.current().getFactionName()
    if (basefac == 'neutral'):
        basefac = VS.GetGalaxyFaction(VS.getSystemFile())
    contractMissionsFor(basefac, minsys, maxsys)
    import news
    news.processNews(plr)
Example #17
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, '')
 def __init__(self, system=VS.getSystemFile()):
     self.system = system
     self.faction = VS.GetGalaxyFaction(self.system)
Example #19
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)
Example #20
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
Example #21
0
def neighborFaction(sys,fac):
    for i in xrange(VS.GetNumAdjacentSystems(sys)):
        asys=VS.GetAdjacentSystem(sys,i)
        if (VS.GetGalaxyFaction(asys)==fac):
            return True
    return False
Example #22
0
def getImportanceOfSystem(sys):
    if (VS.GetGalaxyProperty(sys,"faction")==VS.GetGalaxyFaction(sys)):
        return .5
    else:
        return .1
Example #23
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 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)
Example #25
0
def TakeoverSystem(fac, sys):
    systemcount[VS.GetGalaxyFaction(sys)] -= 1
    VS.SetGalaxyFaction(sys, fac)
    systemcount[fac] += 1
    AddBasesToSystem(fac, sys)
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 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