def Execute(self): dynamic_battle.UpdateCombatTurn() if (self.cur_player>=len(self.players)): self.AddPlayer() self.cur=self.players[self.cur_player] if (self.cur.curquest<len(self.cur.quests)): if (self.cur.quests[self.cur.curquest].Execute()): self.cur.curquest+=1 else: del self.cur.quests[self.cur.curquest] else: self.cur.curquest=0 un = self.decideMode () if (self.cur.curmode!=self.cur.lastmode): #lastmode=curmode#processed this event don't process again if in critical zone self.cur.lastmode=self.cur.curmode print "curmodechange %d" % (self.cur.curmode)#? if un: # if ((vsrandom.random()<(self.fighterprob*self.cur.UpdatePhaseAndAmplitude())) and un): if (not self.atLeastNInsignificantUnitsNear (un,self.min_num_ships)): #determine whether to launch more ships next to significant thing based on ships in that range print ("launch near") self.launch_near (VS.getPlayerX(self.cur_player)) self.cur_player+=1 if (self.cur_player>=VS.getNumPlayers()): self.cur_player=0 VS.setMissionOwner(self.cur_player)
def Check(self): import fg_util dead=not self.un if (not dead): dead = self.un.GetHull()<=0 if (dead): debug.debug("Uunit died") if (VS.systemInMemory (self.starsystem)): import dynamic_battle if fg_util.RemoveShipFromFG(self.fgname,self.faction,self.type)!=0: if (VS.getPlayerX(0)): debug.debug('unit died for real') if (VS.GetRelation(self.faction,VS.getPlayerX(0).getFactionName())>0): import faction_ships dynamic_battle.rescuelist[self.starsystem]=(self.faction,"Shadow",faction_ships.get_enemy_of(self.faction)) debug.debug("friend in trouble") global dnewsman_ import dynamic_battle numships = updatePlayerKillList(0,self.faction) debug.debug("num ships killed ") debug.debug(numships) if ((numships>0 and VS.getPlayer()) or fg_util.NumShipsInFG(self.fgname,self.faction)==0): #generate news here fg killed IRL varList=[str(Director.getSaveData(0,"stardate",0)),dnewsman_.TYPE_DESTROYED,dnewsman_.STAGE_END,"unknown",self.faction,dnewsman_.SUCCESS_WIN,str(dynamic_battle.getImportanceOfType(self.type)),self.starsystem,dnewsman_.KEYWORD_DEFAULT,"unknown","unknown",self.fgname,self.type] if (numships>0 and VS.getPlayer()): varList=[str(Director.getSaveData(0,"stardate",0)),dnewsman_.TYPE_DESTROYED,dnewsman_.STAGE_END,VS.getPlayer().getFactionName(),self.faction,dnewsman_.SUCCESS_WIN,str(dynamic_battle.getImportanceOfType(self.type)),self.starsystem,dnewsman_.KEYWORD_DEFAULT,VS.getPlayer().getFlightgroupName(),VS.getPlayer().getName(),self.fgname,self.type] dnewsman_.writeDynamicString(varList) debug.debug('news about unit dying') else: fg_util.LandShip(self.fgname,self.faction,self.type) return 0 else: sys=self.un.getUnitSystemFile() if (len(sys)): self.starsystem=sys return 1
def Execute (self): ## if (VS.getGameTime()>mission_time): ## VS.IOmessage (0,"cargo mission",self.mplay,"You Have failed to deliver your cargo in a timely manner.") ## VS.IOmessage (0,"cargo mission",self.mplay,"The cargo is no longer of need to us.") ## if (you): ## takeCargoAndTerminate(you,0) ## return if (self.you.isNull() or (self.arrived and self.base.isNull())): VS.IOmessage (0,"cargo mission",self.mplay,"#ff0000You were unable to deliver cargo. Mission failed.") self.SetVar(-1) VS.terminateMission(0) return if (not self.adjsys.Execute() and not (self.arrived and self.base and self.base.isDocked(self.you))): return if (self.arrived): self.adjsys.Execute=self.adjsys.HaveArrived if (self.base.isDocked(self.you) or (self.base.getDistance(self.you)<=1 and not self.knownBases())): self.takeCargoAndTerminate(self.you,1) return else: self.arrived=1 tempfac=self.faction if vsrandom.random()<=.5: tempfac='' self.adjsys=go_somewhere_significant(self.you,1,100,not self.capship,tempfac) capstr="planet" dockstr="land" if tempfac=='': dockstr="dock" capstr="ship" self.adjsys.Print("You must visit the %%s %s" % (capstr),"cargo mission",", docked around the %s",0) VS.IOmessage(0,"cargo mission",self.mplay,"Once there, %s and we will transport the cargo off of your ship." % (dockstr)) self.base=self.adjsys.SignificantUnit() self.role=self.base.getCombatRole() self.base.setCombatRole("INERT")
def __init__ (self): self.sysfile = VS.getSystemFile() self.drone=VS.Unit() self.significants=1 self.timer = VS.GetGameTime(); VS.cacheAnimation ("explosion_wave.ani"); self.playlist=VS.musicAddList("galacticbattle.m3u")
def setProgressMessage(screen_id,message): global __showing if screen_id == __showing: prefix = VS.vsConfig("splash","%s_message" % screen_id,"") if prefix != "": prefix += ": " VS.showSplashMessage(prefix+message)
def __init__ (self): self.player = VS.getPlayer() self.stage = 1 self.timer = VS.GetGameTime() self.msgColor = ("#FF9999","#FF99FF") self.system = VS.getSystemName() self.shipyard = unit.getUnitByName('Shipyard')
def Execute (self): if (VS.getSystemName()==self.system and self.player and self.shipyard): if (self.stage==1 and VS.GetGameTime()>=self.timer): if (self.shipyard.getSignificantDistance(self.player) > 20000): print('shipy ret') print("distance" + str(self.shipyard.getSignificantDistance(self.player))) return 1 else: print('killing') pos = self.shipyard.Position() size = 10*self.shipyard.rSize() VS.playAnimation("explosion_orange.ani",pos,size) pos = (pos[0]+.5*size,pos[1],pos[2]) VS.playAnimation("explosion_orange.ani",pos,size) pos = (pos[0]-size,pos[1],pos[2]) VS.playAnimation("explosion_orange.ani",pos,size) VS.playSound("explosion.wav",pos,(1,0,0)) self.shipyard.DealDamageToHull ((10,0,0),self.shipyard.GetHull()*.9) self.timer = VS.GetGameTime()+10 self.stage = 2 if (self.stage==2 and VS.GetGameTime()>=self.timer): VS.IOmessage(0,unit.getUnitFullName(self.shipyard),"all",self.msgColor[0]+"Large Explosion detected... standby...%#@*") text = "NAVAL SHIPYARDS HIT BY BOMB\\\Disaster struck the Confederate Naval Shipyards orbiting Alpha Centauri hours ago, when a powerful explosive device detonated, crippling a fleet carrier that was nearing completion. " text += "At least a dozen casualties were reported with an unknown number of injured, and salvage crews are still working hard to clear the area of wreckage. " text += "A team from the CSP (Confederate Security Police) arrived at the shipyards mere hours after the incident, and an investigation has been launched to determine who the perpetrators of this attack were, whether they were human terrorists or agents of an alien power." news.publishNews(text) self.stage = 99 if (self.stage==99 and not VS.getSystemName()==self.system): self.stage += 1 # don't enter this loop anymore self.playernum = -1 self.name = "quest_shipyardbomb" self.removeQuest() return 0 return 1
def launch (fgname, faction, type,ai, nr_ships, nr_waves, vec, logo='',useani=1,skipdj=0): # print 'log'+ str( logo) + ' useani '+ str(useani) diff=usingDifficulty() # if useani: # VS.playAnimation ("warp.ani",vec,300.0) if (not diff or (type.find(".blank")==-1 and -1==type.find(".stock"))): for i in range(nr_ships): ret = VS.launch (fgname,type,faction,"unit",ai,1,nr_waves,VS.SafeEntrancePoint (vec,40),logo) unit.moveOutOfPlayerPath(ret) if (not skipdj): dj_lib.PlayMusik(0,dj_lib.HOSTILE_NEWLAUNCH_DISTANCE) return ret rsize=0.0 diffic = VS.GetDifficulty() ret=VS.Unit() for i in range(nr_ships): mynew=VS.launch(fgname,type,faction,"unit",ai,1,nr_waves,VS.SafeEntrancePoint (vec,40),logo) unit.moveOutOfPlayerPath(mynew) if (i==0): ret = mynew rsize =mynew.rSize ()*1.75 ship_upgrades.upgradeUnit ( mynew,diffic) vec=(vec[0]-rsize, vec[1],#-rsize vec[2]-rsize) if (not skipdj): dj_lib.PlayMusik(0,dj_lib.HOSTILE_NEWLAUNCH_DISTANCE) return ret
def saveNameEntryEntered(self,textbox): # this is a bit awkward, mostly since we have to emulate modal behaviour through state machines... if textbox.getText() is not '' and textbox.canceled is False: savename = textbox.getText() if savename in savelist() and savename is not self.oldSaveName: if savename is not self.lastEnteredSavegameName: self.txt_screen.setText( 'warning: overwriting another game with the same name\n' + 'press Enter again to really do it') return else: self.lastEnteredSavegameName = savename VS.saveGame(savename) if self.oldSaveName is not None and savename is not self.oldSaveName: try: os.remove(VS.getSaveDir() + os.sep + self.oldSaveName) except: trace(TRACE_DEBUG,"could not remove old savegame at " + VS.getSaveDir() + os.sep + self.oldSaveName) self.picker_screen.items = [ GUI.GUISimpleListPicker.listitem("New Game",NewSaveGame) ]+savelist() self.txt_screen.hide() textbox.hide() textbox.focus(False) for id in list(self.buttons.keys()): button = self.buttons[id] button.enable() button.redraw() self.saveGameNameEntryBox = None self.picker_screen.show() # self.setExitLinkState(True) self.guiroom.redraw()
def clickNextNode(self,room,choicenum,force=False): plr = VS.getCurrentPlayer() if not self.checkPlayer(plr): return ["failure","player %d not initialized yet!"%plr] player = self.players[plr] if force: curr = player.current else: curr = self.getCurrentNode(room) if not curr: return ["failure","getCurrentNode returned null"] if curr.acceptClientInput(): if (curr.IsCampaignChoiceNode() or (VS.networked() and choicenum==-2)): ret = curr.gotoChoice(room,choicenum) if VS.networked(): import fixers fixers.DestroyActiveButtons() # Don't always go away on their own return ret else: ret = curr.clickFixer(room,force) if VS.networked(): ret = curr.gotoChoice(room,choicenum) return ret else: if VS.isserver(): return ["failure", "don't have a choice here..."] else: return curr.gotoChoice(room,choicenum)
def readPositionFromSavegame(self, savegamelist=None): import VS import Director plr=VS.getCurrentPlayer() self.InitPlayer(plr) player = self.players[plr] player.savegame=[] player.current=self.root if savegamelist: length=len(savegamelist) else: length=Director.getSaveDataLength(plr,self.name) for i in range(length): if savegamelist: newnodenum=int(savegamelist[i]) else: newnodenum=int(Director.getSaveData(plr,self.name,i)) if newnodenum>=0: if newnodenum>=len(player.current.subnodes): debug.debug(str(player.savegame)+': current has '+str(player.current.subnodes)) debug.warn('Error: save game index out of bounds: '+str(newnodenum)) return player.current=player.current.subnodes[newnodenum] elif newnodenum==-2: if not player.current.contingency: debug.debug(str(player.savegame)) debug.warn('Error: save game moves to invalid contengency node!') return player.current=player.current.contingency player.savegame.append(newnodenum) if VS.isserver(): custom.run("campaign", [self.name, "setsavegame"] + player.savegame, None) debug.debug('*** read position from save game: for '+self.name+': '+str(player.savegame)) debug.debug(player.current)
def __call__(self): import VS if self.system: sys=VS.getSystemFile().split('/') debug.debug('System: '+str(sys)+'==?=='+str(self.system)) for i in range(-1,-min(len(self.system),len(sys))-1,-1): if sys[i].lower()!=self.system[i]: debug.debug(str(sys[i])+'!='+str(self.system[i])) debug.debug('*** insystem return false: not in system!!') return False if self.dockedshipname: if type(self.dockedshipname)==str: debug.debug('*** Test if docked to: '+ self.dockedshipname) iter = VS.getUnitList() while iter.notDone(): if VS.getPlayer().isDocked(iter.current()) or iter.current().isDocked(VS.getPlayer()): #Not sure why both have to be checked, it seems to second gives a more consistantly correct response #find unit with name and check debug.info('*** Compare '+iter.current().getName().replace(' ','_').lower()+" == "+self.dockedshipname) debug.info(' Compare '+iter.current().getFullname().replace(' ','_').lower()+" == "+self.dockedshipname) if iter.current().getName().replace(' ','_').lower() == self.dockedshipname or iter.current().getFullname().replace(' ','_').lower() == self.dockedshipname: debug.debug('*** inSystem return true') return True else: debug.info(iter.current().getName()+' not docked to unit') iter.advance() else: debug.debug('*** inSystem return true, no self.dockedshipname') return True debug.debug('*** insystem return false!!') return False
def setCurrentNode(self,room,newnodenum): debug.warn('*** Going to branch number '+str(newnodenum)) import VS import Director plr = VS.getCurrentPlayer() if not self.checkPlayer(plr): return ["failure","player %d not initialized yet!"%plr] player = self.players[plr] if newnodenum>=0: if newnodenum>=len(player.current.subnodes): debug.debug('Error: cannot go to node '+str(newnodenum)) debug.debug('Failed node has text:') debug.debug(str(player.current.text)) return ["failure", "Attempt to go to an invalid subnode"] player.current=player.current.subnodes[newnodenum] player.savegame.append(newnodenum) Director.pushSaveData(VS.getCurrentPlayer(),self.name,float(newnodenum)) elif newnodenum==-2: if not player.current.contingency: debug.debug('Error: cannot go to contingency node!') debug.debug('Failed node has text:') debug.debug(str(player.current.text)) return ["failure", "Failed attempt to go to contingency"] debug.debug('*** Going to contingency!!!') player.current=player.current.contingency player.savegame.append(-2) Director.pushSaveData(VS.getCurrentPlayer(),self.name,float(-2)) if VS.isserver(): self.sendGotoMessage(newnodenum) if player.current.acceptClientInput() or not VS.networked(): if newnodenum != -1: player.current.evaluate(room) return ["success"]
def __call__(self): import VS debug.debug('*** U half active mishuns >= ?') debug.debug('*** '+str(VS.numActiveMissions()-1)+' >= '+str(self.num)) isactive=((VS.numActiveMissions()-1)>=self.num) debug.debug('*** '+str(isactive)) return isactive
def __call__(self,room,subnodes): Script.__call__(self,room,subnodes) import VS if VS.networked(): return True you=VS.getPlayer() removenum=you.removeCargo(self.cargname,self.cargnum,True) if self.missionflag: has=you.hasCargo(self.cargname) if (has): mpart=VS.GetMasterPartList() newcarg=mpart.GetCargo(self.cargname) has=you.removeCargo(self.cargname,has,1) newcarg.SetMissionFlag(0) newcarg.SetContent(self.cargname) newcarg.SetQuantity(has) you.addCargo(newcarg) #It seems that removing and then adding it again is the only way... debug.debug('*********** Remove cargo '+self.cargname+'('+str(self.cargnum)+')') if removenum<self.cargnum: debug.debug(' ...strict failed to remove cargo') return False #since we force add all cargo, we can fail if not all is removed if removenum<1:#self.cargnum less strict debug.debug(' ...really failed :-(') return False return True
def setup(self): self.sysfile = VS.getSystemFile() self.stage=0 self.lastdist=10000 self.jumping=0 self.savedplaya=VS.getPlayer() print "initing"
def __call__(self): import VS debug.debug('*** have active missions <= ?') debug.debug('*** '+str(VS.numActiveMissions()-1)+' <= '+str(self.num)) isactive=((VS.numActiveMissions()-1)<=self.num) debug.debug('*** '+str(isactive)) return isactive
def Lose(self, terminate): VS.IOmessage(0, "plunder mission", self.mplay, "#ff0000You have failed this mission and will not be rewarded.") if len(self.donevar): quest.removeQuest(int(self.mplay[1:]), self.donevar, -1) if terminate: print "lose plunder mission" VS.terminateMission(0)
def exploremission(part,filename,sysfile,creditnum): fixers.DestroyActiveButtons () if part==1: plyr=VS.getPlayer().isPlayerStarship() if quest.findQuest(plyr,(sysfile+"_nav"),1) or quest.findQuest(plyr,(sysfile+"_nav"),2): part=3 if part==1: fixers.CreateChoiceButtons(Base.GetCurRoom(),[ fixers.Choice("bases/fixers/yes.spr",filename,"Accept This Mission"), fixers.Choice("bases/fixers/no.spr","bases/fixers/no.py","Decline This Mission")]) Base.Message("""Hi. Our researchers have found a new signal similar to that of a jump point coming from an area in the #55ffff%s#000000 system. This mission will require that you own a jump drive. We hope that you will accept this mission. You will earn %.2f credits when you explore the area."""%(sysfile.split('/')[-1],creditnum)) elif part==2: Base.Message("""Excellent! Go to the unknown energy source that we have uploaded to your ship computer as a navpoint in #55ffff%s#000000. Once next to the energy source, jump into the energy source and get close to all of the planets in the connecting system."""%sysfile.split('/')[-1]) Base.EnqueueMessage("""You will earn %.2f credits when this is completed"""%creditnum) plyr=VS.getPlayer().isPlayerStarship() if Director.getSaveDataLength(plyr,(sysfile+"_nav"))==0: Director.pushSaveData(plyr,(sysfile+"_nav"),1) else: Director.putSaveData(plyr,(sysfile+"_nav"),0,1) else: Base.Message("""Go to the unknown energy source that we have uploaded to your ship computer as a navpoint in #55ffff%s#000000. Once next to the energy source, jump into the energy source and get close to all of the planets in the connecting system."""%sysfile.split('/')[-1])
def launch_new_wave(self): un = VS.getPlayer() if (vsrandom.randrange(0,4)==0): if (un): currentsystem = VS.getSystemFile() numadj=VS.GetNumAdjacentSystems(currentsystem) if (numadj): cursys=VS.GetAdjacentSystem(currentsystem,vsrandom.randrange(0,numadj)) else: cursys = 'enigma_sector/heavens_gate' debug.info("TJ: jumping to "+cursys) un.JumpTo(cursys) else: debug.info("TJ: jumping to [ERROR: you are null]") side = vsrandom.randrange(0,2) faction="confed" ai = vsrandom.randrange(0,6) if (0 and ai==0): ai = "printhello.py" else: ai = "default" if (side==0): faction=faction_ships.get_enemy_of("confed") else: faction=faction_ships.get_friend_of("confed") launched = launch.launch_wave_around_unit ("Shadow",faction,faction_ships.getRandomFighter(faction),ai,vsrandom.randrange(1,10),100.0,2000.0,VS.getPlayer(),'') if (vsrandom.randrange(0,10)==0): launch.launch_wave_around_unit ("ShadowCap",faction,faction_ships.getRandomCapitol(faction),ai,1,2000.0,4000.0,VS.getPlayer(),'')
def PlayLaunch (): # if (vsrandom.random()<.02): # VS.musicPlaySong('../music/launchjoke.ogg') # VS.micro_sleep(45000000) # else: if (GlobalMusic!= -1): VS.musicPlayList (GlobalMusic)
def Dead(self,activeship): import VS runawaydist=7000 tmp = (self.canrunaway and activeship[0].GetHullPercent()<.7) if tmp: VS.setCompleteness(activeship[1],0.0) return ((tmp and self.you.getDistance(activeship[0])>runawaydist) or not activeship[0])
def Execute (self): playa=VS.getPlayer() if (playa.isNull()): return 1 if (self.stage==0): if (len (self.aera)==0): if (VS.getSystemFile()!=self.sysfile): return 0 if (len (self.aera)==0): VS.IOmessage (0,"game","all","[Aera Burst Transmission] No targets detected--resistance encountered ca--&$&(*!@^6") self.gametime=VS.GetGameTime() self.removeQuest(); self.stage=1 else: if (self.aera[0].isNull()): del self.aera[0] else: if (VS.GetGameTime()-self.gametime>100): if (not self.devil.isNull()): self.devil.DealDamageToHull((10,0,0),self.devil.GetHull()*100) VS.IOmessage (0,"game","all","[Computer] Large energy release detected...") VS.IOmessage (0,"game","all","[Computer] Aera Starbase destroyed!") VS.IOmessage (0,"game","all","[Computer] Star Confederacy Starships detected on far side of planet!") VS.IOmessage (5,"game","all","[Computer] Message from Rescue Fleet") VS.IOmessage (6,"RescueFleet","all","Thank you for your help, privateer...we owe our victory to your cunning kill of those scouts. We offer you 24,000 credits for this critical act!") playa.addCredits (24000) self.removeQuest() return 0 return 1
def look_for (fg, faction, numships,myunit, pos, gcd,newship=[None]): i=0 debug.debug("VS.getUnit (%d)" % (i)) un = VS.getUnit (i) while (not un.isNull()): i+=1 debug.debug("VS.getUnit (%d)" % (i)) un = VS.getUnit (i) i-=1 #now our i is on the last value while ((i>=0) and (numships>0)): debug.debug("VS.getUnit (%d)" % (i)) un = VS.getUnit (i) if (not un.isNull()): if (unOrTupleDistance(un,myunit,1)>gcd ): fac = un.getFactionName () fgname = un.getFlightgroupName () name = un.getName () if ((fg==fgname) and (fac==faction)): if (numships>0): if (vsrandom.random()<0.75): pos=move_to (un,pos) numships-=1 newship[0]=un debug.info("TTYmoving %s to current area" % (name)) else: #toast 'im! un.Kill() debug.info("TTYaxing %s" % (name)) i-=1 return (numships,pos)
def setupEnemy (self): if not self.started: print('Tail Error checking: '+self.directions[0]) print('Tail Error checking: '+self.directions[0].lower()) if self.started: return True elif self.directions[0].lower().find(VS.getPlayerX(self.cp).getUnitSystemFile().lower())!=-1: L = launch.Launch() L.fg=self.enemyfg L.dynfg=self.enemydynfg if self.enemydyntype=='': self.enemydyntype=faction_ships.getRandomFighter(self.enemyfaction) L.type = self.enemydyntype L.faction = self.enemyfaction L.ai = "default" L.num=self.enemynum L.minradius=self.mindist L.maxradius=self.startdist try: L.minradius*=faction_ships.launch_distance_factor L.maxradius*=faction_ships.launch_distance_factor except: pass self.enemy=L.launch(VS.getPlayerX(self.cp)) self.enemy.upgrade("jump_drive",0,0,0,1) self.relation = self.enemy.getRelation(VS.getPlayerX(self.cp)) self.enemy.setCombatRole("INERT") self.updateEnemyObjective() VS.IOmessage (0,"[Mission Computer]","all","Target %s detected! Proceed as per mission instructions."%self.enemy.getFullname()) self.objref=VS.addObjective("Follow the %s until it broadcasts the signal"%self.enemy.getFullname()) self.started=True return True print("now NOT set up!") return False
def launch_new_wave(self): un = VS.getPlayer() if (vsrandom.randrange(0,4)==0): if (un): currentsystem = VS.getSystemFile() numadj=VS.GetNumAdjacentSystems(currentsystem) if (numadj): cursys=VS.GetAdjacentSystem(currentsystem,vsrandom.randrange(0,numadj)) else: cursys = 'enigma_sector/heavens_gate' debug.info("TJ: jumping to "+cursys) un.JumpTo(cursys) else: debug.warn("TJ: jumping to [ERROR: you are null]") return else: siglist=universe.significantUnits() if len(siglist)==0: debug.info("TJ: siglist empty") return sig=siglist[vsrandom.randrange(0,len(siglist))] if (not sig): debug.info("TJ: sig null") return debug.info("TJ: autopiloting to "+sig.getName()) un.AutoPilotTo(sig,True) un.SetTarget(sig)
def launchBaseOrbit(type,faction,loc,orbitradius,orbitspeed,unit): #orbitradius*=2 import Vector import dynamic_universe R = Vector.Vector(vsrandom.uniform(1.25*orbitradius,orbitradius), vsrandom.uniform(1.25*orbitradius,orbitradius), vsrandom.uniform(1.25*orbitradius,orbitradius)) RMag = Vector.Mag(R) T = Vector.Vector(vsrandom.uniform(.5*orbitradius,orbitradius), vsrandom.uniform(.75*orbitradius,.85*orbitradius), vsrandom.uniform(.5*orbitradius,orbitradius)) S = Vector.Cross (T,R) S = Vector.Scale(S, vsrandom.uniform (1.5*orbitradius,orbitradius) /Vector.Mag(S)) SMag = Vector.Mag(S) bas=VS.launch("Base",type,faction,"unit","default",1,1,Vector.Add(loc,R),'') nam=GetRandomBaseName (1,faction); R = Vector.Scale (R,(RMag+2.0*bas.rSize())/RMag) S = Vector.Scale (S,(SMag+2.0*bas.rSize())/SMag) bas.orbit (unit,orbitspeed,R,S,(0.0,0.0,0.0)) #bas.SetPosition(Vector.Add(loc,R)) dynamic_universe.TrackLaunchedShip (BaseFGInSystemName(VS.getSystemFile()), faction, type, bas)
def onSkip(self, button, params): global starting_new_game, plist_monologue PreIntroRoom.onSkip(self, button, params) #DoStartNewGame(self, params) starting_new_game = True VS.musicPlayList(plist_monologue) Base.SetCurRoom(intro_guiroom.getIndex())
def mpl(list,newsituation,forcechange): global situation debug.info("SITUATION IS "+str( situation)+" force change "+str(forcechange) + " bool "+ str(forcechange or newsituation!=situation)) if (forcechange or newsituation!=situation): debug.info("SITUATION IS RESET TO "+str( newsituation)) situation=newsituation VS.musicPlayList(list)
def __init__ (self, creds, faction, quantity, category, returntobase, var_when_done=''): Director.Mission.__init__ (self) self.newship="" self.mplay="all" self.obj=0 self.enemy=VS.Unit() self.curiter=0 self.content="" self.quantity=quantity self.arrived=0 self.faction = faction self.cred=creds self.category=category self.donevar=var_when_done sysfile = VS.getSystemFile() self.newship=faction_ships.getRandomFighter('merchant') self.you=VS.getPlayer() self.pos=self.you.Position() self.gosig=go_somewhere_significant(self.you,0,10000.) self.mplay=universe.getMessagePlayer(self.you) if (self.you): VS.IOmessage (0,"plunder mission",self.mplay,"Your mission is to destroy a %s merchant unit." % (self.newship)) VS.IOmessage (1,"plunder mission",self.mplay,"It is orbiting around the %s planet in the system." % (unit.getUnitFullName(self.gosig.SignificantUnit()))) VS.IOmessage (2,"plunder mission",self.mplay,"After it is destroyed, pick up all %s cargo that got ejected."%self.category) VS.IOmessage (3,"plunder mission",self.mplay,"Then return to a %s base with your cargo. #00ff00Good luck!"%self.faction) else: print("aboritng plunder constructor...") VS.terminateMission (0)
def seed(self, a=None): """Initialize internal state from hashable object. None or no argument seeds from current time. If a is not None or an int or long, hash(a) is used instead. If a is an int or long, a is used directly. Distinct values between 0 and 27814431486575L inclusive are guaranteed to yield distinct internal states (this guarantee is specific to the default Wichmann-Hill generator). """ if a is None: # Initialize from current time import VS a = int(VS.timeofday() * 256) if type(a) not in (type(3), type(3)): a = hash(a) a, x = divmod(a, 30268) a, y = divmod(a, 30306) a, z = divmod(a, 30322) self._seed = int(x)+1, int(y)+1, int(z)+1
def __init__( self, savevar, systems, delay, faction, numenemies, dyntype='', dynfg='', greetingText=[ "Hello there, smuggler. Prepare to die!", "The price on your head is big enough that I missed my lunch" ], directions=[], destination='', AdjustFaction=True): directions_mission.directions_mission.__init__(self, savevar, directions, destination) print('Ambush: Starting') self.faction = faction self.systems = systems if type(systems) != tuple and type(systems) != list: self.systems = (systems, ) self.numenemies = numenemies self.dyntype = dyntype self.dynfg = dynfg self.greetingText = greetingText self.cp = VS.getCurrentPlayer() self.delay = delay self.privateSetupPlayer() self.AdjustFaction = AdjustFaction
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
def getPriceModifier(isUncapped): import difficulty if (not difficulty.usingDifficulty()): return 1.0 if (isUncapped): return getMissionDifficulty() / .5 + .9 return VS.GetDifficulty() / .5 + .9
def DifferentSystemP(self): cursys = VS.getSystemFile() if (cursys == self.cur.lastsys): return 0 self.NewSystemHousekeeping(self.cur.lastsys, cursys) self.cur.lastsys = cursys return 1
def Win(self, un, terminate): VS.IOmessage(0, "plunder mission", self.mplay, "#00ff00Excellent work pilot.") VS.IOmessage( 0, "plunder mission", self.mplay, "#00ff00You have been rewarded for your effort as agreed.") VS.IOmessage( 0, "plunder mission", self.mplay, "#00ff00Your contribution to the war effort will be remembered.") debug.info("do you win?") un.addCredits(self.cred) if len(self.donevar): quest.removeQuest(self.you.isPlayerStarship(), self.donevar, 1) if (terminate): debug.info("you win plunder mission!") VS.terminateMission(1)
def launchBaseStuck(type, faction): un = VS.getPlayer() maxspeed = 100.1 if (un): maxspeed = un.maxAfterburnerSpeed() + 30.1 un.setNull() launchBaseOrbit(type, faction, un.Position(), maxspeed * 180, 0, un)
def moveOutOfPlayerPath(un): def reposition(un, playa, min_distance, vel): ex = (vsrandom.uniform(-1, 1), vsrandom.uniform(-1, 1), vsrandom.uniform(-1, 1)) if vel[0] == 0 and vel[1] == 0 and vel[2] == 0: vel = (1, 0, 0) dir = Vector.Scale(Vector.ScaledCross(ex, vel), min_distance) debug.debug("offsetting you a few meters to the %s" % (str(dir))) un.SetPosition(Vector.Add(playa.Position(), dir)) playa = VS.getPlayer() min_distance = 100 min_forward_distance = 1300 try: min_distance = faction_ships.min_distance min_forward_distance = faction_ships.min_forward_distance except: debug.debug("badness no faction_ships.min_distance") dis = un.getDistance(playa) vel = playa.GetVelocity() vel = Vector.SafeNorm(vel) if (dis < min_distance): reposition(un, playa, min_distance, vel) dir = Vector.SafeNorm(Vector.Sub(playa.Position(), un.Position())) if (dis < min_forward_distance and Vector.Dot(dir, vel) > .8): reposition(un, playa, min_distance, vel)
def GetStats(name): try: return stattable[name] except: shipclass = VS.LookupUnitStat(name, "default", "Combat_Role") debug.info('cannot find ' + name + ' in stattable, using defaults for class ' + shipclass + ' - fix faction_ships_lists.py') if ((shipclass == "INTERCEPTOR") or (shipclass == "FIGHTER") or (shipclass == "SCAVENGER")): return (0.62, 0.66, 18, 52.5, 48) if (shipclass == "TROOP"): return (.5, .5, 1, 1, 1) if (shipclass == "BOMBER"): return (0.44, 0.48, 95.8, 80, 148) if (shipclass == "MERCHANTMAN"): return (0.1, 0.2, 32.8, 80, 38) if (shipclass == "CAP_NOPHASE"): return (0.26, 0.2, 68.3, 220, 66) if (shipclass == "CAP_PHASE"): return (0.2, 0.2, 77.22, 260, 66) if (shipclass == "CARRIER"): return (0.26, 0.2, 68.3, 320, 66) if (shipclass == "BASE"): return (.5, 0, 600, 6000, 2) else: return (.5, .5, 1, 1, 1)
def getRandomJumppoint(): jp_list = getJumppointList() size = len(jp_list) if (size > 0): return jp_list[vsrandom.randrange(0, size)] else: return VS.Unit()
def MakeContraband(which): constructor = cargo_mission.cargo_mission numsys = vsrandom.randrange(2, 5) jumps = universe.getAdjacentSystems(VS.getSystemFile(), numsys)[1] diff = vsrandom.randrange(0, 3) creds = numsys * 2500 + diff * 800 args = ('pirates', 0, 6, diff, creds, 1, 1200, 'Contraband', jumps) briefing0 = 'We need some...*cough*... cargo delivered to some of our pirates in a nearby system: ' + Jumplist( jumps ) + ' It\'d be preferable if ye kept the ole po\' off yo back durin the run. Will ya do it for ' + str( creds) + ' creds?' briefing1 = 'Thanks pal; keep it on the d&l if you know my meanin.' vars = { 'MISSION_TYPE': 'CONTRABAND', 'MISSION_SHORTDESC': 'Deliver contraband to %s for %s' % (Jumplist(jumps), creds) } try: vars['MISSION_ID'] = vars['MISSION_ID'] except: vars['MISSION_ID'] = which description = vars['MISSION_SHORTDESC'] AddNewMission(description, args, constructor, briefing0, briefing1, vars, vars) return ("bases/fixers/pirate.spr", "Talk with the Pirate", which)
def mission_success(self): self.confed_cruiser = launch.launch_wave_around_unit( "Sonorous", "confed", "corvette", "default", 1, 4000, 8000, self.cargo_container) self.confed_epeels = launch.launch_wave_around_unit( "Sonorous E1", "confed", "epeellcat", "default", 5, 1000, 1000, self.confed_cruiser) VS.IOmessage(3, "Sonorous Command", "all", "Attention Private Vessel!") VS.IOmessage( 4, "Sonorous Command", "all", "Under Code 1530 of the Trade Practices Charter, we take posession of this cargo pod." ) VS.IOmessage(6, "Sonorous Command", "all", "Please remove yourself or we will remove you.") self.jumpout = 0 self.quest_exit = 1
def LaunchAlly(self): import launch import faction_ships import universe L = launch.Launch() L.faction = self.friendlyfaction L.fg = "Patrol_Wing" L.dynfg = "" L.minradius = 3000.0 L.maxradius = 4000.0 try: L.minradius *= faction_ships.launch_distance_factor L.maxradius *= faction_ships.launch_distance_factor except: pass L.num = 1 L.ai = "default" L.type = faction_ships.getRandomCapitol(self.friendlyfaction) self.allyobj = VS.addObjective("Protect the %s" % L.type) self.ally = L.launch(self.you) L.type = faction_ships.getRandomFighter(self.friendlyfaction) import vsrandom L.num = vsrandom.randrange(3, 6) L.launch(self.you) universe.greet(self.allygreetingtext, self.ally, self.you)
def create(self, roomid): if VS.isserver(): return self.calculateWidth() x = self.totalwidth / -2. y = self.totalheight / 2. room = GUI.GUIRoom(roomid) self.roomid = roomid if not self.bg: rect = makeRect(x - 0.01, y + 0.01, self.totalwidth + 0.02, self.totalheight + 0.02) size = rect.getHotRect() self.bgsize = size #print str(rect) #print (x,y,self.totalwidth,self.totalheight) self.bg = GUI.GUIStaticText(room, self.idname, '', rect, color=GUI.GUIColor(0.6, 0.6, 0.6, 1.0), bgcolor=GUI.GUIColor( 0.2, 0.2, 0.2, 0.8)) self.bglink = GUI.GUIMouseOver(room, 'Dialog box', self.idname, rect) for el in self.elements: hei = el.height() #print "*** Creating "+repr(el)+" at y "+str(y)+", height "+str(hei) el.create(self, room, x, y, self.totalwidth, hei) y -= hei
def initbriefing(self): VS.IOmessage( 0, "cargo mission", "briefing", "Your mission for today will be to run some %s cargo" % self.cargoname) self.briefgametime = 0 self.adjsys.initbriefing()
def AddNewMission(which, args, constructor=None, briefing0='', briefing1='', vars0=None, vars1=None): """ Adds a mission to the list of missions stored in playerInfo. """ if not isinstance(vars0, dict): vars0 = dict() vars1 = vars0 if VS.isserver(): lenvars0 = len(vars0) sendargs = ["AddNewMission", which, briefing0, briefing1, lenvars0] for key in vars0: sendargs.append(key) sendargs.append(vars0[key]) custom.run("mission_lib", sendargs, None) plr = getMissionPlayer() addPlayer(plr, False) playerInfo = players[plr] which = str(which) playerInfo.last_constructor[which] = constructor playerInfo.last_args[which] = args playerInfo.last_briefing[0][which] = briefing0 playerInfo.last_briefing[1][which] = briefing1 playerInfo.last_briefing_vars[0][which] = vars0 playerInfo.last_briefing_vars[1][which] = vars1
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 savelist(): global savefilters return [ GUI.GUISimpleListPicker.listitem(path, path) for path in time_sorted_listdir(VS.getSaveDir()) if path[:1] != '.' and path not in savefilters ]
def translateItem(self, item, news_tuple, docked_faction): """Using the given item and information, returns a fully translated version of the item.""" self.rand_int = news_tuple[NewsManager.RANDOM_INTEGER_INDEX] self.item = item[2].split() self.vars = dict() stardat_ = dict() if news_tuple[NewsManager.STARDATE_INDEX] == 0: stardat_['value'] = VS.getStarTime() else: stardat_['value'] = news_tuple[NewsManager.STARDATE_INDEX] self.vars['stardate'] = stardat_ aggressor = dict() aggressor['faction'] = news_tuple[NewsManager.AGGRESSOR_INDEX] aggressor['FG'] = news_tuple[NewsManager.AGGRESSOR_FLIGHTGROUP_INDEX] aggressor['FGtype'] = LookupRealName(news_tuple[NewsManager.AGGRESSOR_SHIPTYPE_INDEX],aggressor['faction']) self.vars['aggressor'] = aggressor defender = dict() defender['faction'] = news_tuple[NewsManager.DEFENDER_INDEX] defender['FG'] = news_tuple[NewsManager.DEFENDER_FLIGHTGROUP_INDEX] defender['FGtype'] = LookupRealName(news_tuple[NewsManager.DEFENDER_SHIPTYPE_INDEX],defender['faction']) self.vars['defender'] = defender dockeda_ = dict() dockeda_['faction'] = docked_faction self.vars['dockedat'] = dockeda_ system = SystemInformation(news_tuple[NewsManager.EVENT_SYSTEM_INDEX]) syste_ = dict() syste_['system'] = system.getInfo(system.SYSTEM) syste_['sector'] = system.getInfo(system.SECTOR) self.vars['system'] = syste_ for i in range(len(self.item)): self.item[i] = self.translateWord(self.item[i]) return " ".join(self.item) + self.STARDATE_TEXT + stardate.formatStarDate(self.vars['dockedat']['faction'],self.vars['stardate']['value']) + "\\INDY - Independent Daily Yarn"
def FGsLaunchedInCurrentSystemAsSet(): rvset = {} iter = VS.getUnitList() while (not iter.isDone()): un = next(iter) rvset[un.getFlightgroupName()] = 1 return rvset
def reinit(self): self.current_un = VS.Unit() self.objectives = 0 self.player_num = -1 self.callsign = '' self.ship = '' self.docked_un = None
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 __init__( self, num_significants_to_patrol, distance_from_base, creds, savevar, systems, delay, faction, numenemies, dyntype='', dynfg='', greetingText=[ "Hello there, smuggler. Prepare to die!", "The price on your head is big enough that I missed my lunch" ], directions=[], destination=''): ambush.ambush.__init__(self, savevar, systems, delay, faction, numenemies, dyntype, dynfg, greetingText, directions, destination) self.jnum = 0 self.cred = creds self.patrolpoints = [] self.objectives = [] self.distance = distance_from_base you = VS.getPlayer() self.quantity = num_significants_to_patrol name = you.getName() self.mplay = universe.getMessagePlayer(you) self.AdjustFaction = False
def VertSlit(): global filename filename = fname.get() start_ds9() resultstr.set(VS.doit(filename, datapath, messageTextWidget)) wortel.tkraise() wortel.update_idletasks()
def abletodraw(self): for cond in self.precondition: var = cond[0] value = cond[1] if not checkSaveValue(VS.getCurrentPlayer(), var, value): return 0 return 1
def MakeBar(concourse, concoursetext, bartext, BaseTexture, createCampaignFixers=True, defaultbtr=None, forcedefbtr=False, bartenderprefix="", bartenderloc=(.89725,.0813), patrons=[],fixerlocations=[(-0.80025, -1.0088, 0.776, 1.2416),(-0.0725, -0.4058125, 0.1758125, 0.5385)]): if vsrandom.random()<.6: forcedefbtr=True # remove me if you want random bartenders at random bars import bartender bartender.speaktimes=0 room0 = Base.Room ('Bar') x=0 y=0 Base.Texture (room0, 'background', BaseTexture+'.spr', x, y) for p in patrons: if vsrandom.random()<.85: Base.Texture(room0,str(p[0]),'bases/generic/'+str(p[0])+'.spr',float(p[1]),float(p[2])) if defaultbtr: if not forcedefbtr: defaultbtr=bartenders[vsrandom.randrange(len(bartenders))] Base.Texture(room0,'btr','bases/generic/'+bartenderprefix+'bartender'+str(defaultbtr)+'.spr', float(bartenderloc[0]),float(bartenderloc[1])) if VS.networked(): Base.Python (room0, 'newscomp', -1, .7, .3, .3, 'Public Terminal', '#\nimport custom\ncustom.run("computer",[],None)',True) else: Base.Comp (room0, 'newscomp', -1, .7, .3, .3, 'Public Terminal', 'News') Base.Link (room0, 'my_link_id', -0.998047, -0.997396, 1.99414, 0.119792, concoursetext ,concourse) Base.Python (room0, 'talk', bartenderloc[0]-.16, bartenderloc[1]-.15,.3,.3,'Talk to the Bartender',bartext,0) import fixers func=fixers.CreateFixers if not createCampaignFixers: func=fixers.CreateMissionFixers func(room0,[(fixerlocations[0][0],fixerlocations[0][1],fixerlocations[0][2],fixerlocations[0][3],"_1"),(fixerlocations[1][0],fixerlocations[1][1],fixerlocations[1][2],fixerlocations[1][3],"_2")])#add more locations? return room0;
def completeAccept(args): if VS.networked(): if args[0]=="success" or args[0]=="notavailable": mission_lib.BriefLastMission(self.missionname,1,self.guild.textbox) mission_lib.RemoveLastMission(self.missionname) if args[0]=="toomany": self.guild.TooManyMissions()
def updatePlayerKillList(playernum, faction): global player_kill_list fac = VS.GetFactionIndex(faction) ret = 0 for i in range(VS.getNumPlayers() - len(player_kill_list)): player_kill_list.append([]) for i in range(VS.getNumPlayers()): numfac = Director.getSaveDataLength(i, "kills") for j in range(numfac - len(player_kill_list[i])): player_kill_list[i].append(0) for j in range(numfac): if (i == playernum and j == fac): ret = Director.getSaveData(i, "kills", j) - player_kill_list[i][j] player_kill_list[i][j] = Director.getSaveData(i, "kills", j) return ret
def DestroyUnit (self): playa = VS.getPlayer() if (not playa.isNull()): if (vsrandom.randrange(0,2)==0): un=playa.GetTarget() if (not un.isNull()): if (self.unitRipe(playa,un)): self.killUnit(un) return i=VS.getUnitList () un = i.current() while (not un.isNull()): if (self.unitRipe(playa,un)): self.killUnit(un) return un = i.next()
def CountSystems(sys): fac = VS.GetGalaxyFaction(sys) if fac in systemcount: systemcount[fac] += 1 else: systemcount[fac] = 1 systemcount[None] += 1