flexible.py 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859
  1. from twisted.internet import reactor
  2. from twisted.internet import task
  3. from twisted.internet import defer
  4. from colorama import Fore, Back, Style
  5. from twisted.python import log
  6. from twisted.internet.task import coiterate
  7. from twisted.internet.defer import gatherResults
  8. from itertools import cycle
  9. import pendulum
  10. from pprint import pformat
  11. from galaxy import GameData, PORT_CLASSES, CLASSES_PORT
  12. class SpinningCursor(object):
  13. """ Spinner class, that handles every so many clicks
  14. s = SpinningCursor(5) # every 5
  15. for x in range(10):
  16. if s.click():
  17. print(s.cycle())
  18. """
  19. def __init__(self, every=10):
  20. self.itercycle = cycle(["/", "-", "\\", "|"])
  21. self.count = 0
  22. self.every = every
  23. def reset(self):
  24. self.itercycle = cycle(["/", "-", "\\", "|"])
  25. self.count = 0
  26. def click(self):
  27. self.count += 1
  28. return self.count % self.every == 0
  29. def cycle(self):
  30. return next(self.itercycle)
  31. def merge(color_string):
  32. """ Given a string of colorama ANSI, merge them if you can. """
  33. return color_string.replace("m\x1b[", ";")
  34. class PlayerInput(object):
  35. """ Player Input
  36. Example:
  37. from flexible import PlayerInput
  38. ask = PlayerInput(self.game)
  39. # abort_blank means, if the input field is blank, abort. Use error_back.
  40. d = ask.prompt("What is your quest?", 40, name="quest", abort_blank=True)
  41. # Display the user's input / but not needed.
  42. d.addCallback(ask.output)
  43. d.addCallback(
  44. lambda ignore: ask.prompt(
  45. "What is your favorite color?", 10, name="color"
  46. )
  47. )
  48. d.addCallback(ask.output)
  49. d.addCallback(
  50. lambda ignore: ask.prompt(
  51. "What is your least favorite number?",
  52. 12,
  53. name="number",
  54. digits=True,
  55. )
  56. )
  57. d.addCallback(ask.output)
  58. def show_values(show):
  59. log.msg(show)
  60. self.queue_game.put(pformat(show).replace("\n", "\n\r") + self.nl)
  61. d.addCallback(lambda ignore: show_values(ask.keep))
  62. d.addCallback(self.welcome_back)
  63. # On error, just return back
  64. d.addErrback(self.welcome_back)
  65. """
  66. def __init__(self, game):
  67. # I think game gives us access to everything we need
  68. self.game = game
  69. self.observer = self.game.observer
  70. self.save = None
  71. self.deferred = None
  72. self.queue_game = game.queue_game
  73. self.keep = {}
  74. # default colors
  75. self.c = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  76. self.cp = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  77. # useful consts
  78. self.r = Style.RESET_ALL
  79. self.nl = "\n\r"
  80. self.bsb = "\b \b"
  81. self.keepalive = None
  82. def color(self, c):
  83. self.c = c
  84. def colorp(self, cp):
  85. self.cp = cp
  86. def alive(self):
  87. log.msg("PlayerInput.alive()")
  88. self.game.queue_player.put(" ")
  89. def prompt(self, user_prompt, limit, **kw):
  90. """ Generate prompt for user input.
  91. Note: This returns deferred.
  92. prompt = text displayed.
  93. limit = # of characters allowed.
  94. default = (text to default to)
  95. keywords:
  96. abort_blank : Abort if they give us blank text.
  97. name : Stores the input in self.keep dict.
  98. digits : Only allow 0-9 to be entered.
  99. """
  100. log.msg("PlayerInput({0}, {1}, {2}".format(user_prompt, limit, kw))
  101. self.limit = limit
  102. self.input = ""
  103. self.kw = kw
  104. assert self.save is None
  105. assert self.keepalive is None
  106. # Note: This clears out the server "keep alive"
  107. self.save = self.observer.save()
  108. self.observer.connect("player", self.get_input)
  109. self.keepalive = task.LoopingCall(self.alive)
  110. self.keepalive.start(30)
  111. # We need to "hide" the game output.
  112. # Otherwise it WITH mess up the user input display.
  113. self.to_player = self.game.to_player
  114. self.game.to_player = False
  115. # Display prompt
  116. # self.queue_game.put(self.r + self.nl + self.c + user_prompt + " " + self.cp)
  117. self.queue_game.put(self.r + self.c + user_prompt + self.r + " " + self.cp)
  118. # Set "Background of prompt"
  119. self.queue_game.put(" " * limit + "\b" * limit)
  120. assert self.deferred is None
  121. d = defer.Deferred()
  122. self.deferred = d
  123. log.msg("Return deferred ...", self.deferred)
  124. return d
  125. def get_input(self, chunk):
  126. """ Data from player (in bytes) """
  127. chunk = chunk.decode("latin-1", "ignore")
  128. for ch in chunk:
  129. if ch == "\b":
  130. if len(self.input) > 0:
  131. self.queue_game.put(self.bsb)
  132. self.input = self.input[0:-1]
  133. else:
  134. self.queue_game.put("\a")
  135. elif ch == "\r":
  136. self.queue_game.put(self.r + self.nl)
  137. log.msg("Restore observer dispatch", self.save)
  138. assert not self.save is None
  139. self.observer.load(self.save)
  140. self.save = None
  141. log.msg("Disable keepalive")
  142. self.keepalive.stop()
  143. self.keepalive = None
  144. line = self.input
  145. self.input = ""
  146. assert not self.deferred is None
  147. self.game.to_player = self.to_player
  148. # If they gave us the keyword name, save the value as that name
  149. if "name" in self.kw:
  150. self.keep[self.kw["name"]] = line
  151. if "abort_blank" in self.kw and self.kw["abort_blank"]:
  152. # Abort on blank input
  153. if line.strip() == "":
  154. # Yes, input is blank, abort.
  155. log.msg("errback, abort_blank")
  156. reactor.callLater(
  157. 0, self.deferred.errback, Exception("abort_blank")
  158. )
  159. self.deferred = None
  160. return
  161. # Ok, use deferred.callback, or reactor.callLater?
  162. # self.deferred.callback(line)
  163. reactor.callLater(0, self.deferred.callback, line)
  164. self.deferred = None
  165. return
  166. elif ch.isprintable():
  167. # Printable, but is it acceptable?
  168. if "digits" in self.kw:
  169. if not ch.isdigit():
  170. self.queue_game.put("\a")
  171. continue
  172. if len(self.input) + 1 <= self.limit:
  173. self.input += ch
  174. self.queue_game.put(ch)
  175. else:
  176. self.queue_game.put("\a")
  177. def output(self, line):
  178. """ A default display of what they just input. """
  179. log.msg("PlayerInput.output({0})".format(line))
  180. self.game.queue_game.put(self.r + "[{0}]".format(line) + self.nl)
  181. return line
  182. import re
  183. # The CIMWarpReport -- is only needed if the json file gets damaged in some way.
  184. # or needs to be reset. The warps should automatically update themselves now.
  185. class CIMWarpReport(object):
  186. def __init__(self, game):
  187. self.game = game
  188. self.queue_game = game.queue_game
  189. self.queue_player = game.queue_player
  190. self.observer = game.observer
  191. # Yes, at this point we would activate
  192. self.prompt = game.buffer
  193. self.save = self.observer.save()
  194. # I actually don't want the player input, but I'll grab it anyway.
  195. self.observer.connect("player", self.player)
  196. self.observer.connect("prompt", self.game_prompt)
  197. self.observer.connect("game-line", self.game_line)
  198. # If we want it, it's here.
  199. self.defer = None
  200. self.to_player = self.game.to_player
  201. # Hide what's happening from the player
  202. self.game.to_player = False
  203. self.queue_player.put("^") # Activate CIM
  204. self.state = 1
  205. # self.warpdata = {}
  206. self.warpcycle = SpinningCursor()
  207. def game_prompt(self, prompt):
  208. if prompt == ": ":
  209. if self.state == 1:
  210. # Ok, then we're ready to request the port report
  211. self.warpcycle.reset()
  212. self.queue_player.put("I")
  213. self.state = 2
  214. elif self.state == 2:
  215. self.queue_player.put("Q")
  216. self.state = 3
  217. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  218. if self.state == 3:
  219. # Ok, time to exit
  220. # exit from this...
  221. self.game.to_player = self.to_player
  222. self.observer.load(self.save)
  223. self.save = None
  224. # self.game.warpdata = self.warpdata
  225. self.queue_game.put("\b \b\r\n")
  226. if not self.defer is None:
  227. self.defer.callback(self.game.gamedata.warps)
  228. self.defer = None
  229. def game_line(self, line):
  230. if line == "" or line == ": ":
  231. return
  232. if line == ": ENDINTERROG":
  233. return
  234. if line.startswith('Command [TL='):
  235. return
  236. # This should be the CIM Report Data -- parse it
  237. if self.warpcycle:
  238. if self.warpcycle.click():
  239. self.queue_game.put("\b" + self.warpcycle.cycle())
  240. work = line.strip()
  241. parts = re.split(r"(?<=\d)\s", work)
  242. parts = [int(x) for x in parts]
  243. sector = parts.pop(0)
  244. # tuples are nicer on memory, and the warpdata map isn't going to be changing.
  245. # self.warpdata[sector] = tuple(parts)
  246. self.game.gamedata.warp_to(sector, *parts)
  247. def __del__(self):
  248. log.msg("CIMWarpReport {0} RIP".format(self))
  249. def whenDone(self):
  250. self.defer = defer.Deferred()
  251. # Call this to chain something after we exit.
  252. return self.defer
  253. def player(self, chunk):
  254. """ Data from player (in bytes). """
  255. chunk = chunk.decode("latin-1", "ignore")
  256. key = chunk.upper()
  257. log.msg("CIMWarpReport.player({0}) : I AM stopping...".format(key))
  258. # Stop the keepalive if we are activating something else
  259. # or leaving...
  260. # self.keepalive.stop()
  261. self.queue_game.put("\b \b\r\n")
  262. if not self.defer is None:
  263. # We have something, so:
  264. self.game.to_player = self.to_player
  265. self.observer.load(self.save)
  266. self.save = None
  267. self.defer.errback(Exception("User Abort"))
  268. self.defer = None
  269. else:
  270. # Still "exit" out.
  271. self.game.to_player = self.to_player
  272. self.observer.load(self.save)
  273. # the CIMPortReport will still be needed.
  274. # We can't get fresh report data (that changes) any other way.
  275. class CIMPortReport(object):
  276. """ Parse data from CIM Port Report
  277. Example:
  278. from flexible import CIMPortReport
  279. report = CIMPortReport(self.game)
  280. d = report.whenDone()
  281. d.addCallback(self.port_report)
  282. d.addErrback(self.welcome_back)
  283. def port_report(self, portdata):
  284. self.portdata = portdata
  285. self.queue_game.put("Loaded {0} records.".format(len(portdata)) + self.nl)
  286. self.welcome_back()
  287. def welcome_back(self,*_):
  288. ... restore keep alive timers, etc.
  289. """
  290. def __init__(self, game):
  291. self.game = game
  292. self.queue_game = game.queue_game
  293. self.queue_player = game.queue_player
  294. self.observer = game.observer
  295. # Yes, at this point we would activate
  296. self.prompt = game.buffer
  297. self.save = self.observer.save()
  298. # I actually don't want the player input, but I'll grab it anyway.
  299. self.observer.connect("player", self.player)
  300. self.observer.connect("prompt", self.game_prompt)
  301. self.observer.connect("game-line", self.game_line)
  302. # If we want it, it's here.
  303. self.defer = None
  304. self.to_player = self.game.to_player
  305. log.msg("to_player (stored)", self.to_player)
  306. # Hide what's happening from the player
  307. self.game.to_player = False
  308. self.queue_player.put("^") # Activate CIM
  309. self.state = 1
  310. # self.portdata = {}
  311. self.portcycle = SpinningCursor()
  312. def game_prompt(self, prompt):
  313. if prompt == ": ":
  314. if self.state == 1:
  315. # Ok, then we're ready to request the port report
  316. self.portcycle.reset()
  317. self.queue_player.put("R")
  318. self.state = 2
  319. elif self.state == 2:
  320. self.queue_player.put("Q")
  321. self.state = 3
  322. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  323. if self.state == 3:
  324. # Ok, time to exit
  325. # exit from this...
  326. self.game.to_player = self.to_player
  327. self.observer.load(self.save)
  328. self.save = None
  329. # self.game.portdata = self.portdata
  330. self.queue_game.put("\b \b\r\n")
  331. if not self.defer is None:
  332. self.defer.callback(self.game.gamedata.ports)
  333. self.defer = None
  334. def game_line(self, line: str):
  335. if line == "" or line == ": ":
  336. return
  337. if line == ": ENDINTERROG":
  338. return
  339. # This should be the CIM Report Data -- parse it
  340. if self.portcycle:
  341. if self.portcycle.click():
  342. self.queue_game.put("\b" + self.portcycle.cycle())
  343. work = line.replace("%", "")
  344. parts = re.split(r"(?<=\d)\s", work)
  345. if len(parts) == 8:
  346. port = int(parts[0].strip())
  347. data = dict()
  348. def portBS(info):
  349. if info[0] == "-":
  350. bs = "B"
  351. else:
  352. bs = "S"
  353. return (bs, int(info[1:].strip()))
  354. data["fuel"] = dict()
  355. data["fuel"]["sale"], data["fuel"]["units"] = portBS(parts[1])
  356. data["fuel"]["pct"] = int(parts[2].strip())
  357. data["org"] = dict()
  358. data["org"]["sale"], data["org"]["units"] = portBS(parts[3])
  359. data["org"]["pct"] = int(parts[4].strip())
  360. data["equ"] = dict()
  361. data["equ"]["sale"], data["equ"]["units"] = portBS(parts[5])
  362. data["equ"]["pct"] = int(parts[6].strip())
  363. # Store what this port is buying/selling
  364. data["port"] = (
  365. data["fuel"]["sale"] + data["org"]["sale"] + data["equ"]["sale"]
  366. )
  367. # Convert BBS/SBB to Class number 1-8
  368. data["class"] = CLASSES_PORT[data["port"]]
  369. self.game.gamedata.set_port(port, data)
  370. # self.portdata[port] = data
  371. else:
  372. log.msg("CIMPortReport:", line, "???")
  373. def __del__(self):
  374. log.msg("CIMPortReport {0} RIP".format(self))
  375. def whenDone(self):
  376. self.defer = defer.Deferred()
  377. # Call this to chain something after we exit.
  378. return self.defer
  379. def player(self, chunk):
  380. """ Data from player (in bytes). """
  381. chunk = chunk.decode("latin-1", "ignore")
  382. key = chunk.upper()
  383. log.msg("CIMPortReport.player({0}) : I AM stopping...".format(key))
  384. # Stop the keepalive if we are activating something else
  385. # or leaving...
  386. # self.keepalive.stop()
  387. self.queue_game.put("\b \b\r\n")
  388. if not self.defer is None:
  389. # We have something, so:
  390. self.game.to_player = self.to_player
  391. self.observer.load(self.save)
  392. self.save = None
  393. self.defer.errback(Exception("User Abort"))
  394. self.defer = None
  395. else:
  396. # Still "exit" out.
  397. self.game.to_player = self.to_player
  398. self.observer.load(self.save)
  399. class ScriptPort(object):
  400. """ Performs the Port script.
  401. This is close to the original.
  402. We don't ask for the port to trade with --
  403. because that information is available to us after "D" (display).
  404. We look at the adjacent sectors, and see if we know any ports.
  405. If the ports are burnt (< 20%), we remove them from the list.
  406. If there's just one, we use it. Otherwise we ask them to choose.
  407. """
  408. def __init__(self, game):
  409. self.game = game
  410. self.queue_game = game.queue_game
  411. self.queue_player = game.queue_player
  412. self.observer = game.observer
  413. self.r = Style.RESET_ALL
  414. self.nl = "\n\r"
  415. self.this_sector = None # Starting sector
  416. self.sector1 = None # Current Sector
  417. self.sector2 = None # Next Sector Stop
  418. self.percent = 5 # Stick with the good default.
  419. self.credits = 0
  420. self.last_credits = None
  421. self.times_left = 0
  422. # Activate
  423. self.prompt = game.buffer
  424. self.save = self.observer.save()
  425. self.observer.connect('player', self.player)
  426. self.observer.connect("prompt", self.game_prompt)
  427. self.observer.connect("game-line", self.game_line)
  428. self.defer = None
  429. self.queue_game.put(
  430. self.nl + "Script based on: Port Pair Trading v2.00" + self.r + self.nl
  431. )
  432. self.possible_sectors = None
  433. self.state = 1
  434. self.queue_player.put("D")
  435. # Original, send 'D' to display current sector.
  436. # We could get the sector number from the self.prompt string -- HOWEVER:
  437. # IF! We send 'D', we can also get the sectors around -- we might not even need to
  438. # prompt for sector to trade with (we could possibly figure it out ourselves).
  439. # [Command [TL=00:00:00]:[967] (?=Help)? : D]
  440. # [<Re-Display>]
  441. # []
  442. # [Sector : 967 in uncharted space.]
  443. # [Planets : (M) Into the Darkness]
  444. # [Warps to Sector(s) : 397 - (562) - (639)]
  445. # []
  446. def whenDone(self):
  447. self.defer = defer.Deferred()
  448. # Call this to chain something after we exit.
  449. return self.defer
  450. def deactivate(self):
  451. self.state = 0
  452. log.msg("ScriptPort.deactivate ({0})".format(self.times_left))
  453. assert(not self.save is None)
  454. self.observer.load(self.save)
  455. self.save = None
  456. if self.defer:
  457. self.defer.callback('done')
  458. self.defer = None
  459. def player(self, chunk: bytes):
  460. # If we receive anything -- ABORT!
  461. self.deactivate()
  462. def game_prompt(self, prompt: str):
  463. log.msg("{0} : {1}".format(self.state, prompt))
  464. if self.state == 3:
  465. log.msg("game_prompt: ", prompt)
  466. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  467. self.state = 4
  468. log.msg("Ok, state 4")
  469. if self.sector2 is None:
  470. # Ok, we need to prompt for this.
  471. self.queue_game.put(self.r + self.nl +
  472. "Which sector to trade with? {0}".format(GameData.port_show_part(self.this_sector, self.game.gamedata.ports[self.this_sector])) +
  473. self.nl + Fore.CYAN)
  474. for i, p in enumerate(self.possible):
  475. self.queue_game.put(" " + str(i + 1) + " : " + GameData.port_show_part(p, self.game.gamedata.ports[p]) + self.nl)
  476. pi = PlayerInput(self.game)
  477. def got_need1(*_):
  478. log.msg("Ok, I have:", pi.keep)
  479. if pi.keep['count'].strip() == '':
  480. self.deactivate()
  481. return
  482. self.times_left = int(pi.keep['count'])
  483. if pi.keep['choice'].strip() == '':
  484. self.deactivate()
  485. return
  486. c = int(pi.keep['choice']) -1
  487. if c < 0 or c >= len(self.possible):
  488. self.deactivate()
  489. return
  490. self.sector2 = self.possible[int(pi.keep['choice']) -1]
  491. # self.queue_game.put(pformat(pi.keep).replace("\n", "\n\r"))
  492. self.state = 5
  493. self.trade()
  494. d = pi.prompt("Choose -=>", 5, name='choice', digits=True)
  495. d.addCallback(lambda ignore: pi.prompt("Times to execute script:", 5, name='count', digits=True))
  496. d.addCallback(got_need1)
  497. else:
  498. # We already have our target port, so...
  499. self.queue_game.put(self.r + self.nl + "Trading from {0} ({1}) to default {2} ({3}).".format(
  500. self.this_sector,
  501. self.game.gamedata.ports[self.this_sector]['port'],
  502. self.sector2, self.game.gamedata.ports[self.sector2]['port']) + self.nl
  503. )
  504. self.queue_game.put(self.r + self.nl + "Trading {0}".format(
  505. self.game.gamedata.port_trade_show(self.this_sector,
  506. self.sector2)
  507. ))
  508. # The code is smart enough now, that this can't happen. :( Drat!
  509. if self.game.gamedata.ports[self.this_sector]['port'] == self.game.gamedata.ports[self.sector2]['port']:
  510. self.queue_game.put("Hey dummy! Look out the window! These ports are the same class!" + nl)
  511. self.deactivate()
  512. return
  513. pi = PlayerInput(self.game)
  514. def got_need2(*_):
  515. if pi.keep['count'].strip() == '':
  516. self.deactivate()
  517. return
  518. self.times_left = int(pi.keep['count'])
  519. log.msg("Ok, I have:", pi.keep)
  520. # self.queue_game.put(pformat(pi.keep).replace("\n", "\n\r"))
  521. self.state = 5
  522. self.trade()
  523. self.queue_game.put(self.r + self.nl)
  524. d = pi.prompt("Times to execute script", 5, name='count')
  525. d.addCallback(got_need2)
  526. elif self.state == 6:
  527. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  528. if self.fixable:
  529. self.queue_game.put("Ok! Let's fix this by going to the other sector..." + self.nl)
  530. log.msg("Fixing...")
  531. if self.this_sector == self.sector1:
  532. self.this_sector = self.sector2
  533. self.queue_player.put("{0}\r".format(self.sector2))
  534. self.state = 5
  535. self.trade()
  536. else:
  537. self.this_sector = self.sector1
  538. self.queue_player.put("{0}\r".format(self.sector1))
  539. self.state = 5
  540. self.trade()
  541. elif self.state == 7:
  542. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  543. # Done
  544. if self.this_sector == self.sector1:
  545. self.this_sector = self.sector2
  546. self.queue_player.put("{0}\r".format(self.sector2))
  547. self.state = 10
  548. else:
  549. self.times_left -= 1
  550. if self.times_left <= 0:
  551. # Ok, exit out
  552. self.deactivate()
  553. return
  554. if self.last_credits is None:
  555. self.last_credits = self.credits
  556. else:
  557. if self.credits <= self.last_credits:
  558. log.msg("We don't seem to be making any money here...")
  559. self.queue_game.put(self.r + self.nl + "We don't seem to be making any money here. I'm stopping!" + self.nl)
  560. self.deactivate()
  561. return
  562. self.this_sector = self.sector1
  563. self.queue_player.put("{0}\r".format(self.sector1))
  564. self.state = 10
  565. elif re.match(r'Your offer \[\d+\] \?', prompt):
  566. if self.fix_offer:
  567. # Make real offer / WHAT?@?!
  568. work = prompt.replace(',', '')
  569. parts = re.split(r"\s+", work)
  570. amount = parts[2]
  571. # Ok, we have the amount, now to figure pct...
  572. if self.sell_pct > 100:
  573. self.sell_pct -= 1
  574. else:
  575. self.sell_pct += 1
  576. price = amount * self.sell_pct // 100
  577. log.msg("start: {0} % {1} price {2}".format(amount, self.sell_perc, price))
  578. if self.sell_pct > 100:
  579. self.sell_pct -= 1
  580. else:
  581. self.sell_pct += 1
  582. self.queue_player.put("{0}\r".format(price))
  583. elif self.state == 8:
  584. # What are we trading
  585. # How many holds of Equipment do you want to buy [75]?
  586. if re.match(r"How many holds of .+ do you want to buy \[\d+\]\?", prompt):
  587. parts = prompt.split()
  588. trade_type = parts[4]
  589. if trade_type == 'Fuel':
  590. if (self.tpc in (5,7)) and (self.opc in (2,3,4,8)):
  591. # Can buy equipment - fuel ore is worthless.
  592. self.queue_player.put("0\r")
  593. return
  594. if (self.tpc in(4,7)) and (self.opc in (1,3,5,8)):
  595. # Can buy organics - fuel ore is worthless.
  596. self.queue_player.put("0\r")
  597. return
  598. if (self.tpc in (4,7,3,5)) and (self.opc in (3,4,5,7)):
  599. # No point in buying fuel ore if it can't be sold.
  600. self.queue_player.put("0\r")
  601. return
  602. elif trade_type == 'Organics':
  603. if (self.tpc in (6,7)) and (self.opc in (2,3,4,8)):
  604. # Can buy equipment - organics is worthless.
  605. self.queue_player.put("0\r")
  606. return
  607. if (self.tpc in (2,4,6,7)) and (self.opc in (2,4,6,7)):
  608. # No point in buying organics if it can't be sold.
  609. self.queue_player.put("0\r")
  610. return
  611. elif trade_type == 'Equipment':
  612. if (self.opc in (1,5,6,7)):
  613. # No point in buying equipment if it can't be sold.
  614. self.queue_player.put("0\r")
  615. return
  616. self.queue_player.put("\r")
  617. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  618. # Done
  619. if self.this_sector == self.sector1:
  620. self.this_sector = self.sector2
  621. self.queue_player.put("{0}\r".format(self.sector2))
  622. self.state = 10
  623. else:
  624. self.times_left -= 1
  625. if self.times_left <= 0:
  626. # Ok, exit out
  627. self.deactivate()
  628. return
  629. if self.last_credits is None:
  630. self.last_credits = self.credits
  631. else:
  632. if self.credits <= self.last_credits:
  633. log.msg("We don't seem to be making any money here...")
  634. self.deactivate()
  635. return
  636. self.this_sector = self.sector1
  637. self.queue_player.put("{0}\r".format(self.sector1))
  638. self.state = 10
  639. def trade(self, *_):
  640. # state 5
  641. log.msg("trade!")
  642. self.queue_player.put("pt") # Port Trade
  643. self.this_port = self.game.gamedata.ports[self.this_sector]
  644. if self.this_sector == self.sector1:
  645. self.other_port = self.game.gamedata.ports[self.sector2]
  646. else:
  647. self.other_port = self.game.gamedata.ports[self.sector1]
  648. # Ok, perform some calculations
  649. self.tpc = self.this_port['class']
  650. self.opc = self.other_port['class']
  651. self.fixable = 0
  652. self.fix_offer = 0
  653. # [ Items Status Trading % of max OnBoard]
  654. # [ ----- ------ ------- -------- -------]
  655. # [Fuel Ore Selling 2573 93% 0]
  656. # [Organics Buying 2960 100% 0]
  657. # [Equipment Buying 1958 86% 0]
  658. # []
  659. # []
  660. # [You have 1,000 credits and 20 empty cargo holds.]
  661. # []
  662. # [We are selling up to 2573. You have 0 in your holds.]
  663. # [How many holds of Fuel Ore do you want to buy [20]? 0]
  664. def game_line(self, line: str):
  665. if line.startswith("You have ") and 'credits and' in line:
  666. parts = line.replace(',', '').split()
  667. credits = int(parts[2])
  668. log.msg("Credits: {0}".format(credits))
  669. self.credits = credits
  670. if self.state == 1:
  671. # First exploration
  672. if line.startswith("Sector :"):
  673. # We have starting sector information
  674. parts = re.split("\s+", line)
  675. self.this_sector = int(parts[2])
  676. # These will be the ones swapped around as we trade back and forth.
  677. self.sector1 = self.this_sector
  678. elif line.startswith("Warps to Sector(s) : "):
  679. # Warps to Sector(s) : 397 - (562) - (639)
  680. _, _, warps = line.partition(':')
  681. warps = warps.replace('-', '').replace('(', '').replace(')', '').strip()
  682. log.msg("Warps: [{0}]".format(warps))
  683. self.warps = [ int(x) for x in re.split("\s+", warps)]
  684. log.msg("Warps: [{0}]".format(self.warps))
  685. self.state = 2
  686. elif self.state == 2:
  687. if line == "":
  688. # Ok, we're done
  689. self.state = 3
  690. # Check to see if we have information on any possible ports
  691. # if hasattr(self.game, 'portdata'):
  692. if True:
  693. if not self.this_sector in self.game.gamedata.ports:
  694. self.state = 0
  695. log.msg("Current sector {0} not in portdata.".format(self.this_sector))
  696. self.queue_game.put(self.r + self.nl + "I can't find the current sector in the portdata." + self.nl)
  697. self.deactivate()
  698. return
  699. else:
  700. # Ok, we are in the portdata
  701. pd = self.game.gamedata.ports[self.this_sector]
  702. if GameData.port_burnt(pd):
  703. log.msg("Current sector {0} port is burnt (<= 20%).".format(self.this_sector))
  704. self.queue_game.put(self.r + self.nl + "Current sector port is burnt out. <= 20%." + self.nl)
  705. self.deactivate()
  706. return
  707. possible = [ x for x in self.warps if x in self.game.gamedata.ports ]
  708. log.msg("Possible:", possible)
  709. # BUG: Sometimes links to another sector, don't link back!
  710. # This causes the game to plot a course / autopilot.
  711. # if hasattr(self.game, 'warpdata'):
  712. if True:
  713. # Great! verify that those warps link back to us!
  714. possible = [ x for x in possible if x in self.game.gamedata.warps and self.this_sector in self.game.gamedata.warps[x]]
  715. if len(possible) == 0:
  716. self.state = 0
  717. self.queue_game.put(self.r + self.nl + "I don't see any ports in [{0}].".format(self.warps) + self.nl)
  718. self.deactivate()
  719. return
  720. possible = [ x for x in possible if not GameData.port_burnt(self.game.gamedata.ports[x]) ]
  721. log.msg("Possible:", possible)
  722. if len(possible) == 0:
  723. self.state = 0
  724. self.queue_game.put(self.r + self.nl + "I don't see any unburnt ports in [{0}].".format(self.warps) + self.nl)
  725. self.deactivate()
  726. return
  727. possible = [ x for x in possible if GameData.port_trading(self.game.gamedata.ports[self.this_sector]['port'], self.game.gamedata.ports[x]['port'])]
  728. self.possible = possible
  729. if len(possible) == 0:
  730. self.state = 0
  731. self.queue_game.put(self.r + self.nl + "I don't see any possible port trades in [{0}].".format(self.warps) + self.nl)
  732. self.deactivate()
  733. return
  734. elif len(possible) == 1:
  735. # Ok! there's only one!
  736. self.sector2 = possible[0]
  737. # Display possible ports:
  738. # spos = [ str(x) for x in possible]
  739. # self.queue_game.put(self.r + self.nl + self.nl.join(spos) + self.nl)
  740. # At state 3, we only get a prompt.
  741. return
  742. else:
  743. self.state = 0
  744. log.msg("We don't have any portdata!")
  745. self.queue_game.put(self.r + self.nl + "I have no portdata. Please run CIM Port Report." + self.nl)
  746. self.deactivate()
  747. return
  748. elif self.state == 5:
  749. if "-----" in line:
  750. self.state = 6
  751. elif self.state == 6:
  752. if "We are buying up to" in line:
  753. # Sell
  754. self.state = 7
  755. self.queue_player.put("\r")
  756. self.sell_perc = 100 + self.percent
  757. if "We are selling up to" in line:
  758. # Buy
  759. self.state = 8
  760. self.sell_perc = 100 - self.percent
  761. if line.startswith('Fuel Ore') or line.startswith('Organics') or line.startswith('Equipment'):
  762. work = line.replace('Fuel Ore', 'Fuel')
  763. parts = re.split(r"\s+", work)
  764. # log.msg(parts)
  765. # Equipment, Selling xxx x% xxx
  766. if parts[-1] != '0' and parts[2] != '0' and parts[1] != 'Buying':
  767. log.msg("We have a problem -- they aren't buying what we have in stock!")
  768. stuff = line[0] # F O or E.
  769. if stuff == 'F':
  770. spos = 0
  771. elif stuff == 'O':
  772. spos = 1
  773. else:
  774. spos = 2
  775. other = self.other_port['port']
  776. if other[spos] == 'B':
  777. self.fixable = 1
  778. if "You don't have anything they want" in line:
  779. # Neither! DRAT!
  780. if not self.fixable:
  781. self.deactivate()
  782. return
  783. if "We're not interested." in line:
  784. log.msg("Try, try again. :(")
  785. self.state = 5
  786. self.trade()
  787. elif self.state == 7:
  788. # Haggle Sell
  789. if "We'll buy them for" in line or "Our final offer" in line:
  790. if "Our final offer" in line:
  791. self.sell_perc -= 1
  792. parts = line.replace(',', '').split()
  793. start_price = int(parts[4])
  794. price = start_price * self.sell_perc // 100
  795. log.msg("start: {0} % {1} price {2}".format(start_price, self.sell_perc, price))
  796. self.sell_perc -= 1
  797. self.queue_player.put("{0}\r".format(price))
  798. if "We are selling up to" in line:
  799. # Buy
  800. self.state = 8
  801. self.sell_perc = 100 - self.percent
  802. if "We're not interested." in line:
  803. log.msg("Try, try again. :(")
  804. self.state = 5
  805. self.trade()
  806. if "WHAT?!@!? you must be crazy!" in line:
  807. log.msg("fix offer")
  808. self.fix_offer = 1
  809. if "So, you think I'm as stupid as you look?" in line:
  810. log.msg("fix offer")
  811. self.fix_offer = 1
  812. if "Quit playing around, you're wasting my time!" in line:
  813. log.msg("fix offer")
  814. self.fix_offer = 1
  815. elif self.state == 8:
  816. # Haggle Buy
  817. if "We'll sell them for" in line or "Our final offer" in line:
  818. if "Our final offer" in line:
  819. self.sell_perc += 1
  820. parts = line.replace(',', '').split()
  821. start_price = int(parts[4])
  822. price = start_price * self.sell_perc // 100
  823. log.msg("start: {0} % {1} price {2}".format(start_price, self.sell_perc, price))
  824. self.sell_perc += 1
  825. self.queue_player.put("{0}\r".format(price))
  826. if "We're not interested." in line:
  827. log.msg("Try, try again. :(")
  828. self.state = 5
  829. self.trade()
  830. elif self.state == 10:
  831. if "Sector : " in line:
  832. # Trade
  833. self.state = 5
  834. reactor.callLater(0, self.trade, 0)
  835. # self.trade()
  836. # elif self.state == 3:
  837. # log.msg("At state 3 [{0}]".format(line))
  838. # self.queue_game.put("At state 3.")
  839. # self.deactivate()
  840. # return
  841. class ScriptExplore(object):
  842. """ Script Explore v1.00
  843. By: David Thielemann
  844. WARNINGS:
  845. We assume the player has a Holo-Scanner!
  846. We assume the player has lots o turns, or unlimited turns!
  847. We assume the player is aware we run infinitly until we can't find new sectors to move to!
  848. """
  849. def __init__(self, game):
  850. self.game = game
  851. self.queue_game = game.queue_game
  852. self.queue_player = game.queue_player
  853. self.observer = game.observer
  854. self.r = Style.RESET_ALL
  855. self.nl = "\n\r"
  856. # Our Stuff, Not our pants!
  857. self.dense = [] # We did a density, store that info.
  858. self.clear = [] # Warps that we know are clear.
  859. self.didDense = False
  860. self.didHolo = False
  861. self.highsector = 0 # Selected Sector to move to next!
  862. self.highwarp = 0 # Selected Sector's Warp Count!
  863. self.stacksector = set() # Set of sectors that we have not picked but are unexplored... even though we did a holo!
  864. self.oneMoveSector = False
  865. self.times = 0
  866. self.maxtimes = 0
  867. # Activate
  868. self.prompt = game.buffer
  869. self.save = self.observer.save()
  870. self.observer.connect('player', self.player)
  871. self.observer.connect("prompt", self.game_prompt)
  872. self.observer.connect("game-line", self.game_line)
  873. self.defer = None
  874. self.send2player("Explorer v1.01")
  875. # How many times we going to go today?
  876. ask = PlayerInput(self.game)
  877. def settimes(*_):
  878. times = int(ask.keep['times'].strip())
  879. log.msg("settimes got '{0}'".format(times))
  880. if times == None:
  881. self.deactivate()
  882. else:
  883. self.times = times
  884. self.maxtimes = times
  885. self.send2game("D")
  886. self.state = 1
  887. d = ask.prompt("How many sectors would you lick to explode?", 5, name="times", digits=True)
  888. #d.addCallback(ask.output)
  889. #d.addCallback(lambda ignore: self.settimes(ask.keep))
  890. d.addCallback(settimes)
  891. def whenDone(self):
  892. self.defer = defer.Deferred()
  893. # Call this to chain something after we exit.
  894. return self.defer
  895. def deactivate(self):
  896. self.state = 0
  897. log.msg("ScriptExplore.deactivate()")
  898. assert(not self.save is None)
  899. self.observer.load(self.save)
  900. self.save = None
  901. if self.defer:
  902. self.defer.callback('done')
  903. self.defer = None
  904. def player(self, chunk: bytes):
  905. # If we receive anything -- ABORT!
  906. self.deactivate()
  907. def send2game(self, txt):
  908. self.queue_player.put(txt)
  909. def send2player(self, txt):
  910. self.queue_game.put(
  911. self.nl + txt + self.r + self.nl
  912. )
  913. def resetStuff(self):
  914. self.didDense = False
  915. self.didHolo = False
  916. self.dense = []
  917. self.clear = []
  918. self.highwarp = 0
  919. self.highsector = 0
  920. log.msg("ScriptExplore.resetStuff()")
  921. def game_prompt(self, prompt: str):
  922. log.msg("{0} : {1}".format(self.state, prompt))
  923. if self.state == 2:
  924. if "Select (H)olo Scan or (D)ensity Scan or (Q)uit" in prompt:
  925. if not self.didDense:
  926. self.send2game("D")
  927. self.didDense = True
  928. self.state += 1
  929. else:
  930. log.msg("Possibly no Holo Scanner Installed.")
  931. self.deactivate()
  932. if self.state == 5:
  933. log.msg("dense is {0} sectors big".format(len(self.dense)))
  934. if "Select (H)olo Scan or (D)ensity Scan or (Q)uit" in prompt:
  935. if not self.didHolo:
  936. self.send2game("H")
  937. self.didHolo = True
  938. self.state += 1
  939. else:
  940. log.msg("FATAL: No Holo Scanner Installed!")
  941. self.deactivate()
  942. def game_line(self, line: str):
  943. log.msg("{0} | {1}".format(self.state, line))
  944. if "Mine Control" in line: # If we don't have a Holo-Scanner and we attempted to do a Holo-scan, abort
  945. self.deactivate()
  946. if self.state == 1:
  947. # Density Scan, (Assume we have the Holo-Scanner)
  948. self.send2game("S")
  949. if "Relative Density Scan" in line:
  950. self.state = 3
  951. elif "You don't have a long range scanner." in line:
  952. log.msg("FATAL: No Long Range Scanner Installed!")
  953. self.deactivate()
  954. elif "Long Range Scan" in line:
  955. self.state += 1
  956. elif self.state == 4:
  957. # Holo Scan, (Assume we have the Holo-Scanner)
  958. self.send2game("S")
  959. if "You don't have a long range scanner." in line:
  960. log.msg("FATAL: No Long Range Scanner Installed!")
  961. self.deactivate()
  962. elif "Long Range Scan" in line:
  963. self.state += 1
  964. elif self.state == 3:
  965. if line.startswith("Sector"):
  966. work = line.replace(':', '').replace(')', '').replace('%', '').replace('==>', '')
  967. work = re.split(r"\s+", work)
  968. # 'Sector', '8192', '0', 'Warps', '4', 'NavHaz', '0', 'Anom', 'No'
  969. # 'Sector', '(', '8192)', '0', 'Warps', '4', 'NavHaz', '0', 'Anom', 'No'
  970. # New Sector?
  971. if work[1] == '(':
  972. temp1 = True
  973. else:
  974. temp1 = False
  975. # Yes new sector! So we will add it!
  976. if temp1:
  977. # Switch Anom into bool state
  978. if(work[9] == 'No'):
  979. temp = False
  980. else:
  981. temp = True
  982. self.dense.append( {'sector': int(work[2]), 'density': int(work[3]), 'warps': int(work[5]), 'navhaz': int(work[7]), 'anom': temp} )
  983. # {'sector': 8192, 'density': 0, 'warps': 4, 'navhaz': 0, 'anom': False}
  984. elif line == "":
  985. self.state += 1
  986. elif self.state == 6:
  987. # Begin Processing our data we got from density scan and find highest warp count in what sectors
  988. # Remove sectors with one warp
  989. # Do we have a new place to go? (That is also worth going to)
  990. if not self.dense: # Dense contains no new sectors, abort
  991. log.msg("No New Sectors Found!")
  992. self.send2player("Find a new area for me to search in!")
  993. # Attempt to resolve no new sectors!
  994. if self.stacksector: # Do we have anything on the stack? (If so we set highsector with one of the randomly selected sectors)
  995. self.highsector = self.stacksector.pop()
  996. self.deactivate()
  997. elif self.dense: # Dense does contain at least 1 new sector, continue on
  998. t = [] # Pre-Test to check if there are just a bunch of 1 warp sectors
  999. for d in self.dense:
  1000. if d['warps'] != 1:
  1001. t.append(d['sector'])
  1002. if not t: # If there are no sectors with more that 1 warp, abort
  1003. log.msg("No Sectors Found except one move sector!")
  1004. self.send2player("Find a new area for me to look at!")
  1005. # Attempt to resolve no new sectors with more than 1 warp!
  1006. if self.stacksector: # Do we have anything on the stack? (If so we set highsector with one of the randomly selected sectors)
  1007. self.highsector = self.stacksector.pop()
  1008. self.deactivate()
  1009. # Is the sector safe to go into?
  1010. for d in self.dense:
  1011. if not d['anom']:
  1012. # Sector does not contain a Anomoly
  1013. if d['navhaz'] == 0:
  1014. # Sector does not contain Hazards
  1015. if d['density'] == 0 or d['density'] == 1 or d['density'] == 100 or d['density'] == 101:
  1016. # Sector does contain empty space / a beacon / a port / or a beacon and port
  1017. if d['warps'] > 1:
  1018. # If Sector is worth checking out?
  1019. self.clear.append(d['sector'])
  1020. if self.clear: # We have sector(s) we can move to!
  1021. log.msg("Clear Sectors: {0}".format(len(self.clear)))
  1022. # This was state 5 but why can't we reduce number of states? ( Yeah let's kick California and New York out of the US, oh wrong states :P )
  1023. # Sort to find greatest warp count
  1024. for c in self.clear:
  1025. for d in self.dense:
  1026. if d['sector'] == c:
  1027. if d['warps'] > self.highwarp:
  1028. self.highwarp = d['warps']
  1029. self.highsector = c
  1030. elif d['warps'] == self.highwarp:
  1031. if c > self.highsector:
  1032. self.highsector = c
  1033. if self.highwarp and self.highsector:
  1034. log.msg("Sector: {0:5d} Warps: {1}".format(self.highsector, self.highwarp))
  1035. self.state += 1
  1036. elif self.state == 7:
  1037. # Add the dense scan of unknown sectors onto the stack of sectors, only save the ones we think are clear... for now.
  1038. for c in self.clear:
  1039. self.stacksector.add(c)
  1040. # Remove the sector we are just about to go to, we use discard so if the sector does not exist we don't throw a error!
  1041. self.stacksector.discard(self.highsector)
  1042. # Ok we know the sector we want to go to now let's move it!
  1043. self.send2game("m{0}\n\r".format(self.highsector))
  1044. # Reset Variables for fresh data
  1045. self.resetStuff()
  1046. self.state = 1
  1047. # Warning! Yes we can and will eat all the turns! :P
  1048. self.times -= 1
  1049. if self.times <= 0:
  1050. self.send2player("Completed {0}".format(self.maxtimes))
  1051. log.msg("Completed {0}".format(self.maxtimes))
  1052. self.deactivate()
  1053. class ScriptSpace(object):
  1054. """ Space Exploration script.
  1055. Send "SD", verify paths are clear.
  1056. Find nearest unknown. Sector + CR.
  1057. Save "shortest path from to" information.
  1058. At 'Engage the Autopilot', Send "S" (Single Step)
  1059. At '[Stop in this sector', Send "SD", verify path is clear.
  1060. Send "SH" (glean sector/port information along the way.)
  1061. Send "N" (Next)!
  1062. Send "SD" / Verify clear.
  1063. Send "SH"
  1064. Repeat for Next closest.
  1065. """
  1066. def __init__(self, game):
  1067. self.game = game
  1068. self.queue_game = game.queue_game
  1069. self.queue_player = game.queue_player
  1070. self.observer = game.observer
  1071. self.r = Style.RESET_ALL
  1072. self.nl = "\n\r"
  1073. self.this_sector = None # Starting sector
  1074. self.target_sector = None # Sector going to
  1075. self.path = []
  1076. self.times_left = 0 # How many times to look for target
  1077. self.density = dict() # Results of density scan. (Just the numbers)
  1078. # Activate
  1079. self.prompt = game.buffer
  1080. self.save = self.observer.save()
  1081. self.observer.connect('player', self.player)
  1082. self.observer.connect("prompt", self.game_prompt)
  1083. self.observer.connect("game-line", self.game_line)
  1084. self.defer = None
  1085. self.queue_game.put(
  1086. self.nl + "Bugz (like space), is big." + self.r + self.nl
  1087. )
  1088. self.state = 1
  1089. self.queue_player.put("SD")
  1090. # Get current density scan + also get the current sector.
  1091. # [Command [TL=00:00:00]:[XXXX] (?=Help)? : D]
  1092. def whenDone(self):
  1093. self.defer = defer.Deferred()
  1094. # Call this to chain something after we exit.
  1095. return self.defer
  1096. def deactivate(self):
  1097. self.state = 0
  1098. log.msg("ScriptPort.deactivate ({0})".format(self.times_left))
  1099. assert(not self.save is None)
  1100. self.observer.load(self.save)
  1101. self.save = None
  1102. if self.defer:
  1103. self.defer.callback('done')
  1104. self.defer = None
  1105. def player(self, chunk: bytes):
  1106. # If we receive anything -- ABORT!
  1107. self.deactivate()
  1108. def unknown_search(self, starting_sector):
  1109. seen = set()
  1110. possible = set()
  1111. possible.add(int(starting_sector))
  1112. done = False
  1113. while not done:
  1114. next_possible = set()
  1115. for s in possible:
  1116. p = self.game.gamedata.get_warps(s)
  1117. if p is not None:
  1118. for pos in p:
  1119. if pos not in seen:
  1120. next_possible.add(pos)
  1121. else:
  1122. log.msg("unknown found:", s)
  1123. self.unknown = s
  1124. done = True
  1125. break
  1126. seen.add(s)
  1127. if self.unknown is None:
  1128. log.msg("possible:", next_possible)
  1129. possible = next_possible
  1130. yield
  1131. def find_unknown(self, starting_sector):
  1132. log.msg("find_unknown( {0})".format(starting_sector))
  1133. d = defer.Deferred()
  1134. # Process things
  1135. self.unknown = None
  1136. c = coiterate(self.unknown_search(starting_sector))
  1137. c.addCallback(lambda unknown: d.callback(self.unknown))
  1138. return d
  1139. def show_unknown(self, sector):
  1140. if sector is None:
  1141. self.deactivate()
  1142. return
  1143. log.msg("Travel to {0}...".format(sector))
  1144. self.queue_player.put("{0}\r".format(sector))
  1145. def game_prompt(self, prompt: str):
  1146. log.msg("{0} : {1}".format(self.state, prompt))
  1147. if self.state == 3:
  1148. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  1149. # this_sector code isn't working -- so! Get sector from prompt
  1150. self.state = 4
  1151. _, _, sector = prompt.partition(']:[')
  1152. sector, _, _ = sector.partition(']')
  1153. self.this_sector = int(sector)
  1154. # Ok, we're done with Density Scan, and we're back at the command prompt
  1155. log.msg("Go find the nearest unknown...")
  1156. d = self.find_unknown(sector)
  1157. d.addCallback(self.show_unknown)
  1158. elif self.state == 6:
  1159. # Engage the autopilot?
  1160. if prompt.startswith('Engage the Autopilot? (Y/N/Single step/Express) [Y]'):
  1161. self.state = 7
  1162. sector = self.path.pop(0)
  1163. if sector in self.density:
  1164. if self.density[sector] in (0, 100):
  1165. # Ok, looks safe!
  1166. self.queue_player.put("S")
  1167. self.this_sector = sector
  1168. else:
  1169. log.msg("FATAL: Density for {0} is {1}".format(sector, self.density[sector]))
  1170. self.deactivate()
  1171. return
  1172. else:
  1173. log.msg("{0} not in density scan? (how's that possible?)".format(sector))
  1174. self.deactivate()
  1175. return
  1176. elif self.state == 7:
  1177. # Ok, we're in a new sector (single stepping through space)
  1178. # update density scan
  1179. if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?'):
  1180. self.queue_player.put("SD")
  1181. self.state = 8
  1182. elif self.state == 10:
  1183. # Because we're here
  1184. if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?'):
  1185. self.queue_player.put("SH")
  1186. self.state = 11
  1187. elif self.state == 11:
  1188. if prompt.startswith('Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?'):
  1189. # Ok, is the density scan clear?
  1190. sector = self.path.pop(0)
  1191. if sector in self.density:
  1192. if self.density[sector] in (0, 100):
  1193. # Ok, looks safe
  1194. self.queue_player.put("N")
  1195. self.state = 7
  1196. self.this_sector = sector
  1197. else:
  1198. log.msg("FATAL: Density for {0} is {1}".format(sector, self.density[sector]))
  1199. self.deactivate()
  1200. return
  1201. else:
  1202. log.msg("{0} not in density scane? (how's that possible...)".format(sector))
  1203. self.deactivate()
  1204. return
  1205. def next_unknown(self, sector):
  1206. log.msg("Unknown is :", sector)
  1207. self.deactivate()
  1208. def game_line(self, line: str):
  1209. log.msg("line {0} : {1}".format(self.state, line))
  1210. if line.startswith('Sector : '):
  1211. work = line.strip()
  1212. parts = re.split(r"\s+", work)
  1213. self.this_sector = int(parts[2])
  1214. log.msg("game_line sector", self.this_sector)
  1215. elif line.startswith("Command [TL=]"):
  1216. # Ok, get the current sector from this
  1217. _, _, sector = line.partition("]:[")
  1218. sector, _, _ = sector.partition("]")
  1219. self.this_sector = int(sector)
  1220. log.msg("current sector: {0}".format(self.this_sector))
  1221. elif line.startswith('Warps to Sector(s) :'):
  1222. # Warps to Sector(s) : 5468
  1223. _, _, work = line.partition(':')
  1224. work = work.strip().replace('(', '').replace(')', '').replace(' - ', ' ')
  1225. parts = [ int(x) for x in work.split(' ')]
  1226. self.path = list(parts)
  1227. if self.state in (1, 8):
  1228. if 'Relative Density Scan' in line:
  1229. # Start Density Scan
  1230. self.state += 1
  1231. self.density = {}
  1232. elif self.state in (2, 9):
  1233. if line == '':
  1234. # End of Density Scan
  1235. self.state += 1
  1236. log.msg("Density: {0}".format(self.density))
  1237. # self.deactivate()
  1238. elif line.startswith('Sector'):
  1239. # Parse Density Scan values
  1240. work = line.replace('(', '').replace(')', '').replace(':', '').replace('%', '').replace(',', '')
  1241. parts = re.split(r'\s+', work)
  1242. log.msg("Sector", parts)
  1243. sector = int(parts[1])
  1244. self.density[sector] = int(parts[3])
  1245. if parts[7] != '0':
  1246. log.msg("NavHaz {0} : {1}".format(parts[7], work))
  1247. self.density[sector] += 99
  1248. if parts[9] != 'No':
  1249. log.msg("Anom {0} : {1}".format(parts[9], work))
  1250. self.density[sector] += 990
  1251. elif self.state == 4:
  1252. # Looking for shortest path message / warp info
  1253. # Or possibly, "We're here!"
  1254. if line.startswith('Sector :') and str(self.unknown) in line:
  1255. # Ok, I'd guess that we're already there!
  1256. # Try it again!
  1257. self.queue_player.put("SD")
  1258. self.state = 1
  1259. if line.startswith('The shortest path'):
  1260. self.state = 5
  1261. elif self.state == 5:
  1262. # This is the warps line
  1263. # Can this be multiple lines?
  1264. if line == "":
  1265. self.state = 6
  1266. else:
  1267. work = line.replace("(", "").replace(")", "").replace(">", "").strip()
  1268. self.path = [int(x) for x in work.split()]
  1269. log.msg("Path:", self.path)
  1270. # Verify
  1271. current = self.path.pop(0)
  1272. if current != self.this_sector:
  1273. log.msg("Failed: {0} != {1}".format(current, self.this_sector))
  1274. self.deactivate()
  1275. return
  1276. elif self.state == 7:
  1277. if self.unknown == self.this_sector:
  1278. # We have arrived!
  1279. log.msg("We're here!")
  1280. self.deactivate()
  1281. from boxes import Boxes
  1282. class ProxyMenu(object):
  1283. """ Display ProxyMenu
  1284. Example:
  1285. from flexible import ProxyMenu
  1286. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  1287. menu = ProxyMenu(self.game)
  1288. """
  1289. def __init__(self, game):
  1290. self.nl = "\n\r"
  1291. self.c = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  1292. self.r = Style.RESET_ALL
  1293. self.c1 = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  1294. self.c2 = merge(Style.NORMAL + Fore.CYAN + Back.BLUE)
  1295. # self.portdata = None
  1296. self.game = game
  1297. self.queue_game = game.queue_game
  1298. self.observer = game.observer
  1299. # Am I using self or game? (I think I want game, not self.)
  1300. # if hasattr(self.game, "portdata"):
  1301. # self.portdata = self.game.portdata
  1302. # else:
  1303. # self.portdata = {}
  1304. # if hasattr(self.game, 'warpdata'):
  1305. # self.warpdata = self.game.warpdata
  1306. # else:
  1307. # self.warpdata = {}
  1308. if hasattr(self.game, 'trade_report'):
  1309. self.trade_report = self.game.trade_report
  1310. else:
  1311. self.trade_report = []
  1312. # Yes, at this point we would activate
  1313. self.prompt = game.buffer
  1314. self.save = self.observer.save()
  1315. self.observer.connect("player", self.player)
  1316. # If we want it, it's here.
  1317. self.defer = None
  1318. self.keepalive = task.LoopingCall(self.awake)
  1319. self.keepalive.start(30)
  1320. self.menu()
  1321. def __del__(self):
  1322. log.msg("ProxyMenu {0} RIP".format(self))
  1323. def whenDone(self):
  1324. self.defer = defer.Deferred()
  1325. # Call this to chain something after we exit.
  1326. return self.defer
  1327. def menu(self):
  1328. box = Boxes(30, color=self.c)
  1329. self.queue_game.put(box.top())
  1330. self.queue_game.put(
  1331. box.row(self.c + "{0:^30}".format("TradeWars Proxy Active")))
  1332. self.queue_game.put(box.middle())
  1333. def menu_item(ch: str, desc: str):
  1334. row = self.c1 + " {0} {1}- {2}{3:25}".format(ch, self.c2, self.c1, desc)
  1335. self.queue_game.put(box.row(row))
  1336. # self.queue_game.put(
  1337. # " " + self.c1 + ch + self.c2 + " - " + self.c1 + desc + self.nl
  1338. # )
  1339. menu_item("D", "Display Report again")
  1340. # menu_item("Q", "Quest")
  1341. # if hasattr(self.game, 'portdata'):
  1342. # ports = len(self.game.portdata)
  1343. # else:
  1344. # ports = '?'
  1345. menu_item("P", "Port CIM Report ({0})".format(len(self.game.gamedata.ports)))
  1346. # if hasattr(self.game, 'warpdata'):
  1347. # warps = len(self.game.warpdata)
  1348. # else:
  1349. # warps = '?'
  1350. menu_item("W", "Warp CIM Report ({0})".format(len(self.game.gamedata.warps)))
  1351. menu_item("T", "Trading Report")
  1352. menu_item("S", "Scripts")
  1353. menu_item("X", "eXit")
  1354. self.queue_game.put(box.bottom())
  1355. self.queue_game.put(" " + self.c + "-=>" + self.r + " ")
  1356. def awake(self):
  1357. log.msg("ProxyMenu.awake()")
  1358. self.game.queue_player.put(" ")
  1359. def port_report(self, portdata: dict):
  1360. # self.portdata = portdata
  1361. # self.game.portdata = portdata
  1362. self.queue_game.put("Loaded {0} ports.".format(len(portdata)) + self.nl)
  1363. self.welcome_back()
  1364. def warp_report(self, warpdata: dict):
  1365. # self.warpdata = warpdata
  1366. # self.game.warpdata = warpdata
  1367. self.queue_game.put("Loaded {0} sectors.".format(len(warpdata)) + self.nl)
  1368. self.welcome_back()
  1369. def make_trade_report(self):
  1370. log.msg("make_trade_report()")
  1371. ok_trades = []
  1372. best_trades = []
  1373. # for sector, pd in self.game.gamedata.ports.items():
  1374. for sector in sorted(self.game.gamedata.ports.keys()):
  1375. pd = self.game.gamedata.ports[sector]
  1376. if not GameData.port_burnt(pd):
  1377. pc = pd['class']
  1378. # Ok, let's look into it.
  1379. if not sector in self.game.gamedata.warps:
  1380. continue
  1381. warps = self.game.gamedata.warps[sector]
  1382. for w in warps:
  1383. # Verify that we have that warp's info, and that the sector is in it.
  1384. # (We can get back from it)
  1385. if w in self.game.gamedata.warps and sector in self.game.gamedata.warps[w]:
  1386. # Ok, we can get there -- and get back!
  1387. if w > sector and w in self.game.gamedata.ports and not GameData.port_burnt(self.game.gamedata.ports[w]):
  1388. # it is > and has a port.
  1389. wd = self.game.gamedata.ports[w]
  1390. wc = wd['class']
  1391. # 1: "BBS",
  1392. # 2: "BSB",
  1393. # 3: "SBB",
  1394. # 4: "SSB",
  1395. # 5: "SBS",
  1396. # 6: "BSS",
  1397. # 7: "SSS",
  1398. # 8: "BBB",
  1399. if pc in (1,5) and wc in (2,4):
  1400. best_trades.append(self.game.gamedata.port_trade_show(sector, w))
  1401. # best_trades.append( "{0:5} -=- {1:5}".format(sector, w))
  1402. elif pc in (2,4) and wc in (1,5):
  1403. best_trades.append(self.game.gamedata.port_trade_show(sector, w))
  1404. # best_trades.append( "{0:5} -=- {1:5}".format(sector, w))
  1405. elif GameData.port_trading(pd['port'], self.game.gamedata.ports[w]['port']):
  1406. # ok_trades.append( "{0:5} -=- {1:5}".format(sector,w))
  1407. ok_trades.append(self.game.gamedata.port_trade_show(sector, w))
  1408. yield
  1409. self.trade_report.append("Best Trades: (org/equ)")
  1410. self.trade_report.extend(best_trades)
  1411. self.trade_report.append("Ok Trades:")
  1412. self.trade_report.extend(ok_trades)
  1413. # self.queue_game.put("BEST TRADES:" + self.nl + self.nl.join(best_trades) + self.nl)
  1414. # self.queue_game.put("OK TRADES:" + self.nl + self.nl.join(ok_trades) + self.nl)
  1415. def show_trade_report(self, *_):
  1416. self.game.trade_report = self.trade_report
  1417. for t in self.trade_report:
  1418. self.queue_game.put(t + self.nl)
  1419. self.welcome_back()
  1420. def player(self, chunk: bytes):
  1421. """ Data from player (in bytes). """
  1422. chunk = chunk.decode("latin-1", "ignore")
  1423. key = chunk.upper()
  1424. log.msg("ProxyMenu.player({0})".format(key))
  1425. # Stop the keepalive if we are activating something else
  1426. # or leaving...
  1427. self.keepalive.stop()
  1428. if key == "T":
  1429. self.queue_game.put(self.c + key + self.r + self.nl)
  1430. # Trade Report
  1431. # do we have enough information to do this?
  1432. # if not hasattr(self.game, 'portdata') and not hasattr(self.game, 'warpdata'):
  1433. # self.queue_game.put("Missing portdata and warpdata." + self.nl)
  1434. # elif not hasattr(self.game, 'portdata'):
  1435. # self.queue_game.put("Missing portdata." + self.nl)
  1436. # elif not hasattr(self.game, 'warpdata'):
  1437. # self.queue_game.put("Missing warpdata." + self.nl)
  1438. # else:
  1439. if True:
  1440. # Yes, so let's start!
  1441. self.trade_report = []
  1442. d = coiterate(self.make_trade_report())
  1443. d.addCallback(self.show_trade_report)
  1444. return
  1445. elif key == "P":
  1446. self.queue_game.put(self.c + key + self.r + self.nl)
  1447. # Activate CIM Port Report
  1448. report = CIMPortReport(self.game)
  1449. d = report.whenDone()
  1450. d.addCallback(self.port_report)
  1451. d.addErrback(self.welcome_back)
  1452. return
  1453. elif key == "W":
  1454. self.queue_game.put(self.c + key + self.r + self.nl)
  1455. # Activate CIM Warp Report
  1456. report = CIMWarpReport(self.game)
  1457. d = report.whenDone()
  1458. d.addCallback(self.warp_report)
  1459. d.addErrback(self.welcome_back)
  1460. return
  1461. elif key == "S":
  1462. self.queue_game.put(self.c + key + self.r + self.nl)
  1463. # Scripts
  1464. self.activate_scripts_menu()
  1465. return
  1466. elif key == "D":
  1467. self.queue_game.put(self.c + key + self.r + self.nl)
  1468. # (Re) Display Trade Report
  1469. if self.trade_report:
  1470. for t in self.trade_report:
  1471. self.queue_game.put(t + self.nl)
  1472. else:
  1473. self.queue_game.put("Missing trade_report." + self.nl)
  1474. # self.queue_game.put(pformat(self.portdata).replace("\n", "\n\r") + self.nl)
  1475. # self.queue_game.put(pformat(self.warpdata).replace("\n", "\n\r") + self.nl)
  1476. elif key == "Q":
  1477. self.queue_game.put(self.c + key + self.r + self.nl)
  1478. # This is an example of chaining PlayerInput prompt calls.
  1479. ask = PlayerInput(self.game)
  1480. d = ask.prompt("What is your quest?", 40, name="quest", abort_blank=True)
  1481. # Display the user's input
  1482. d.addCallback(ask.output)
  1483. d.addCallback(
  1484. lambda ignore: ask.prompt(
  1485. "What is your favorite color?", 10, name="color"
  1486. )
  1487. )
  1488. d.addCallback(ask.output)
  1489. d.addCallback(
  1490. lambda ignore: ask.prompt(
  1491. "What is the meaning of the squirrel?",
  1492. 12,
  1493. name="squirrel",
  1494. digits=True,
  1495. )
  1496. )
  1497. d.addCallback(ask.output)
  1498. def show_values(show):
  1499. log.msg(show)
  1500. self.queue_game.put(pformat(show).replace("\n", "\n\r") + self.nl)
  1501. d.addCallback(lambda ignore: show_values(ask.keep))
  1502. d.addCallback(self.welcome_back)
  1503. # On error, just return back
  1504. # This doesn't seem to be getting called.
  1505. # d.addErrback(lambda ignore: self.welcome_back)
  1506. d.addErrback(self.welcome_back)
  1507. return
  1508. elif key == "X":
  1509. self.queue_game.put(self.c + key + self.r + self.nl)
  1510. self.queue_game.put(Boxes.alert("Proxy done.", base="green"))
  1511. # self.queue_game.put("Proxy done." + self.nl)
  1512. self.observer.load(self.save)
  1513. self.save = None
  1514. # It isn't running (NOW), so don't try to stop it.
  1515. # self.keepalive.stop()
  1516. self.keepalive = None
  1517. # Ok, this is a HORRIBLE idea, because the prompt might be
  1518. # outdated.
  1519. # self.queue_game.put(self.prompt)
  1520. self.prompt = None
  1521. # Possibly: Send '\r' to re-display the prompt
  1522. # instead of displaying the original one.
  1523. self.game.queue_player.put("d")
  1524. # Were we asked to do something when we were done here?
  1525. if self.defer:
  1526. reactor.CallLater(0, self.defer.callback)
  1527. # self.defer.callback()
  1528. self.defer = None
  1529. return
  1530. self.keepalive.start(30, True)
  1531. self.menu()
  1532. def activate_scripts_menu(self):
  1533. self.observer.disconnect("player", self.player)
  1534. self.observer.connect("player", self.scripts_player)
  1535. self.scripts_menu()
  1536. def deactivate_scripts_menu(self, *_):
  1537. self.observer.disconnect("player", self.scripts_player)
  1538. self.observer.connect("player", self.player)
  1539. self.welcome_back()
  1540. def scripts_menu(self, *_):
  1541. c1 = merge(Style.BRIGHT + Fore.CYAN)
  1542. c2 = merge(Style.NORMAL + Fore.CYAN)
  1543. box = Boxes(40, color=c1)
  1544. self.queue_game.put(box.top())
  1545. self.queue_game.put(box.row(c1 + "{0:^40}".format("Scripts")))
  1546. self.queue_game.put(box.middle())
  1547. def menu_item(ch, desc):
  1548. row = " {0}{1} {2}-{3} {4:35}".format(c1, ch, c2, c1, desc)
  1549. # self.queue_game.put(
  1550. # " " + c1 + ch + c2 + " - " + c1 + desc + self.nl
  1551. # )
  1552. self.queue_game.put(box.row(row))
  1553. menu_item("1", "Ports (Trades between two sectors)")
  1554. menu_item("2", "Explore (Strange new sectors)")
  1555. menu_item("3", "Space... the final frontier...")
  1556. menu_item("X", "eXit")
  1557. self.queue_game.put(box.bottom())
  1558. self.queue_game.put(" " + c1 + "-=>" + self.r + " ")
  1559. def scripts_player(self, chunk: bytes):
  1560. """ Data from player (in bytes). """
  1561. chunk = chunk.decode("latin-1", "ignore")
  1562. key = chunk.upper()
  1563. if key == '1':
  1564. self.queue_game.put(self.c + key + self.r + self.nl)
  1565. # Activate this magical event here
  1566. ports = ScriptPort(self.game)
  1567. d = ports.whenDone()
  1568. # d.addCallback(self.scripts_menu)
  1569. # d.addErrback(self.scripts_menu)
  1570. d.addCallback(self.deactivate_scripts_menu)
  1571. d.addErrback(self.deactivate_scripts_menu)
  1572. return
  1573. elif key == '2':
  1574. self.queue_game.put(self.c + key + self.r + self.nl)
  1575. explore = ScriptExplore(self.game)
  1576. d = explore.whenDone()
  1577. d.addCallback(self.deactivate_scripts_menu)
  1578. d.addErrback(self.deactivate_scripts_menu)
  1579. return
  1580. elif key == '3':
  1581. self.queue_game.put(self.c + key + self.r + self.nl)
  1582. space = ScriptSpace(self.game)
  1583. d = space.whenDone()
  1584. d.addCallback(self.deactivate_scripts_menu)
  1585. d.addErrback(self.deactivate_scripts_menu)
  1586. return
  1587. elif key == 'X':
  1588. self.queue_game.put(self.c + key + self.r + self.nl)
  1589. self.deactivate_scripts_menu()
  1590. return
  1591. else:
  1592. self.queue_game.put(self.c + "?" + self.r + self.nl)
  1593. self.scripts_menu()
  1594. def welcome_back(self, *_):
  1595. log.msg("welcome_back")
  1596. self.keepalive.start(30, True)
  1597. self.menu()