Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
 All Data Structures Namespaces Files Functions Variables
dynamic_mission.py
Go to the documentation of this file.
1 #""" This module provides different mission types. """
2 
3 import VS
4 import PickleTools
5 import Director
6 import fg_util
7 import vsrandom
8 import faction_ships
9 import universe
10 import dynamic_universe
11 import dynamic_news
12 import debug
13 import generate_dyn_universe
14 
15 global dnewsman_
17 
18 plr=0
19 basefac='neutral'
20 
21 def formatShip(ship):
22  where=ship.find(".blank")
23  if (where!=-1):
24  ship=ship[0:where]
25  return ship.capitalize()
26 
28  where=ship.rfind("/")
29  if (where!=-1):
30  ship=ship[where+1:]
31  return ship.capitalize()
32 
33 #Credit to Peter Trethewey, master of python and all things nefarious
34 def getSystemsKAwayNoFaction( start, k ):
35  set = [start]#set of systems that have been visited
36  pathset = [[start]]#parallel data structure to set, but with paths
37  pathtor = [[start]]#parallel data structure to raw return systems with path
38  r = [start] #raw data structure containing systems n away where n<=k
39  for n in range(0,k):
40  set.extend(r)
41  pathset.extend(pathtor)
42  r=[]
43  pathtor=[]
44  for iind in range(len(set)):
45  i = set[iind]
47  for jind in range(len(l)):
48  j=l[jind]
49  if not (j in set or j in r):
50  r.append(j)
51  pathtor.append(pathset[iind]+[j])
52  return pathtor
53 
54 def getSystemsNAway (start,k,preferredfaction):
55  l = getSystemsKAwayNoFaction(start,k)
56  if (preferredfaction==None):
57  return l
58  lbak=l
59  if (preferredfaction==''):
60  preferredfaction=VS.GetGalaxyFaction(start)
61  i=0
62  while i <len(l):
63  if (VS.GetRelation(preferredfaction,VS.GetGalaxyFaction(l[i][-1]))<0):
64  del l[i]
65  i-=1
66  i+=1
67  if (len(l)):
68  return l
69  return lbak
70 
71 syscreds = int(VS.vsConfig("dynamic_universe","missions.defaults.jumpprice","3000"))
72 
73 
75  bnl=[]
76  debug.debug('reading company names ')
77  filename = '../universe/companies.txt'
78  try:
79  f = open (filename,'r')
80  bnl = f.readlines()
81  f.close()
82  except:
83  return ''
84  for i in range(len(bnl)):
85  bnl[i]=bnl[i].rstrip()
86  import vsrandom
87  idx = vsrandom.randint(0,len(bnl)-1)
88  return bnl[idx]
89 
91  bnl=[]
92  brief=''
93  debug.debug('generating cargo briefing')
94  filename = '../universe/cargo_brief.txt'
95  try:
96  f = open (filename,'r')
97  bnl = f.readlines()
98  f.close()
99  except:
100  return ''
101  for i in range(len(bnl)):
102  bnl[i]=bnl[i].rstrip()
103  import vsrandom
104  idx = vsrandom.randint(0,len(bnl)-1)
105  brief = bnl[idx]
106  return brief
107 
108 def getCargoName(category):
109  l=category.split('/')
110  if len(l)>1:
111  cargo = l[len(l)-1]+' '+l[0]
112  else:
113  cargo = category
114  cargo = cargo.replace('_',' ')
115  return cargo
116 
118  import difficulty
119  tmp=difficulty.getPlayerUnboundDifficulty(VS.getCurrentPlayer())
120  if (tmp>1.5):
121  tmp=1.5
122  return tmp
123 
124 def getPriceModifier(isUncapped):
125  import difficulty
126  if (not difficulty.usingDifficulty()):
127  return 1.0
128  if (isUncapped):
129  return getMissionDifficulty()/.5+.9
130  return VS.GetDifficulty()/.5+.9
131 
132 def howMuchHarder(makeharder):
133  import difficulty
134  if (makeharder==0):
135  return 0
136  udiff = getMissionDifficulty()
137  if (udiff<=1):
138  return 0
139  return int(udiff*2)-1
140 
141 def processSystem(sys):
142  k= sys.split('/')
143  if (len(k)>1):
144  k=k[1]
145  else:
146  k=k[0]
147  return k
148 
149 totalMissionNumber=0
150 insysMissionNumber=0
151 
153  global insysMissionNumber
154  if insysMissionNumber:
155  insysMissionNumber=0
156  return True
157  return False
158 
160  global totalMissionNumber
161  if totalMissionNumber:
162  totalMissionNumber=0
163  return True
164  return False
165 
167  if (checkMissionNum()+checkInsysNum()>0):
168  return True
169  return False
170 
172  k=str(s)
173  if (len(k)<2):
174  return 0
175  if (k[1]=='F'):
176  return 1
177  if (k[1]=='G'):
178  return 2
179  return 0
180 def writemissionname(name,path,isfixer):
181  if (isfixer==0):
182  if path[-1]==VS.getSystemFile():
183  name="In_System_"+name
184  global insysMissionNumber
185  insysMissionNumber+=1
186  else:
187  global totalMissionNumber
188  totalMissionNumber+=1
189  Director.pushSaveString(plr, "mission_names", name)
190 
191 
193  Director.pushSaveString(plr, "mission_descriptions", name.replace("_"," "))
194 
196  Director.pushSaveString(plr, "mission_scripts", name)
197 
198 def writemissionvars (vars):
199  Director.pushSaveString(plr, "mission_vars", PickleTools.encodeMap(vars))
200 
202  Director.clearSaveString(plr, "mission_scripts")
203  Director.clearSaveString(plr, "mission_names")
204  Director.clearSaveString(plr, "mission_descriptions")
205  Director.clearSaveString(plr, "mission_vars")
206 
208  import sys
209  len=Director.getSaveStringLength(plr, "mission_scripts")
210  if (len!=Director.getSaveStringLength(plr, "mission_names") or len!=Director.getSaveStringLength(plr, "mission_descriptions")):
211  sys.stdout.write("Warning: Number of mission descs., names and scripts are unequal.\n")
212  if len>0:
213  for i in range(len-1,-1,-1):
214  Director.eraseSaveString(plr, "mission_scripts", i)
215  Director.eraseSaveString(plr, "mission_names", i)
216  Director.eraseSaveString(plr, "mission_descriptions", i)
217  Director.eraseSaveString(plr, "mission_vars", i)
218 
219 fixerpct=0.02
220 guildpct=0.4
221 
223  global fixerpct
224  global guildpct
225  fixerpct=.0625
226  guildpct=.4
227 
229  global fixerpct
230  global guildpct
231  fixerpct=.0375
232  guildpct=1
233 
234 def generateCleansweepMission(path,numplanets,enemy,
235  pricescale = float(VS.vsConfig("dynamic_universe","missions.cleansweep.pricescale","16000")),
236  jumpscale = float(VS.vsConfig("dynamic_universe","missions.cleansweep.jumpscale","1.2")),
237  sweepmod = float(VS.vsConfig("dynamic_universe","missions.cleansweep.pricemod.sweep","4")),
238  capshipmod = float(VS.vsConfig("dynamic_universe","missions.cleansweep.pricemod.capship","4")),
239  forceattackmod = float(VS.vsConfig("dynamic_universe","missions.cleansweep.pricemod.forceattack","0.25"))
240  ):
241  fighterprob=vsrandom.random()*.75+.25;
242  capshipprob=0.0
243  if (vsrandom.random()<.2):
244  capshipprob=vsrandom.random()*.25;
245  forceattack=vsrandom.randrange(0,2)
246  cleansweep=vsrandom.randrange(0,2)
247  minships=maxships=vsrandom.randrange(1,4)
248  creds = ( pricescale * (
249  1+
250  cleansweep*sweepmod+
251  capshipprob*capshipmod+
252  forceattack*forceattackmod
253  ) * minships * fighterprob
254  + jumpscale * syscreds * len(path) )
255  creds*=getPriceModifier(False)
256  addstr=""
257  isFixer=vsrandom.random()
258  if isFixer<fixerpct:
259  creds*=2
260  addstr+="#F#bases/fixers/confed.spr#Talk to the Confed Officer#Thank you. Your help makes space a safer place.#\n"
261  elif isFixer<guildpct:
262  creds*=1.5
263  if (cleansweep):
264  addstr+="#G#Bounty#\n"
265  else:
266  addstr+="#G#Patrol#\n"
267  missiontype="patrol_enemies"
268  additional=""
269  additionalinstructions=""
270  patrolorclean="Patrol"
271  dist=1000
272  if (cleansweep):
273  dist=1500
274  additional=",1"
275  patrolorclean="Clean_Sweep"
276  missiontype="cleansweep"
277  additionalinstructions+=" Eliminate all such forces encountered to receive payment."
278  if (capshipprob):
279  additionalinstructions+=" Capital ships are possibly in the area."
280 
281  writemissionsavegame (addstr+"import %s\ntemp=%s.%s(0, %d, %d, %d, %s,'',%d,%d,%f,%f,'%s',%d%s)\ntemp=0\n"%(missiontype,missiontype,missiontype,numplanets, dist, creds, str(path),minships,maxships,fighterprob,capshipprob,enemy,forceattack,additional))
282  writedescription("Authorities would like a detailed scan of the %s system. We require %d nav locations be visited on the scanning route. The pay for this mission is %d. Encounters with %s forces likely.%s"%(processSystem(path[-1]),numplanets,creds,enemy,additionalinstructions))
283  ispoint="s"
284  if numplanets==1:
285  ispoint=""
286  if len(path)==1:
287  mistype = 'IN-SYSTEM ATTACK'
288  else:
289  mistype = 'ATTACK'
290  writemissionname("%s/%s_%d_Point%s_in_%s"%(patrolorclean,patrolorclean,numplanets,ispoint, processSystem(path[-1])),path,isFixerString(addstr))
291  writemissionvars( { 'MISSION_TYPE' : mistype } )
292 
293 def generatePatrolMission (path, numplanets,
294  planetprice = float(VS.vsConfig("dynamic_universe","missions.patrol.planetprice","100")),
295  baseprice = float(VS.vsConfig("dynamic_universe","missions.patrol.baseprice","2400")),
296  jumpscale = float(VS.vsConfig("dynamic_universe","missions.patrol.jumpscale","1"))
297  ):
298  dist=400
299  creds = numplanets*planetprice+baseprice+jumpscale*syscreds*len(path)
300  creds*=getPriceModifier(False)
301  addstr=""
302  isFixer=vsrandom.random()
303  if isFixer<fixerpct:
304  creds*=2
305  addstr+="#F#bases/fixers/confed.spr#Talk to the Confed Officer#Thank you. Your help makes space a safer place.#\n"
306  elif isFixer<guildpct:
307  creds*=1.5
308  addstr+="#G#Patrol#\n"
309  writemissionsavegame (addstr+"import patrol\ntemp=patrol.patrol(0, %d, %d, %d, %s)\ntemp=0\n"%(numplanets, dist, creds, str(path)))
310  writedescription("Insystem authorities would like a detailed scan of the %s system. We require %d nav locations be visited on the scanning route. The pay for this mission is %d."%(processSystem(path[-1]),numplanets,creds))
311  ispoint="s"
312  if numplanets==1:
313  ispoint=""
314  if len(path)==1:
315  mistype = 'IN-SYSTEM PATROL'
316  else:
317  mistype = 'PATROL'
318  writemissionname("Patrol/Patrol_%d_Point%s_in_%s"%(numplanets,ispoint, processSystem(path[-1])),path,isFixerString(addstr))
319  writemissionvars( { 'MISSION_TYPE' : mistype } )
320 
321 def isNotWorthy(fac):
322  return VS.GetRelation(fac,VS.getPlayer().getFactionName())<0
323 
324 def generateEscortLocal(path,fg,fac,
325  waveprice = float(VS.vsConfig("dynamic_universe","missions.escort.local.waveprice","5500"))
326  ):
327  if (isNotWorthy(fac)):
328  return
329  typ = fg_util.RandomShipIn(fg,fac)
330  if typ in faction_ships.unescortable:
331  typ = faction_ships.unescortable[typ]
332  enfac = faction_ships.get_enemy_of(fac)
333  diff=vsrandom.randrange(1,4)
334  waves=vsrandom.randrange(0,5-diff)
335  incoming=vsrandom.randrange(0,2)
336  enfg =fg_util.AllFGsInSystem(enfac,path[-1])
337  creds=waveprice*diff*(1+waves);
338  if (len(enfg)):
339  enfg=enfg[vsrandom.randrange(0,len(enfg))]
340  else:
341  enfg=''
342  isFixer=vsrandom.random()
343  addstr=""
344  if isFixer<fixerpct:
345  creds*=2
346  addstr+="#F#bases/fixers/merchant.spr#Talk to the Merchant#Thank you. I entrust that you will safely guide my collegue until he reaches the destination.#\n"
347  elif isFixer<guildpct:
348  creds*=1.5
349  addstr+="#G#Escort#\n"
350  additionalinfo="to the jump point"
351  if (incoming):
352  additionalinfo="from the jump point to a nearby base"
353  if len(path)==1:
354  mistype = 'IN-SYSTEM ESCORT'
355  else:
356  mistype = 'ESCORT'
357  writemissionsavegame(addstr+"import escort_local\ntemp=escort_local.escort_local('%s',0,%d,%d,500,%d,%d,'%s',(),'','%s','','%s','%s')"%(enfac,diff,waves,creds,incoming,fac,enfg,fg,typ))
358  writedescription("Escort %s is required for the %s type %s starship from the %s flightgroup in this system. Attacks from the %s faction are likely. You will be paid %d credits if the starship survives in this starsystem until it reaches its destination."%(additionalinfo,formatShip(typ),fac,fg,enfac,int(creds)))
359  writemissionname("Escort/Escort_%s_%s"%(fac,fg),[path[-1]],isFixerString(addstr))
360  writemissionvars( { 'MISSION_TYPE' : mistype } )
361 
362 def generateEscortMission (path,fg,fac,
363  baseprice = float(VS.vsConfig("dynamic_universe","missions.escort.waveprice","500")),
364  jumpscale = float(VS.vsConfig("dynamic_universe","missions.escort.jumpscale","0.5"))
365  ):
366  ###
367  if (isNotWorthy(fac)):
368  return
369  typ = fg_util.RandomShipIn(fg,fac)
370  if typ in faction_ships.unescortable:
371  typ = faction_ships.unescortable[typ]
372  diff=vsrandom.randrange(0,6)
373  creds=baseprice*diff+jumpscale*syscreds*len(path)
374  creds*=getPriceModifier(False)
375  addstr=""
376  isFixer=vsrandom.random()
377  if isFixer<fixerpct:
378  creds*=2
379  addstr+="#F#bases/fixers/merchant.spr#Talk to the Merchant#Thank you. I entrust that you will safely guide my collegue until you reach the destination.#\n"
380  elif isFixer<guildpct:
381  creds*=1.5
382  addstr+="#G#Escort#\n"
383  if len(path)==1:
384  mistype = 'IN-SYSTEM ESCORT'
385  else:
386  mistype = 'ESCORT'
387  writemissionsavegame (addstr+"import escort_mission\ntemp=escort_mission.initrandom('%s', %d, %g, 0, 0, %s, '','%s','%s')\ntemp=0\n"%(fac, diff, float(creds), str(path),fg,typ))
388  writedescription("The %s %s in the %s flightgroup requres an escort to %s. The reward for a successful escort is %d credits."%(fac,formatShip(typ),fg, processSystem(path[-1]),creds))
389  writemissionname("Escort/Escort_%s_%s_to_%s"%(fac,fg,processSystem(path[-1])),path,isFixerString(addstr))
390  writemissionvars( { 'MISSION_TYPE' : mistype } )
391 
392 def changecat(category):
393  l=category.split('/')
394  if len(l)>1:
395  return l[-1]+'_'+l[0]
396  else:
397  return category
398 
399 def pathWarning(path,isFixer):
400  global dnewsman_
401  message = str()
402  factions = list()
403  if isFixer:
404  message+="\nPrecautions to ensure the success of this mission should be taken at your expense."
405  else:
406  for system in path:
407  sysfac = VS.GetGalaxyFaction(system)
408  if sysfac not in factions:
409  factions.append(sysfac)
410  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 "
411  if len(factions) == 1:
412  message+=dnewsman_.data.getFactionData(factions[0],'full')[0]+"."
413  else:
414  message+="following factions: "
415  jj=0
416  for fac in factions:
417  jj+=1
418  message+=dnewsman_.data.getFactionData(fac,'full')[0]
419  if jj<len(factions)-1:
420  message+=", "
421  elif jj<len(factions):
422  message+=" and "
423  return message
424 
426  return 3+int((max-3)*VS.GetDifficulty())
427 
428 def isHabitable (system):
429  planetlist=VS.GetGalaxyProperty(system,"planets")
430  if (len(planetlist)==0):
431  return False
432  planets=planetlist.split(' ')
433  for planet in planets:
434  if planet=="i" or planet=="a" or planet=="am" or planet=="u" or planet=="com" or planet=="bd" or planet=="s" or planet=="o" or planet=="at" or planet=="bs" or planet=="bdm" or planet=="bsm" or planet=="f" or planet=="fm" or planet=="t":
435  return True
436  debug.debug(str(planets)+ " Not in Habitable List")
437  return False
438 
439 def generateCargoMission (path, numcargos,category, fac,
440  baseprice = float(VS.vsConfig("dynamic_universe","missions.cargo.waveprice","500")),
441  jumpscale = float(VS.vsConfig("dynamic_universe","missions.cargo.jumpscale","0.2")),
442  cargoprice = float(VS.vsConfig("dynamic_universe","missions.cargo.cargoprice","250")),
443  contrabandprice = float(VS.vsConfig("dynamic_universe","missions.cargo.contrabandprice","5000")),
444  starshipprice = float(VS.vsConfig("dynamic_universe","missions.cargo.starshipprice","20000"))
445  ):
446  #if (isNotWorthy(fac)):
447  # return
448  launchcap=0 #(vsrandom.random()>=.97) #currently no delivering to capships, maybe only from
449  if (not launchcap) and not isHabitable(path[-1]):
450  return
452  creds = (
453  cargoprice*numcargos
454  +baseprice*diff
455  +jumpscale*syscreds*len(path)
456  +contrabandprice*(category[:10]=="Contraband")
457  +starshipprice*(category[:9]=="starships")
458  )
459  addstr=""
460  creds*=getPriceModifier(False)
461  isFixer=vsrandom.random()
462  if isFixer<fixerpct:
463  creds*=2
464  addstr+="#F#bases/fixers/merchant.spr#Talk to the Merchant#Thank you. I entrust you will make the delivery successfully.#\n"
465  elif isFixer<guildpct:
466  creds*=1.5
467  addstr+="#G#Cargo#\n"
468  writemissionsavegame (addstr+"import cargo_mission\ntemp=cargo_mission.cargo_mission('%s', 0, %d, %d, %g, %d, 0, '%s', %s, '')\ntemp=0\n"%(fac, numcargos, diff, creds, launchcap, category, str(path)))
469  if (category==''):
470  category='generic'
471  randCompany = GetRandomCompanyName()
472  if (randCompany==''):
473  strStart = "We need to deliver some "
474  else:
475  strStart = randCompany+" seeks delivery of "
476  brief = GetRandomCargoBrief()
477  if (brief<>''):
478  composedBrief = brief.replace('$CL',randCompany)
479  composedBrief = composedBrief.replace('$CG',formatCargoCategory(category))
480  composedBrief = composedBrief.replace(' $DB','')
481  composedBrief = composedBrief.replace('$DS',processSystem(path[-1]))
482  composedBrief = composedBrief.replace('$PY',str(int(creds)))
483  writedescription(composedBrief)
484  else:
485  writedescription(strStart+"%s cargo to the %s system. The mission is worth %d credits to us. You will deliver it to a base owned by the %s.%s"%(formatCargoCategory(category), processSystem(path[-1]),creds,fac,pathWarning(path,isFixer<guildpct)))
486  writemissionname("Cargo/Deliver_%s_to_%s"%(changecat(category),processSystem(path[-1])),path,isFixerString(addstr))
487 
488  if len(path)==1:
489  mistype = 'IN-SYSTEM CARGO'
490  else:
491  mistype = 'CARGO'
492  writemissionvars( { 'MISSION_TYPE' : mistype } )
493 
494 def generateRescueMission(path,rescuelist,
495  totmaxprice = int(VS.vsConfig("dynamic_universe","missions.rescue.totmaxprice","21000")),
496  shipminprice = int(VS.vsConfig("dynamic_universe","missions.rescue.pership.minprice","4041")),
497  shipmaxprice = int(VS.vsConfig("dynamic_universe","missions.rescue.pership.maxprice","8640")),
498  jumpminprice = int(VS.vsConfig("dynamic_universe","missions.rescue.perjump.minprice","4041")),
499  jumpmaxprice = int(VS.vsConfig("dynamic_universe","missions.rescue.perjump.maxprice","8640"))
500  ):
501  makemissionharder=vsrandom.randrange(0,2)
502  numships = vsrandom.randrange(1,adjustQuantityDifficulty(6))+howMuchHarder(makemissionharder)
503  creds = numships*vsrandom.randrange(shipminprice,shipmaxprice)
504  creds += len(path)*vsrandom.randrange(jumpminprice,jumpmaxprice)
505  creds = min(totmaxprice, creds)
506  creds *= getPriceModifier(makemissionharder!=0)
507  if len(path)==1:
508  mistype = 'IN-SYSTEM RESCUE'
509  else:
510  mistype = 'RESCUE'
511  writemissionsavegame("import rescue\nntemp=rescue.rescue(%d,0,'%s',%d,'%s','%s',%s)\nntemp=0"%(creds,rescuelist[0],numships,rescuelist[2],rescuelist[1],str(path)))
512  writedescription("SOS! This is an ejected %s pilot under attack by at least %d %s craft. I request immediate assistance to the %s system and will offer %d credits for a safe return to the local planet where I may recover."%(rescuelist[0],numships,rescuelist[2],processSystem(path[-1]),creds))
513  writemissionname("Rescue/Rescue_%s_from_%s_ships"%(rescuelist[0],rescuelist[2]),path,0)
514  writemissionvars( { 'MISSION_TYPE' : mistype } )
515 
516 def generateBountyMission (path,fg,fac,
517  baseprice = float(VS.vsConfig("dynamic_universe","missions.bounty.baseprice","20000")),
518  runawayprice = float(VS.vsConfig("dynamic_universe","missions.bounty.runaway","5000")),
519  diffprice = float(VS.vsConfig("dynamic_universe","missions.bounty.diffprice","500")),
520  jumpscale = float(VS.vsConfig("dynamic_universe","missions.bounty.jumpscale","1")),
521  capscale = float(VS.vsConfig("dynamic_universe","missions.bounty.capscale","4"))
522  ):
523  typ = fg_util.RandomShipIn(fg,fac)
524  cap = faction_ships.isCapital(typ)
525  makemissionharder=vsrandom.randrange(0,2)
526  diff=vsrandom.randrange(0,adjustQuantityDifficulty(7))+howMuchHarder(makemissionharder)
527  runaway=(vsrandom.random()>=.75)
528  creds = (
529  baseprice
530  +runawayprice*runaway
531  +diffprice*diff
532  +jumpscale*syscreds*len(path)
533  )
534  if (cap):
535  creds *= capscale
536 
537  finalprice=creds*getPriceModifier(False)
538  addstr=""
539  isFixer=vsrandom.random()
540  if isFixer<fixerpct:
541  finalprice*=2
542  addstr+="#F#bases/fixers/hunter.spr#Talk with the Bounty Hunter#We will pay you on mission completion. And as far as anyone knows - we never met."
543  if (runaway):
544  addstr += '#Also-- we have information that the target may be informed about your attack and may be ready to run. Be quick!'
545  addstr+="#\n"
546  elif isFixer<guildpct:
547  creds*=1.5
548  addstr+="#G#Bounty#\n"
549  writemissionsavegame(addstr+"import bounty\ntemp=bounty.bounty(0, 0, %g, %d, %d, '%s', %s, '', '%s','%s')\ntemp=0\n"%(finalprice, runaway, diff, fac, str(path), fg,typ))
550  diffstr = ""
551  if (diff>0):
552  diffstr=" The ship in question is thought to have %d starships for protection."%diff
553  if len(path)==1:
554  mistype = 'IN-SYSTEM BOUNTY'
555  else:
556  mistype = 'BOUNTY'
557  writedescription("A %s starship in the %s flightgroup has been harassing operations in the %s system. Reward for the termination of said ship is %d credits.%s"%(formatShip(typ),fg, processSystem(path[-1]), finalprice,diffstr))
558  if (cap):
559  writemissionname ("Bounty/on_%s_Capital_Vessel_in_%s"%(fac,processSystem(path[-1])),path,isFixerString(addstr))
560  else:
561  writemissionname ("Bounty/Bounty_on_%s_starship_in_%s"%(fac,processSystem(path[-1])),path,isFixerString(addstr))
562  writemissionvars( { 'MISSION_TYPE' : mistype } )
563 
564 def generateDefendMission (path,defendfg,defendfac, attackfg,attackfac,
565  baseprice = float(VS.vsConfig("dynamic_universe","missions.defend.baseprice","5000")),
566  jumpscale = float(VS.vsConfig("dynamic_universe","missions.defend.jumpscale","1"))
567  ):
568  if (isNotWorthy(defendfac)):
569  return
570  #defendtyp = fg_util.RandomShipIn(defendfg,defendfac)
571  attacktyp = fg_util.RandomShipIn(attackfg,attackfac)
572  isbase=fg_util.BaseFGInSystemName(path[-1])==defendfg
573  creds=baseprice
574  minq = 1
575  maxq = adjustQuantityDifficulty(5)
576  makemissionharder=vsrandom.randrange(0,2)
577  quantity = vsrandom.randrange(minq,maxq)+howMuchHarder(makemissionharder)
578  reallydefend = "1"
579  if (vsrandom.randrange(0,4)==0):
580  reallydefend="0"
581  addstr=""
582  creds=creds*quantity+jumpscale*syscreds*len(path)
583  creds*=getPriceModifier(makemissionharder)
584  isFixer=vsrandom.random()
585  if isFixer<fixerpct:
586  creds*=2
587  addstr+="#F#bases/fixers/confed.spr#Talk to the Confed Officer#Thank you. Your defense will help confed in the long run. We appreciate the support of the bounty hunting community.#\n"
588  elif isFixer<guildpct:
589  creds*=1.5
590  addstr+="#G#Defend#\n"
591  writemissionsavegame(addstr+"import defend\ntemp=defend.defend('%s', %d, %d, 8000.0, 100000.0, %g, %s, %d, '%s', %s, '%s', '%s', '%s', '%s')\ntemp=0\n"%
592  (attackfac, 0, quantity, creds, reallydefend, isbase, defendfac, str(path), '',attackfg, attacktyp,defendfg))
593  iscapitol=""
594  if isbase:
595  iscapitol="capital "
596  if len(path)==1:
597  mistype = 'IN-SYSTEM DEFEND'
598  else:
599  mistype = 'DEFEND'
600  writedescription("A %s assault wing named %s has jumped in and is moving for an attack on one of our %sassets in the %s system.\nYour task is to eradicate them before they eliminate our starship.\nIntelligence shows that they have %d starships of type %s. Your reward is %d credits."%(attackfac, attackfg, iscapitol, processSystem(path[-1]),quantity, formatShip(attacktyp),creds))
601  writemissionname("Defend/Defend_%s_from_%s"%(defendfac, attackfac),path,isFixerString(addstr))
602  writemissionvars( { 'MISSION_TYPE' : mistype } )
603 
604 def generateWingmanMission(fg, faction,
605  baseprice = float(VS.vsConfig("dynamic_universe","missions.wingman.baseprice","10000")),
606  shipprice = float(VS.vsConfig("dynamic_universe","missions.wingman.shipprice","15000"))
607  ):
608  numships=vsrandom.randrange(1,4)
609  creds=baseprice+shipprice*numships
610  writemissionsavegame("import wingman\newmission = wingman.wingman (%f, '%s', %d, 0)\newmission=0"%(creds, faction, numships))
611  s="A pilot"
612  EorA="a"
613  are="is"
614  if numships > 1:
615  s=str(numships)+" pilots"
616  EorA="e"
617  are="are"
618  writedescription(s+" in the %s faction %s willing to help you out and fight with you as long as you pay %d credits."%(faction, are, creds))
619  writemissionname("Wingmen/Hire_%d_%s_Wingm%sn"%(numships,faction,EorA),[VS.getSystemFile()],0)
620  writemissionvars( { 'MISSION_TYPE' : 'WINGMAN' } )
621 
622 def GetFactionToDefend(thisfaction, fac, cursys):
623  m = fg_util.FGsInSystem ("merchant",cursys)
624  nummerchant=len(m)
625  m+=fg_util.FGsInSystem (thisfaction,cursys)
626  numthisfac=len(m)
627  m+=fg_util.FGsInSystem (fac,cursys)
628  return (m,nummerchant,numthisfac)
629 
630 def contractMissionsFor(fac,minsysaway,maxsysaway):
631  global totalMissionNumber
632  global insysMissionNumber
633  totalMissionNumber=0
634  insysMissionNumber=0
635  facnum=faction_ships.factionToInt(fac)
636  enemies = list(faction_ships.enemies[facnum])
637  script=''
638  cursystem = VS.getSystemFile()
639  thisfaction = VS.GetGalaxyFaction (cursystem)
640  preferredfaction=None
641  if (VS.GetRelation (fac,thisfaction)>=0):
642  preferredfaction=thisfaction#try to stay in this territory
643  l=[]
644  num_wingmen=2
645  num_rescue=2
646  num_defend=1
647  num_idefend=2
648  num_bounty=1
649  num_ibounty=1
650  num_patrol=1
651  num_ipatrol=1
652  num_escort=1
653  num_iescort=1
654  mincount=2
655  usedcats={}
656  plr=VS.getPlayer()
657  if plr:
658  for i in range(plr.numCargo()):
659  usedcats[plr.GetCargoIndex(i).GetCategory()]=1
660  for i in range (minsysaway,maxsysaway+1):
661  for j in getSystemsNAway(cursystem,i,preferredfaction):
662  import dynamic_battle
663  if (i<2 and num_rescue>0):
664  if j[-1] in dynamic_battle.rescuelist:
665  generateRescueMission(j,dynamic_battle.rescuelist[j[-1]])
666  if checkCreatedMission():
667  num_rescue-=1
668 # if (0 and i==0):
669 # generateRescueMission(j,("confed","Shadow","pirates"))
671  nodefend=1
672  for k in l:
673  if (VS.GetRelation(fac,k[1][1])>=0):
674  if ((j[-1]==VS.getSystemFile() and num_idefend<=0) or (j[-1]!=VS.getSystemFile() and num_defend<=0)):
675  mungeFixerPct()
676  debug.debug("Munged")
677  else:
678  nodefend=0
679  generateDefendMission(j,k[1][0],k[1][1],k[0][0],k[0][1])
681  if checkInsysNum():
682  num_idefend-=1
683  if checkMissionNum():
684  num_defend-=1
685  debug.debug("Generated defendX with insys at: "+str(num_idefend)+" and outsys at "+str (num_defend))
686  (m,nummerchant,numthisfac)=GetFactionToDefend(thisfaction, fac, j[-1])
687 
688  if preferredfaction:
689  for kk in faction_ships.enemies[faction_ships.factiondict[thisfaction]]:
691  for mm in fg_util.FGsInSystem(k,j[-1]):
692  if (i==0 or vsrandom.randrange(0,4)==0):#fixme betterthan 4
693  if nodefend and len(m) and vsrandom.random()<.4:
694  if 1:#for i in range(vsrandom.randrange(1,3)):
695  insys=(j[-1]==VS.getSystemFile())
696  if (insys and num_idefend<=0):
697  mungeFixerPct()
698  elif (num_defend<=0 and not insys):
699  mungeFixerPct()
700  rnd=vsrandom.randrange(0,len(m))
701  def_fg=m[rnd]
702  def_fac = "merchant"
703  if rnd>=nummerchant:
704  def_fac= thisfaction
705  if rnd>=numthisfac:
706  def_fac = fac
707  generateDefendMission(j,def_fg,def_fac,mm,k)
709  if checkInsysNum():
710  num_idefend-=1
711  if checkMissionNum():
712  num_defend-=1
713  debug.debug("Generated defendY with insys at: "+str(num_idefend)+" and outsys at "+str (num_defend))
714  nodefend=0
715  elif ((i==0 or vsrandom.random()<.5)):
716  if ((j[-1]==VS.getSystemFile() and num_ibounty<=0) or (j[-1]!=VS.getSystemFile() and num_bounty<=0)):
717  mungeFixerPct()
718  generateBountyMission(j,mm,k)
720  if checkInsysNum():
721  debug.debug(" decrementing INSYS bounty to "+str(num_ibounty))
722  num_ibounty-=1
723  if checkMissionNum():
724  debug.debug(" decrementing bounty to "+str(num_bounty))
725  num_bounty-=1
726 
727 
728 
729  mincount=-2
730  if i==0:
731  mincount=1
732  for k in range(vsrandom.randrange(mincount,4)): ###FIXME: choose a better number than 4.
733  if k<0:
734  k=0
735  rnd=vsrandom.random()
736  if (rnd<.15): # 15% - nothing
737  pass
738  if (rnd<.5 or i==0): # 35% - Patrol Mission
739  if ((j[-1]==VS.getSystemFile() and num_ipatrol<=0) or (j[-1]!=VS.getSystemFile() and num_patrol<=0)):
740  mungeFixerPct()
741  if (vsrandom.randrange(0,2) or j[-1] in faction_ships.fortress_systems):
743  else:
746  if checkInsysNum():
747  num_ipatrol-=1
748  if checkMissionNum():
749  num_patrol-=1
750 
751  else: # 50% - Cargo mission
752  numcargos=vsrandom.randrange(1,25)
753  if numcargos>20:
754  numcargos=20
755  category=''
756  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"):
757  category='Contraband'
758  else:
759  for myiter in range (100):
760  carg=VS.getRandCargo(numcargos,category)
761  category=carg.GetCategory()
762  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)):
763  break
764  if (myiter!=99):
765  category=''
766 # debug.debug("CATEGORY OK "+category)
767  if not category in usedcats:
768  generateCargoMission(j,numcargos,category,fac)
769  usedcats[category]=1
770  numescort = vsrandom.randrange(0,2)
771  if (numescort>len(m)):
772  numescort=len(m)
773  count=0
774  for k in m:
775  if (i==0):
776  if vsrandom.random()<.92:
777  count+=1
778  continue
779  elif (vsrandom.random()<.97):
780  count+=1
781  continue
782  f = "merchant"
783  if count>=nummerchant:
784  f= thisfaction
785  if count>=numthisfac:
786  f = fac
787  if (vsrandom.random()<.25):
788  if (num_wingmen>0):
790  num_wingmen-=1
791  elif (i==0):
792  if (vsrandom.random()<.25):
793  if num_iescort<=0:
794  mungeFixerPct()
795  generateEscortLocal(j,k,f)
797  if checkCreatedMission():
798  num_iescort-=1
799  else:
800  if num_escort<=0:
801  mungeFixerPct()
802  generateEscortMission(j,k,f)
804  if checkCreatedMission():
805  num_escort-=1
806 
807  count+=1
808 
809 def CreateMissions(minsys=0,maxsys=4):
811  if VS.networked():
812  # No generating stuff while networked.
813  return
814  eraseExtras()
815  global plr,basefac
816  plrun=VS.getPlayer()
817  plr=plrun.isPlayerStarship()
818  i = VS.getUnitList()
819  while(i.notDone() and not i.current().isDocked(plrun)):
820  i.advance()
821  if (i.notDone()):
822  basefac=i.current().getFactionName()
823  if (basefac=='neutral'):
824  basefac=VS.GetGalaxyFaction(VS.getSystemFile())
825  contractMissionsFor(basefac,minsys,maxsys)
826  import news
827  news.processNews(plr)