flexible.py 35 KB

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