flexible.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  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. pass
  348. def game_prompt(self, prompt: str):
  349. log.msg("{0} : {1}".format(self.state, prompt))
  350. if self.state == 3:
  351. log.msg("game_prompt: ", prompt)
  352. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  353. self.state = 4
  354. log.msg("Ok, state 4")
  355. if self.sector2 is None:
  356. # Ok, we need to prompt for this.
  357. self.queue_game.put(self.r + self.nl + "Which sector to trade with?" + self.nl + Fore.CYAN)
  358. for i, p in enumerate(self.possible):
  359. self.queue_game.put(" " + str(i + 1) + " : " + str(p) + self.nl)
  360. pi = PlayerInput(self.game)
  361. def got_need1(*_):
  362. log.msg("Ok, I have:", pi.keep)
  363. if pi.keep['count'].strip() == '':
  364. self.deactivate()
  365. return
  366. self.times_left = int(pi.keep['count'])
  367. if pi.keep['choice'].strip() == '':
  368. self.deactivate()
  369. return
  370. c = int(pi.keep['choice']) -1
  371. if c < 0 or c >= len(self.possible):
  372. self.deactivate()
  373. return
  374. self.sector2 = self.possible[int(pi.keep['choice']) -1]
  375. # self.queue_game.put(pformat(pi.keep).replace("\n", "\n\r"))
  376. self.state = 5
  377. self.trade()
  378. d = pi.prompt("Choose -=>", 5, name='choice', digits=True)
  379. d.addCallback(lambda ignore: pi.prompt("Times to execute script:", 5, name='count', digits=True))
  380. d.addCallback(got_need1)
  381. else:
  382. # We already have our target port, so...
  383. pi = PlayerInput(self.game)
  384. def got_need2(*_):
  385. if pi.keep['count'].strip() == '':
  386. self.deactivate()
  387. return
  388. self.times_left = int(pi.keep['count'])
  389. log.msg("Ok, I have:", pi.keep)
  390. self.queue_game.put(pformat(pi.keep).replace("\n", "\n\r"))
  391. self.state = 5
  392. self.trade()
  393. self.queue_game.put(self.r + self.nl)
  394. d = pi.prompt("Times to execute script", 5, name='count')
  395. d.addCallback(got_need2)
  396. elif self.state == 7:
  397. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  398. # Done
  399. if self.this_sector == self.sector1:
  400. self.this_sector = self.sector2
  401. self.queue_player.put("{0}\r".format(self.sector2))
  402. self.state = 10
  403. else:
  404. self.times_left -= 1
  405. if self.times_left <= 0:
  406. # Ok, exit out
  407. self.deactivate()
  408. return
  409. self.this_sector = self.sector1
  410. self.queue_player.put("{0}\r".format(self.sector1))
  411. self.state = 10
  412. elif self.state == 8:
  413. # What are we trading
  414. if "How many holds of" in prompt:
  415. parts = prompt.split()
  416. trade_type = parts[4]
  417. if trade_type == 'Fuel':
  418. if (self.tpc in (5,7)) and (self.opc in (2,3,4,8)):
  419. # Can buy equipment - fuel ore is worthless.
  420. self.queue_player.put("0\r")
  421. return
  422. if (self.tpc in(4,7)) and (self.opc in (1,3,5,8)):
  423. # Can buy organics - fuel ore is worthless.
  424. self.queue_player.put("0\r")
  425. return
  426. if (self.tpc in (4,7,3,5)) and (self.opc in (3,4,5,7)):
  427. # No point in buying fuel ore if it can't be sold.
  428. self.queue_player.put("0\r")
  429. return
  430. elif trade_type == 'Organics':
  431. if (self.tpc in (6,7)) and (self.opc in (2,3,4,8)):
  432. # Can buy equipment - organics is worthless.
  433. self.queue_player.put("0\r")
  434. return
  435. if (self.tpc in (2,4,6,7)) and (self.opc in (2,4,6,7)):
  436. # No point in buying organics if it can't be sold.
  437. self.queue_player.put("0\r")
  438. return
  439. elif trade_type == 'Equipment':
  440. if (self.opc in (1,5,6,7)):
  441. # No point in buying equipment if it can't be sold.
  442. self.queue_player.put("0\r")
  443. return
  444. self.queue_player.put("\r")
  445. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  446. # Done
  447. if self.this_sector == self.sector1:
  448. self.this_sector = self.sector2
  449. self.queue_player.put("{0}\r".format(self.sector2))
  450. self.state = 10
  451. else:
  452. self.times_left -= 1
  453. if self.times_left <= 0:
  454. # Ok, exit out
  455. self.deactivate()
  456. return
  457. self.this_sector = self.sector1
  458. self.queue_player.put("{0}\r".format(self.sector1))
  459. self.state = 10
  460. def trade(self, *_):
  461. # state 5
  462. log.msg("trade!")
  463. self.queue_player.put("pt") # Port Trade
  464. self.this_port = self.game.portdata[self.this_sector]
  465. if self.this_sector == self.sector1:
  466. self.other_port = self.game.portdata[self.sector2]
  467. else:
  468. self.other_port = self.game.portdata[self.sector1]
  469. # Ok, perform some calculations
  470. self.tpc = self.this_port['class']
  471. self.opc = self.other_port['class']
  472. # [ Items Status Trading % of max OnBoard]
  473. # [ ----- ------ ------- -------- -------]
  474. # [Fuel Ore Selling 2573 93% 0]
  475. # [Organics Buying 2960 100% 0]
  476. # [Equipment Buying 1958 86% 0]
  477. # []
  478. # []
  479. # [You have 1,000 credits and 20 empty cargo holds.]
  480. # []
  481. # [We are selling up to 2573. You have 0 in your holds.]
  482. # [How many holds of Fuel Ore do you want to buy [20]? 0]
  483. pass
  484. def game_line(self, line: str):
  485. if self.state == 1:
  486. # First exploration
  487. if line.startswith("Sector :"):
  488. # We have starting sector information
  489. parts = re.split("\s+", line)
  490. self.this_sector = int(parts[2])
  491. # These will be the ones swapped around as we trade back and forth.
  492. self.sector1 = self.this_sector
  493. elif line.startswith("Warps to Sector(s) : "):
  494. # Warps to Sector(s) : 397 - (562) - (639)
  495. _, _, warps = line.partition(':')
  496. warps = warps.replace('-', '').replace('(', '').replace(')', '').strip()
  497. log.msg("Warps: [{0}]".format(warps))
  498. self.warps = [ int(x) for x in re.split("\s+", warps)]
  499. log.msg("Warps: [{0}]".format(self.warps))
  500. self.state = 2
  501. elif self.state == 2:
  502. if line == "":
  503. # Ok, we're done
  504. self.state = 3
  505. # Check to see if we have information on any possible ports
  506. if hasattr(self.game, 'portdata'):
  507. if not self.this_sector in self.game.portdata:
  508. self.state = 0
  509. log.msg("Current sector {0} not in portdata.".format(self.this_sector))
  510. self.queue_game.put(self.r + self.nl + "I can't find the current sector in the portdata." + self.nl)
  511. self.deactivate()
  512. return
  513. else:
  514. # Ok, we are in the portdata
  515. def port_burnt(port):
  516. if port['equ']['pct'] <= 20 or port['fuel']['pct'] <= 20 or port['org']['pct'] <= 20:
  517. return True
  518. return False
  519. pd = self.game.portdata[self.this_sector]
  520. if port_burnt(pd):
  521. log.msg("Current sector {0} port is burnt (<= 20%).".format(self.this_sector))
  522. self.queue_game.put(self.r + self.nl + "Current sector port is burnt out. <= 20%." + self.nl)
  523. self.deactivate()
  524. return
  525. # possible = [ x for x in self.warps if x in self.game.portdata ]
  526. possible = [ x for x in self.warps if x in self.game.portdata and not port_burnt(self.game.portdata[x]) ]
  527. log.msg("Possible:", possible)
  528. self.possible = possible
  529. if len(possible) == 0:
  530. self.state = 0
  531. self.queue_game.put(self.r + self.nl + "I don't see any (not burnt) ports in [{0}].".format(self.warps) + self.nl)
  532. self.deactivate()
  533. return
  534. elif len(possible) == 1:
  535. # Ok! there's only one!
  536. self.sector2 = possible[0]
  537. # Display possible ports:
  538. # spos = [ str(x) for x in possible]
  539. # self.queue_game.put(self.r + self.nl + self.nl.join(spos) + self.nl)
  540. # At state 3, we only get a prompt.
  541. return
  542. else:
  543. self.state = 0
  544. log.msg("We don't have any portdata!")
  545. self.queue_game.put(self.r + self.nl + "I have no portdata. Please run CIM Port Report." + self.nl)
  546. self.deactivate()
  547. return
  548. elif self.state == 5:
  549. if "-----" in line:
  550. self.state = 6
  551. elif self.state == 6:
  552. if "We are buying up to" in line:
  553. # Sell
  554. self.state = 7
  555. self.queue_player.put("\r")
  556. self.sell_perc = 100 + self.percent
  557. if "We are selling up to" in line:
  558. # Buy
  559. self.state = 8
  560. self.sell_perc = 100 - self.percent
  561. if "You don't have anything they want" in line:
  562. # Neither! DRAT!
  563. self.deactivate()
  564. return
  565. if "We're not interested." in line:
  566. log.msg("Try, try again. :(")
  567. self.state = 5
  568. self.trade()
  569. elif self.state == 7:
  570. # Haggle Sell
  571. if "We'll buy them for" in line or "Our final offer" in line:
  572. if "Our final offer" in line:
  573. self.sell_perc -= 1
  574. parts = line.replace(',', '').split()
  575. start_price = int(parts[4])
  576. price = start_price * self.sell_perc // 100
  577. log.msg("start: {0} % {1} price {2}".format(start_price, self.sell_perc, price))
  578. self.sell_perc -= 1
  579. self.queue_player.put("{0}\r".format(price))
  580. if "We are selling up to" in line:
  581. # Buy
  582. self.state = 8
  583. self.sell_perc = 100 - self.percent
  584. if line.startswith("You have ") and 'credits and' in line:
  585. parts = line.replace(',', '').split()
  586. credits = int(parts[2])
  587. if self.credits == 0:
  588. self.credits = credits
  589. else:
  590. if credits <= self.credits:
  591. log.msg("We don't appear to be making any money here {0}.".format(credits))
  592. self.deactivate()
  593. return
  594. elif self.state == 8:
  595. # Haggle Buy
  596. if "We'll sell them for" in line or "Our final offer" in line:
  597. if "Our final offer" in line:
  598. self.sell_perc += 1
  599. parts = line.replace(',', '').split()
  600. start_price = int(parts[4])
  601. price = start_price * self.sell_perc // 100
  602. log.msg("start: {0} % {1} price {2}".format(start_price, self.sell_perc, price))
  603. self.sell_perc += 1
  604. self.queue_player.put("{0}\r".format(price))
  605. elif self.state == 10:
  606. if "Sector : " in line:
  607. # Trade
  608. self.state = 5
  609. reactor.callLater(0, self.trade, 0)
  610. # self.trade()
  611. # elif self.state == 3:
  612. # log.msg("At state 3 [{0}]".format(line))
  613. # self.queue_game.put("At state 3.")
  614. # self.deactivate()
  615. # return
  616. class ProxyMenu(object):
  617. """ Display ProxyMenu
  618. Example:
  619. from flexible import ProxyMenu
  620. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  621. menu = ProxyMenu(self.game)
  622. """
  623. def __init__(self, game):
  624. self.nl = "\n\r"
  625. self.c = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  626. self.r = Style.RESET_ALL
  627. self.c1 = merge(Style.BRIGHT + Fore.BLUE)
  628. self.c2 = merge(Style.NORMAL + Fore.CYAN)
  629. self.portdata = None
  630. self.game = game
  631. self.queue_game = game.queue_game
  632. self.observer = game.observer
  633. if hasattr(self.game, "portdata"):
  634. self.portdata = self.game.portdata
  635. else:
  636. self.portdata = {}
  637. # Yes, at this point we would activate
  638. self.prompt = game.buffer
  639. self.save = self.observer.save()
  640. self.observer.connect("player", self.player)
  641. # If we want it, it's here.
  642. self.defer = None
  643. self.keepalive = task.LoopingCall(self.awake)
  644. self.keepalive.start(30)
  645. self.menu()
  646. def __del__(self):
  647. log.msg("ProxyMenu {0} RIP".format(self))
  648. def whenDone(self):
  649. self.defer = defer.Deferred()
  650. # Call this to chain something after we exit.
  651. return self.defer
  652. def menu(self):
  653. self.queue_game.put(
  654. self.nl + self.c + "TradeWars Proxy active." + self.r + self.nl
  655. )
  656. def menu_item(ch: str, desc: str):
  657. self.queue_game.put(
  658. " " + self.c1 + ch + self.c2 + " - " + self.c1 + desc + self.nl
  659. )
  660. menu_item("D", "Diagnostics")
  661. menu_item("Q", "Quest")
  662. menu_item("T", "Display current Time")
  663. menu_item("P", "Port CIM Report")
  664. menu_item("S", "Scripts")
  665. menu_item("X", "eXit")
  666. self.queue_game.put(" " + self.c + "-=>" + self.r + " ")
  667. def awake(self):
  668. log.msg("ProxyMenu.awake()")
  669. self.game.queue_player.put(" ")
  670. def port_report(self, portdata: dict):
  671. self.portdata = portdata
  672. self.queue_game.put("Loaded {0} records.".format(len(portdata)) + self.nl)
  673. self.welcome_back()
  674. def player(self, chunk: bytes):
  675. """ Data from player (in bytes). """
  676. chunk = chunk.decode("utf-8", "ignore")
  677. key = chunk.upper()
  678. log.msg("ProxyMenu.player({0})".format(key))
  679. # Stop the keepalive if we are activating something else
  680. # or leaving...
  681. self.keepalive.stop()
  682. if key == "T":
  683. self.queue_game.put(self.c + key + self.r + self.nl)
  684. # perform T option
  685. now = pendulum.now()
  686. self.queue_game.put(
  687. self.nl + self.c1 + "Current time " + now.to_datetime_string() + self.nl
  688. )
  689. elif key == "P":
  690. self.queue_game.put(self.c + key + self.r + self.nl)
  691. # Activate CIM Port Report
  692. report = CIMPortReport(self.game)
  693. d = report.whenDone()
  694. d.addCallback(self.port_report)
  695. d.addErrback(self.welcome_back)
  696. return
  697. elif key == "S":
  698. self.queue_game.put(self.c + key + self.r + self.nl)
  699. self.activate_scripts_menu()
  700. return
  701. elif key == "D":
  702. self.queue_game.put(self.c + key + self.r + self.nl)
  703. self.queue_game.put(pformat(self.portdata).replace("\n", "\n\r") + self.nl)
  704. elif key == "Q":
  705. self.queue_game.put(self.c + key + self.r + self.nl)
  706. # This is an example of chaining PlayerInput prompt calls.
  707. ask = PlayerInput(self.game)
  708. d = ask.prompt("What is your quest?", 40, name="quest", abort_blank=True)
  709. # Display the user's input
  710. d.addCallback(ask.output)
  711. d.addCallback(
  712. lambda ignore: ask.prompt(
  713. "What is your favorite color?", 10, name="color"
  714. )
  715. )
  716. d.addCallback(ask.output)
  717. d.addCallback(
  718. lambda ignore: ask.prompt(
  719. "What is the meaning of the squirrel?",
  720. 12,
  721. name="squirrel",
  722. digits=True,
  723. )
  724. )
  725. d.addCallback(ask.output)
  726. def show_values(show):
  727. log.msg(show)
  728. self.queue_game.put(pformat(show).replace("\n", "\n\r") + self.nl)
  729. d.addCallback(lambda ignore: show_values(ask.keep))
  730. d.addCallback(self.welcome_back)
  731. # On error, just return back
  732. # This doesn't seem to be getting called.
  733. # d.addErrback(lambda ignore: self.welcome_back)
  734. d.addErrback(self.welcome_back)
  735. return
  736. elif key == "X":
  737. self.queue_game.put(self.c + key + self.r + self.nl)
  738. self.observer.load(self.save)
  739. self.save = None
  740. # It isn't running (NOW), so don't try to stop it.
  741. # self.keepalive.stop()
  742. self.keepalive = None
  743. self.queue_game.put(self.prompt)
  744. self.prompt = None
  745. # Possibly: Send '\r' to re-display the prompt
  746. # instead of displaying the original one.
  747. # Were we asked to do something when we were done here?
  748. if self.defer:
  749. reactor.CallLater(0, self.defer.callback)
  750. # self.defer.callback()
  751. self.defer = None
  752. return
  753. self.keepalive.start(30, True)
  754. self.menu()
  755. def activate_scripts_menu(self):
  756. self.observer.disconnect("player", self.player)
  757. self.observer.connect("player", self.scripts_player)
  758. self.scripts_menu()
  759. def deactivate_scripts_menu(self):
  760. self.observer.disconnect("player", self.scripts_player)
  761. self.observer.connect("player", self.player)
  762. self.welcome_back()
  763. def scripts_menu(self, *_):
  764. c1 = merge(Style.BRIGHT + Fore.CYAN)
  765. c2 = merge(Style.NORMAL + Fore.CYAN)
  766. def menu_item(ch, desc):
  767. self.queue_game.put(
  768. " " + c1 + ch + c2 + " - " + c1 + desc + self.nl
  769. )
  770. menu_item("1", "Ports (Trades between two sectors)")
  771. menu_item("2", "TODO")
  772. menu_item("3", "TODO")
  773. menu_item("X", "eXit")
  774. self.queue_game.put(" " + c1 + "-=>" + self.r + " ")
  775. def scripts_player(self, chunk: bytes):
  776. """ Data from player (in bytes). """
  777. chunk = chunk.decode("utf-8", "ignore")
  778. key = chunk.upper()
  779. if key == '1':
  780. self.queue_game.put(self.c + key + self.r + self.nl)
  781. # Activate this magical event here
  782. ports = ScriptPort(self.game)
  783. d = ports.whenDone()
  784. d.addCallback(self.scripts_menu)
  785. d.addErrback(self.scripts_menu)
  786. return
  787. elif key == 'X':
  788. self.queue_game.put(self.c + key + self.r + self.nl)
  789. self.deactivate_scripts_menu()
  790. return
  791. else:
  792. self.queue_game.put(self.c + "?" + self.r + self.nl)
  793. self.scripts_menu()
  794. def welcome_back(self, *_):
  795. log.msg("welcome_back")
  796. self.keepalive.start(30, True)
  797. self.menu()