flexible.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  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 itertools import cycle
  7. import pendulum
  8. from pprint import pformat
  9. def merge(color_string):
  10. """ Given a string of colorama ANSI, merge them if you can. """
  11. return color_string.replace("m\x1b[", ";")
  12. class PlayerInput(object):
  13. """ Player Input
  14. Example:
  15. from flexible import PlayerInput
  16. ask = PlayerInput(self.game)
  17. # abort_blank means, if the input field is blank, abort. Use error_back.
  18. d = ask.prompt("What is your quest?", 40, name="quest", abort_blank=True)
  19. # Display the user's input / but not needed.
  20. d.addCallback(ask.output)
  21. d.addCallback(
  22. lambda ignore: ask.prompt(
  23. "What is your favorite color?", 10, name="color"
  24. )
  25. )
  26. d.addCallback(ask.output)
  27. d.addCallback(
  28. lambda ignore: ask.prompt(
  29. "What is your least favorite number?",
  30. 12,
  31. name="number",
  32. digits=True,
  33. )
  34. )
  35. d.addCallback(ask.output)
  36. def show_values(show):
  37. log.msg(show)
  38. self.queue_game.put(pformat(show).replace("\n", "\n\r") + self.nl)
  39. d.addCallback(lambda ignore: show_values(ask.keep))
  40. d.addCallback(self.welcome_back)
  41. # On error, just return back
  42. d.addErrback(self.welcome_back)
  43. """
  44. def __init__(self, game):
  45. # I think game gives us access to everything we need
  46. self.game = game
  47. self.observer = self.game.observer
  48. self.save = None
  49. self.deferred = None
  50. self.queue_game = game.queue_game
  51. self.keep = {}
  52. # default colors
  53. self.c = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  54. self.cp = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  55. # useful consts
  56. self.r = Style.RESET_ALL
  57. self.nl = "\n\r"
  58. self.bsb = "\b \b"
  59. self.keepalive = None
  60. def color(self, c):
  61. self.c = c
  62. def colorp(self, cp):
  63. self.cp = cp
  64. def alive(self):
  65. log.msg("PlayerInput.alive()")
  66. self.game.queue_player.put(" ")
  67. def prompt(self, user_prompt, limit, **kw):
  68. """ Generate prompt for user input.
  69. Note: This returns deferred.
  70. prompt = text displayed.
  71. limit = # of characters allowed.
  72. default = (text to default to)
  73. keywords:
  74. abort_blank : Abort if they give us blank text.
  75. name : Stores the input in self.keep dict.
  76. digits : Only allow 0-9 to be entered.
  77. """
  78. log.msg("PlayerInput({0}, {1}, {2}".format(user_prompt, limit, kw))
  79. self.limit = limit
  80. self.input = ""
  81. self.kw = kw
  82. assert self.save is None
  83. assert self.keepalive is None
  84. # Note: This clears out the server "keep alive"
  85. self.save = self.observer.save()
  86. self.observer.connect("player", self.get_input)
  87. self.keepalive = task.LoopingCall(self.alive)
  88. self.keepalive.start(30)
  89. # We need to "hide" the game output.
  90. # Otherwise it WITH mess up the user input display.
  91. self.to_player = self.game.to_player
  92. self.game.to_player = False
  93. # Display prompt
  94. # self.queue_game.put(self.r + self.nl + self.c + user_prompt + " " + self.cp)
  95. self.queue_game.put(self.r + self.c + user_prompt + self.r + " " + self.cp)
  96. # Set "Background of prompt"
  97. self.queue_game.put(" " * limit + "\b" * limit)
  98. assert self.deferred is None
  99. d = defer.Deferred()
  100. self.deferred = d
  101. log.msg("Return deferred ...", self.deferred)
  102. return d
  103. def get_input(self, chunk):
  104. """ Data from player (in bytes) """
  105. chunk = chunk.decode("utf-8", "ignore")
  106. for ch in chunk:
  107. if ch == "\b":
  108. if len(self.input) > 0:
  109. self.queue_game.put(self.bsb)
  110. self.input = self.input[0:-1]
  111. else:
  112. self.queue_game.put("\a")
  113. elif ch == "\r":
  114. self.queue_game.put(self.r + self.nl)
  115. log.msg("Restore observer dispatch", self.save)
  116. assert not self.save is None
  117. self.observer.load(self.save)
  118. self.save = None
  119. log.msg("Disable keepalive")
  120. self.keepalive.stop()
  121. self.keepalive = None
  122. line = self.input
  123. self.input = ""
  124. assert not self.deferred is None
  125. self.game.to_player = self.to_player
  126. # If they gave us the keyword name, save the value as that name
  127. if "name" in self.kw:
  128. self.keep[self.kw["name"]] = line
  129. if "abort_blank" in self.kw and self.kw["abort_blank"]:
  130. # Abort on blank input
  131. if line.strip() == "":
  132. # Yes, input is blank, abort.
  133. log.msg("errback, abort_blank")
  134. reactor.callLater(
  135. 0, self.deferred.errback, Exception("abort_blank")
  136. )
  137. self.deferred = None
  138. return
  139. # Ok, use deferred.callback, or reactor.callLater?
  140. # self.deferred.callback(line)
  141. reactor.callLater(0, self.deferred.callback, line)
  142. self.deferred = None
  143. return
  144. elif ch.isprintable():
  145. # Printable, but is it acceptable?
  146. if "digits" in self.kw:
  147. if not ch.isdigit():
  148. self.queue_game.put("\a")
  149. continue
  150. if len(self.input) + 1 <= self.limit:
  151. self.input += ch
  152. self.queue_game.put(ch)
  153. else:
  154. self.queue_game.put("\a")
  155. def output(self, line):
  156. """ A default display of what they just input. """
  157. log.msg("PlayerInput.output({0})".format(line))
  158. self.game.queue_game.put(self.r + "[{0}]".format(line) + self.nl)
  159. return line
  160. PORT_CLASSES = {
  161. 1: "BBS",
  162. 2: "BSB",
  163. 3: "SBB",
  164. 4: "SSB",
  165. 5: "SBS",
  166. 6: "BSS",
  167. 7: "SSS",
  168. 8: "BBB",
  169. }
  170. CLASSES_PORT = {v: k for k, v in PORT_CLASSES.items()}
  171. import re
  172. class CIMPortReport(object):
  173. """ Parse data from CIM Port Report
  174. Example:
  175. from flexible import CIMPortReport
  176. report = CIMPortReport(self.game)
  177. d = report.whenDone()
  178. d.addCallback(self.port_report)
  179. d.addErrback(self.welcome_back)
  180. def port_report(self, portdata):
  181. self.portdata = portdata
  182. self.queue_game.put("Loaded {0} records.".format(len(portdata)) + self.nl)
  183. self.welcome_back()
  184. def welcome_back(self,*_):
  185. ... restore keep alive timers, etc.
  186. """
  187. def __init__(self, game):
  188. self.game = game
  189. self.queue_game = game.queue_game
  190. self.queue_player = game.queue_player
  191. self.observer = game.observer
  192. # Yes, at this point we would activate
  193. self.prompt = game.buffer
  194. self.save = self.observer.save()
  195. # I actually don't want the player input, but I'll grab it anyway.
  196. self.observer.connect("player", self.player)
  197. self.observer.connect("prompt", self.game_prompt)
  198. self.observer.connect("game-line", self.game_line)
  199. # If we want it, it's here.
  200. self.defer = None
  201. self.to_player = self.game.to_player
  202. log.msg("to_player (stored)", self.to_player)
  203. # Hide what's happening from the player
  204. self.game.to_player = False
  205. self.queue_player.put("^") # Activate CIM
  206. self.state = 1
  207. self.portdata = {}
  208. self.portcycle = cycle(["/", "-", "\\", "|"])
  209. def game_prompt(self, prompt):
  210. if prompt == ": ":
  211. if self.state == 1:
  212. # Ok, then we're ready to request the port report
  213. self.portcycle = cycle(["/", "-", "\\", "|"])
  214. self.queue_player.put("R")
  215. self.state = 2
  216. elif self.state == 2:
  217. self.queue_player.put("Q")
  218. self.state = 3
  219. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  220. if self.state == 3:
  221. # Ok, time to exit
  222. # exit from this...
  223. self.game.to_player = self.to_player
  224. self.observer.load(self.save)
  225. self.save = None
  226. self.game.portdata = self.portdata
  227. self.queue_game.put("\b \b\r\n")
  228. if not self.defer is None:
  229. self.defer.callback(self.portdata)
  230. self.defer = None
  231. def game_line(self, line):
  232. if line == "" or line == ": ":
  233. return
  234. if line == ": ENDINTERROG":
  235. return
  236. # This should be the CIM Report Data -- parse it
  237. if self.portcycle:
  238. if len(self.portdata) % 10 == 0:
  239. self.queue_game.put("\b" + next(self.portcycle))
  240. work = line.replace("%", "")
  241. parts = re.split(r"(?<=\d)\s", work)
  242. if len(parts) == 8:
  243. port = int(parts[0].strip())
  244. data = dict()
  245. def portBS(info):
  246. if info[0] == "-":
  247. bs = "B"
  248. else:
  249. bs = "S"
  250. return (bs, int(info[1:].strip()))
  251. data["fuel"] = dict()
  252. data["fuel"]["sale"], data["fuel"]["units"] = portBS(parts[1])
  253. data["fuel"]["pct"] = int(parts[2].strip())
  254. data["org"] = dict()
  255. data["org"]["sale"], data["org"]["units"] = portBS(parts[3])
  256. data["org"]["pct"] = int(parts[4].strip())
  257. data["equ"] = dict()
  258. data["equ"]["sale"], data["equ"]["units"] = portBS(parts[5])
  259. data["equ"]["pct"] = int(parts[6].strip())
  260. # Store what this port is buying/selling
  261. data["port"] = (
  262. data["fuel"]["sale"] + data["org"]["sale"] + data["equ"]["sale"]
  263. )
  264. # Convert BBS/SBB to Class number 1-8
  265. data["class"] = CLASSES_PORT[data["port"]]
  266. self.portdata[port] = data
  267. else:
  268. log.msg("CIMPortReport:", line, "???")
  269. def __del__(self):
  270. log.msg("CIMPortReport {0} RIP".format(self))
  271. def whenDone(self):
  272. self.defer = defer.Deferred()
  273. # Call this to chain something after we exit.
  274. return self.defer
  275. def player(self, chunk):
  276. """ Data from player (in bytes). """
  277. chunk = chunk.decode("utf-8", "ignore")
  278. key = chunk.upper()
  279. log.msg("CIMPortReport.player({0}) : I AM stopping...".format(key))
  280. # Stop the keepalive if we are activating something else
  281. # or leaving...
  282. # self.keepalive.stop()
  283. self.queue_game.put("\b \b\r\n")
  284. if not self.defer is None:
  285. # We have something, so:
  286. self.game.to_player = self.to_player
  287. self.observer.load(self.save)
  288. self.save = None
  289. self.defer.errback(Exception("User Abort"))
  290. self.defer = None
  291. else:
  292. # Still "exit" out.
  293. self.game.to_player = self.to_player
  294. self.observer.load(self.save)
  295. class ScriptPort(object):
  296. """ Performs the Port script. """
  297. def __init__(self, game):
  298. self.game = game
  299. self.queue_game = game.queue_game
  300. self.queue_player = game.queue_player
  301. self.observer = game.observer
  302. self.r = Style.RESET_ALL
  303. self.nl = "\n\r"
  304. self.this_sector = None # Starting sector
  305. self.sector1 = None # Current Sector
  306. self.sector2 = None # Next Sector Stop
  307. self.percent = 5 # Stick with the good default.
  308. self.credits = 0
  309. # Activate
  310. self.prompt = game.buffer
  311. self.save = self.observer.save()
  312. self.observer.connect('player', self.player)
  313. self.observer.connect("prompt", self.game_prompt)
  314. self.observer.connect("game-line", self.game_line)
  315. self.defer = None
  316. self.queue_game.put(
  317. self.nl + "Script based on: Port Pair Trading v2.00" + self.r + self.nl
  318. )
  319. self.possible_sectors = None
  320. self.state = 1
  321. self.queue_player.put("D")
  322. # Original, send 'D' to display current sector.
  323. # We could get the sector number from the self.prompt string -- HOWEVER:
  324. # IF! We send 'D', we can also get the sectors around -- we might not even need to
  325. # prompt for sector to trade with (we could possibly figure it out ourselves).
  326. # [Command [TL=00:00:00]:[967] (?=Help)? : D]
  327. # [<Re-Display>]
  328. # []
  329. # [Sector : 967 in uncharted space.]
  330. # [Planets : (M) Into the Darkness]
  331. # [Warps to Sector(s) : 397 - (562) - (639)]
  332. # []
  333. def whenDone(self):
  334. self.defer = defer.Deferred()
  335. # Call this to chain something after we exit.
  336. return self.defer
  337. def deactivate(self):
  338. self.state = 0
  339. log.msg("ScriptPort.deactivate")
  340. assert(not self.save is None)
  341. self.observer.load(self.save)
  342. self.save = None
  343. if self.defer:
  344. self.defer.callback('done')
  345. self.defer = None
  346. def player(self, chunk: bytes):
  347. # If we receive anything -- ABORT!
  348. self.deactivate()
  349. def game_prompt(self, prompt: str):
  350. log.msg("{0} : {1}".format(self.state, prompt))
  351. if self.state == 3:
  352. log.msg("game_prompt: ", prompt)
  353. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  354. self.state = 4
  355. log.msg("Ok, state 4")
  356. if self.sector2 is None:
  357. # Ok, we need to prompt for this.
  358. self.queue_game.put(self.r + self.nl + "Which sector to trade with?" + self.nl + Fore.CYAN)
  359. for i, p in enumerate(self.possible):
  360. self.queue_game.put(" " + str(i + 1) + " : " + str(p) + self.nl)
  361. pi = PlayerInput(self.game)
  362. def got_need1(*_):
  363. log.msg("Ok, I have:", pi.keep)
  364. if pi.keep['count'].strip() == '':
  365. self.deactivate()
  366. return
  367. self.times_left = int(pi.keep['count'])
  368. if pi.keep['choice'].strip() == '':
  369. self.deactivate()
  370. return
  371. c = int(pi.keep['choice']) -1
  372. if c < 0 or c >= len(self.possible):
  373. self.deactivate()
  374. return
  375. self.sector2 = self.possible[int(pi.keep['choice']) -1]
  376. # self.queue_game.put(pformat(pi.keep).replace("\n", "\n\r"))
  377. self.state = 5
  378. self.trade()
  379. d = pi.prompt("Choose -=>", 5, name='choice', digits=True)
  380. d.addCallback(lambda ignore: pi.prompt("Times to execute script:", 5, name='count', digits=True))
  381. d.addCallback(got_need1)
  382. else:
  383. # We already have our target port, so...
  384. pi = PlayerInput(self.game)
  385. def got_need2(*_):
  386. if pi.keep['count'].strip() == '':
  387. self.deactivate()
  388. return
  389. self.times_left = int(pi.keep['count'])
  390. log.msg("Ok, I have:", pi.keep)
  391. self.queue_game.put(pformat(pi.keep).replace("\n", "\n\r"))
  392. self.state = 5
  393. self.trade()
  394. self.queue_game.put(self.r + self.nl)
  395. d = pi.prompt("Times to execute script", 5, name='count')
  396. d.addCallback(got_need2)
  397. elif self.state == 7:
  398. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  399. # Done
  400. if self.this_sector == self.sector1:
  401. self.this_sector = self.sector2
  402. self.queue_player.put("{0}\r".format(self.sector2))
  403. self.state = 10
  404. else:
  405. self.times_left -= 1
  406. if self.times_left <= 0:
  407. # Ok, exit out
  408. self.deactivate()
  409. return
  410. self.this_sector = self.sector1
  411. self.queue_player.put("{0}\r".format(self.sector1))
  412. self.state = 10
  413. elif self.state == 8:
  414. # What are we trading
  415. if "How many holds of" in prompt:
  416. parts = prompt.split()
  417. trade_type = parts[4]
  418. if trade_type == 'Fuel':
  419. if (self.tpc in (5,7)) and (self.opc in (2,3,4,8)):
  420. # Can buy equipment - fuel ore is worthless.
  421. self.queue_player.put("0\r")
  422. return
  423. if (self.tpc in(4,7)) and (self.opc in (1,3,5,8)):
  424. # Can buy organics - fuel ore is worthless.
  425. self.queue_player.put("0\r")
  426. return
  427. if (self.tpc in (4,7,3,5)) and (self.opc in (3,4,5,7)):
  428. # No point in buying fuel ore if it can't be sold.
  429. self.queue_player.put("0\r")
  430. return
  431. elif trade_type == 'Organics':
  432. if (self.tpc in (6,7)) and (self.opc in (2,3,4,8)):
  433. # Can buy equipment - organics is worthless.
  434. self.queue_player.put("0\r")
  435. return
  436. if (self.tpc in (2,4,6,7)) and (self.opc in (2,4,6,7)):
  437. # No point in buying organics if it can't be sold.
  438. self.queue_player.put("0\r")
  439. return
  440. elif trade_type == 'Equipment':
  441. if (self.opc in (1,5,6,7)):
  442. # No point in buying equipment if it can't be sold.
  443. self.queue_player.put("0\r")
  444. return
  445. self.queue_player.put("\r")
  446. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  447. # Done
  448. if self.this_sector == self.sector1:
  449. self.this_sector = self.sector2
  450. self.queue_player.put("{0}\r".format(self.sector2))
  451. self.state = 10
  452. else:
  453. self.times_left -= 1
  454. if self.times_left <= 0:
  455. # Ok, exit out
  456. self.deactivate()
  457. return
  458. self.this_sector = self.sector1
  459. self.queue_player.put("{0}\r".format(self.sector1))
  460. self.state = 10
  461. def trade(self, *_):
  462. # state 5
  463. log.msg("trade!")
  464. self.queue_player.put("pt") # Port Trade
  465. self.this_port = self.game.portdata[self.this_sector]
  466. if self.this_sector == self.sector1:
  467. self.other_port = self.game.portdata[self.sector2]
  468. else:
  469. self.other_port = self.game.portdata[self.sector1]
  470. # Ok, perform some calculations
  471. self.tpc = self.this_port['class']
  472. self.opc = self.other_port['class']
  473. # [ Items Status Trading % of max OnBoard]
  474. # [ ----- ------ ------- -------- -------]
  475. # [Fuel Ore Selling 2573 93% 0]
  476. # [Organics Buying 2960 100% 0]
  477. # [Equipment Buying 1958 86% 0]
  478. # []
  479. # []
  480. # [You have 1,000 credits and 20 empty cargo holds.]
  481. # []
  482. # [We are selling up to 2573. You have 0 in your holds.]
  483. # [How many holds of Fuel Ore do you want to buy [20]? 0]
  484. pass
  485. def game_line(self, line: str):
  486. if self.state == 1:
  487. # First exploration
  488. if line.startswith("Sector :"):
  489. # We have starting sector information
  490. parts = re.split("\s+", line)
  491. self.this_sector = int(parts[2])
  492. # These will be the ones swapped around as we trade back and forth.
  493. self.sector1 = self.this_sector
  494. elif line.startswith("Warps to Sector(s) : "):
  495. # Warps to Sector(s) : 397 - (562) - (639)
  496. _, _, warps = line.partition(':')
  497. warps = warps.replace('-', '').replace('(', '').replace(')', '').strip()
  498. log.msg("Warps: [{0}]".format(warps))
  499. self.warps = [ int(x) for x in re.split("\s+", warps)]
  500. log.msg("Warps: [{0}]".format(self.warps))
  501. self.state = 2
  502. elif self.state == 2:
  503. if line == "":
  504. # Ok, we're done
  505. self.state = 3
  506. # Check to see if we have information on any possible ports
  507. if hasattr(self.game, 'portdata'):
  508. if not self.this_sector in self.game.portdata:
  509. self.state = 0
  510. log.msg("Current sector {0} not in portdata.".format(self.this_sector))
  511. self.queue_game.put(self.r + self.nl + "I can't find the current sector in the portdata." + self.nl)
  512. self.deactivate()
  513. return
  514. else:
  515. # Ok, we are in the portdata
  516. def port_burnt(port):
  517. if port['equ']['pct'] <= 20 or port['fuel']['pct'] <= 20 or port['org']['pct'] <= 20:
  518. return True
  519. return False
  520. pd = self.game.portdata[self.this_sector]
  521. if port_burnt(pd):
  522. log.msg("Current sector {0} port is burnt (<= 20%).".format(self.this_sector))
  523. self.queue_game.put(self.r + self.nl + "Current sector port is burnt out. <= 20%." + self.nl)
  524. self.deactivate()
  525. return
  526. possible = [ x for x in self.warps if x in self.game.portdata ]
  527. log.msg("Ppossible:", possible)
  528. if len(possible) == 0:
  529. self.state = 0
  530. self.queue_game.put(self.r + self.nl + "I don't see any ports in [{0}].".format(self.warps) + self.nl)
  531. self.deactivate()
  532. return
  533. possible = [ x for x in possible if not port_burnt(self.game.portdata[x]) ]
  534. log.msg("Possible:", possible)
  535. self.possible = possible
  536. if len(possible) == 0:
  537. self.state = 0
  538. self.queue_game.put(self.r + self.nl + "I don't see any unburnt ports in [{0}].".format(self.warps) + self.nl)
  539. self.deactivate()
  540. return
  541. elif len(possible) == 1:
  542. # Ok! there's only one!
  543. self.sector2 = possible[0]
  544. # Display possible ports:
  545. # spos = [ str(x) for x in possible]
  546. # self.queue_game.put(self.r + self.nl + self.nl.join(spos) + self.nl)
  547. # At state 3, we only get a prompt.
  548. return
  549. else:
  550. self.state = 0
  551. log.msg("We don't have any portdata!")
  552. self.queue_game.put(self.r + self.nl + "I have no portdata. Please run CIM Port Report." + self.nl)
  553. self.deactivate()
  554. return
  555. elif self.state == 5:
  556. if "-----" in line:
  557. self.state = 6
  558. elif self.state == 6:
  559. if "We are buying up to" in line:
  560. # Sell
  561. self.state = 7
  562. self.queue_player.put("\r")
  563. self.sell_perc = 100 + self.percent
  564. if "We are selling up to" in line:
  565. # Buy
  566. self.state = 8
  567. self.sell_perc = 100 - self.percent
  568. if "You don't have anything they want" in line:
  569. # Neither! DRAT!
  570. self.deactivate()
  571. return
  572. if "We're not interested." in line:
  573. log.msg("Try, try again. :(")
  574. self.state = 5
  575. self.trade()
  576. elif self.state == 7:
  577. # Haggle Sell
  578. if "We'll buy them for" in line or "Our final offer" in line:
  579. if "Our final offer" in line:
  580. self.sell_perc -= 1
  581. parts = line.replace(',', '').split()
  582. start_price = int(parts[4])
  583. price = start_price * self.sell_perc // 100
  584. log.msg("start: {0} % {1} price {2}".format(start_price, self.sell_perc, price))
  585. self.sell_perc -= 1
  586. self.queue_player.put("{0}\r".format(price))
  587. if "We are selling up to" in line:
  588. # Buy
  589. self.state = 8
  590. self.sell_perc = 100 - self.percent
  591. if line.startswith("You have ") and 'credits and' in line:
  592. parts = line.replace(',', '').split()
  593. credits = int(parts[2])
  594. if self.credits == 0:
  595. self.credits = credits
  596. else:
  597. if credits <= self.credits:
  598. log.msg("We don't appear to be making any money here {0}.".format(credits))
  599. self.deactivate()
  600. return
  601. elif self.state == 8:
  602. # Haggle Buy
  603. if "We'll sell them for" in line or "Our final offer" in line:
  604. if "Our final offer" in line:
  605. self.sell_perc += 1
  606. parts = line.replace(',', '').split()
  607. start_price = int(parts[4])
  608. price = start_price * self.sell_perc // 100
  609. log.msg("start: {0} % {1} price {2}".format(start_price, self.sell_perc, price))
  610. self.sell_perc += 1
  611. self.queue_player.put("{0}\r".format(price))
  612. if "We're not interested." in line:
  613. log.msg("Try, try again. :(")
  614. self.state = 5
  615. self.trade()
  616. elif self.state == 10:
  617. if "Sector : " in line:
  618. # Trade
  619. self.state = 5
  620. reactor.callLater(0, self.trade, 0)
  621. # self.trade()
  622. # elif self.state == 3:
  623. # log.msg("At state 3 [{0}]".format(line))
  624. # self.queue_game.put("At state 3.")
  625. # self.deactivate()
  626. # return
  627. class ProxyMenu(object):
  628. """ Display ProxyMenu
  629. Example:
  630. from flexible import ProxyMenu
  631. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  632. menu = ProxyMenu(self.game)
  633. """
  634. def __init__(self, game):
  635. self.nl = "\n\r"
  636. self.c = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  637. self.r = Style.RESET_ALL
  638. self.c1 = merge(Style.BRIGHT + Fore.BLUE)
  639. self.c2 = merge(Style.NORMAL + Fore.CYAN)
  640. self.portdata = None
  641. self.game = game
  642. self.queue_game = game.queue_game
  643. self.observer = game.observer
  644. if hasattr(self.game, "portdata"):
  645. self.portdata = self.game.portdata
  646. else:
  647. self.portdata = {}
  648. # Yes, at this point we would activate
  649. self.prompt = game.buffer
  650. self.save = self.observer.save()
  651. self.observer.connect("player", self.player)
  652. # If we want it, it's here.
  653. self.defer = None
  654. self.keepalive = task.LoopingCall(self.awake)
  655. self.keepalive.start(30)
  656. self.menu()
  657. def __del__(self):
  658. log.msg("ProxyMenu {0} RIP".format(self))
  659. def whenDone(self):
  660. self.defer = defer.Deferred()
  661. # Call this to chain something after we exit.
  662. return self.defer
  663. def menu(self):
  664. self.queue_game.put(
  665. self.nl + self.c + "TradeWars Proxy active." + self.r + self.nl
  666. )
  667. def menu_item(ch: str, desc: str):
  668. self.queue_game.put(
  669. " " + self.c1 + ch + self.c2 + " - " + self.c1 + desc + self.nl
  670. )
  671. menu_item("D", "Diagnostics")
  672. menu_item("Q", "Quest")
  673. menu_item("T", "Display current Time")
  674. menu_item("P", "Port CIM Report")
  675. menu_item("S", "Scripts")
  676. menu_item("X", "eXit")
  677. self.queue_game.put(" " + self.c + "-=>" + self.r + " ")
  678. def awake(self):
  679. log.msg("ProxyMenu.awake()")
  680. self.game.queue_player.put(" ")
  681. def port_report(self, portdata: dict):
  682. self.portdata = portdata
  683. self.queue_game.put("Loaded {0} records.".format(len(portdata)) + self.nl)
  684. self.welcome_back()
  685. def player(self, chunk: bytes):
  686. """ Data from player (in bytes). """
  687. chunk = chunk.decode("utf-8", "ignore")
  688. key = chunk.upper()
  689. log.msg("ProxyMenu.player({0})".format(key))
  690. # Stop the keepalive if we are activating something else
  691. # or leaving...
  692. self.keepalive.stop()
  693. if key == "T":
  694. self.queue_game.put(self.c + key + self.r + self.nl)
  695. # perform T option
  696. now = pendulum.now()
  697. self.queue_game.put(
  698. self.nl + self.c1 + "Current time " + now.to_datetime_string() + self.nl
  699. )
  700. elif key == "P":
  701. self.queue_game.put(self.c + key + self.r + self.nl)
  702. # Activate CIM Port Report
  703. report = CIMPortReport(self.game)
  704. d = report.whenDone()
  705. d.addCallback(self.port_report)
  706. d.addErrback(self.welcome_back)
  707. return
  708. elif key == "S":
  709. self.queue_game.put(self.c + key + self.r + self.nl)
  710. self.activate_scripts_menu()
  711. return
  712. elif key == "D":
  713. self.queue_game.put(self.c + key + self.r + self.nl)
  714. self.queue_game.put(pformat(self.portdata).replace("\n", "\n\r") + self.nl)
  715. elif key == "Q":
  716. self.queue_game.put(self.c + key + self.r + self.nl)
  717. # This is an example of chaining PlayerInput prompt calls.
  718. ask = PlayerInput(self.game)
  719. d = ask.prompt("What is your quest?", 40, name="quest", abort_blank=True)
  720. # Display the user's input
  721. d.addCallback(ask.output)
  722. d.addCallback(
  723. lambda ignore: ask.prompt(
  724. "What is your favorite color?", 10, name="color"
  725. )
  726. )
  727. d.addCallback(ask.output)
  728. d.addCallback(
  729. lambda ignore: ask.prompt(
  730. "What is the meaning of the squirrel?",
  731. 12,
  732. name="squirrel",
  733. digits=True,
  734. )
  735. )
  736. d.addCallback(ask.output)
  737. def show_values(show):
  738. log.msg(show)
  739. self.queue_game.put(pformat(show).replace("\n", "\n\r") + self.nl)
  740. d.addCallback(lambda ignore: show_values(ask.keep))
  741. d.addCallback(self.welcome_back)
  742. # On error, just return back
  743. # This doesn't seem to be getting called.
  744. # d.addErrback(lambda ignore: self.welcome_back)
  745. d.addErrback(self.welcome_back)
  746. return
  747. elif key == "X":
  748. self.queue_game.put(self.c + key + self.r + self.nl)
  749. self.observer.load(self.save)
  750. self.save = None
  751. # It isn't running (NOW), so don't try to stop it.
  752. # self.keepalive.stop()
  753. self.keepalive = None
  754. self.queue_game.put(self.prompt)
  755. self.prompt = None
  756. # Possibly: Send '\r' to re-display the prompt
  757. # instead of displaying the original one.
  758. # Were we asked to do something when we were done here?
  759. if self.defer:
  760. reactor.CallLater(0, self.defer.callback)
  761. # self.defer.callback()
  762. self.defer = None
  763. return
  764. self.keepalive.start(30, True)
  765. self.menu()
  766. def activate_scripts_menu(self):
  767. self.observer.disconnect("player", self.player)
  768. self.observer.connect("player", self.scripts_player)
  769. self.scripts_menu()
  770. def deactivate_scripts_menu(self):
  771. self.observer.disconnect("player", self.scripts_player)
  772. self.observer.connect("player", self.player)
  773. self.welcome_back()
  774. def scripts_menu(self, *_):
  775. c1 = merge(Style.BRIGHT + Fore.CYAN)
  776. c2 = merge(Style.NORMAL + Fore.CYAN)
  777. def menu_item(ch, desc):
  778. self.queue_game.put(
  779. " " + c1 + ch + c2 + " - " + c1 + desc + self.nl
  780. )
  781. menu_item("1", "Ports (Trades between two sectors)")
  782. menu_item("2", "TODO")
  783. menu_item("3", "TODO")
  784. menu_item("X", "eXit")
  785. self.queue_game.put(" " + c1 + "-=>" + self.r + " ")
  786. def scripts_player(self, chunk: bytes):
  787. """ Data from player (in bytes). """
  788. chunk = chunk.decode("utf-8", "ignore")
  789. key = chunk.upper()
  790. if key == '1':
  791. self.queue_game.put(self.c + key + self.r + self.nl)
  792. # Activate this magical event here
  793. ports = ScriptPort(self.game)
  794. d = ports.whenDone()
  795. d.addCallback(self.scripts_menu)
  796. d.addErrback(self.scripts_menu)
  797. return
  798. elif key == 'X':
  799. self.queue_game.put(self.c + key + self.r + self.nl)
  800. self.deactivate_scripts_menu()
  801. return
  802. else:
  803. self.queue_game.put(self.c + "?" + self.r + self.nl)
  804. self.scripts_menu()
  805. def welcome_back(self, *_):
  806. log.msg("welcome_back")
  807. self.keepalive.start(30, True)
  808. self.menu()