flexible.py 213 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394
  1. from twisted.internet import reactor
  2. from twisted.internet import task
  3. from twisted.internet import defer
  4. from colorama import Fore, Back, Style
  5. # from twisted.python import log
  6. from twisted.internet.task import coiterate
  7. from twisted.internet.defer import gatherResults
  8. from itertools import cycle
  9. import pendulum
  10. from pprint import pformat
  11. from galaxy import GameData, PORT_CLASSES, CLASSES_PORT
  12. from boxes import Boxes
  13. import logging
  14. from time import localtime
  15. BLINK = "\x1b[5m"
  16. log = logging.getLogger(__name__)
  17. class SpinningCursor(object):
  18. """ Spinner class, that handles every so many clicks
  19. s = SpinningCursor(5) # every 5
  20. for x in range(10):
  21. if s.click():
  22. print(s.cycle())
  23. """
  24. def __init__(self, every=10):
  25. self.itercycle = cycle(["/", "-", "\\", "|"])
  26. self.count = 0
  27. self.every = every
  28. def reset(self):
  29. self.itercycle = cycle(["/", "-", "\\", "|"])
  30. self.count = 0
  31. def click(self):
  32. self.count += 1
  33. return self.count % self.every == 0
  34. def cycle(self):
  35. return next(self.itercycle)
  36. def again(self, count: int):
  37. return self.count % count == 0
  38. def merge(color_string):
  39. """ Given a string of colorama ANSI, merge them if you can. """
  40. return color_string.replace("m\x1b[", ";")
  41. class PlayerInput(object):
  42. """ Player Input
  43. Example:
  44. from flexible import PlayerInput
  45. ask = PlayerInput(self.game)
  46. # abort_blank means, if the input field is blank, abort. Use error_back.
  47. d = ask.prompt("What is your quest?", 40, name="quest", abort_blank=True)
  48. # Display the user's input / but not needed.
  49. d.addCallback(ask.output)
  50. d.addCallback(
  51. lambda ignore: ask.prompt(
  52. "What is your favorite color?", 10, name="color"
  53. )
  54. )
  55. d.addCallback(ask.output)
  56. d.addCallback(
  57. lambda ignore: ask.prompt(
  58. "What is your least favorite number?",
  59. 12,
  60. name="number",
  61. digits=True,
  62. )
  63. )
  64. d.addCallback(ask.output)
  65. def show_values(show):
  66. log.debug(show)
  67. self.queue_game.put(pformat(show).replace("\n", "\n\r") + self.nl)
  68. d.addCallback(lambda ignore: show_values(ask.keep))
  69. d.addCallback(self.welcome_back)
  70. # On error, just return back
  71. d.addErrback(self.welcome_back)
  72. """
  73. def __init__(self, game):
  74. # I think game gives us access to everything we need
  75. self.game = game
  76. self.observer = self.game.observer
  77. self.save = None
  78. self.deferred = None
  79. self.queue_game = game.queue_game
  80. self.keep = {}
  81. # default colors
  82. # prompt
  83. self.c = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  84. # input
  85. self.cp = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  86. # useful constants
  87. self.r = Style.RESET_ALL
  88. self.nl = "\n\r"
  89. self.bsb = "\b \b"
  90. self.keepalive = None
  91. def color(self, c):
  92. self.c = c
  93. def colorp(self, cp):
  94. self.cp = cp
  95. def alive(self):
  96. log.debug("PlayerInput.alive()")
  97. self.game.queue_player.put(" ")
  98. def prompt(self, user_prompt, limit, **kw):
  99. """ Generate prompt for user input.
  100. Note: This returns deferred.
  101. prompt = text displayed.
  102. limit = # of characters allowed.
  103. default = (text to default to)
  104. keywords:
  105. abort_blank : Abort if they give us blank text.
  106. name : Stores the input in self.keep dict.
  107. digits : Only allow 0-9 to be entered.
  108. """
  109. log.debug("PlayerInput({0}, {1}, {2}".format(user_prompt, limit, kw))
  110. self.limit = limit
  111. self.input = ""
  112. self.kw = kw
  113. assert self.save is None
  114. assert self.keepalive is None
  115. # Note: This clears out the server "keep alive"
  116. self.save = self.observer.save()
  117. self.observer.connect("player", self.get_input)
  118. self.keepalive = task.LoopingCall(self.alive)
  119. self.keepalive.start(30)
  120. # We need to "hide" the game output.
  121. # Otherwise it WITH mess up the user input display.
  122. self.to_player = self.game.to_player
  123. self.game.to_player = False
  124. # Display prompt
  125. # self.queue_game.put(self.r + self.nl + self.c + user_prompt + " " + self.cp)
  126. self.queue_game.put(self.r + self.c + user_prompt + self.r + " " + self.cp)
  127. # Set "Background of prompt"
  128. self.queue_game.put(" " * limit + "\b" * limit)
  129. assert self.deferred is None
  130. d = defer.Deferred()
  131. self.deferred = d
  132. log.debug("Return deferred ...")
  133. return d
  134. def get_input(self, chunk):
  135. """ Data from player (in bytes) """
  136. chunk = chunk.decode("latin-1", "ignore")
  137. for ch in chunk:
  138. if ch == "\b":
  139. if len(self.input) > 0:
  140. self.queue_game.put(self.bsb)
  141. self.input = self.input[0:-1]
  142. else:
  143. self.queue_game.put("\a")
  144. elif ch == "\r":
  145. self.queue_game.put(self.r + self.nl)
  146. log.debug("Restore observer dispatch {0}".format(self.save))
  147. assert not self.save is None
  148. self.observer.load(self.save)
  149. self.save = None
  150. log.debug("Disable keepalive")
  151. self.keepalive.stop()
  152. self.keepalive = None
  153. line = self.input
  154. self.input = ""
  155. assert not self.deferred is None
  156. self.game.to_player = self.to_player
  157. # If they gave us the keyword name, save the value as that name
  158. if "name" in self.kw:
  159. self.keep[self.kw["name"]] = line
  160. if "abort_blank" in self.kw and self.kw["abort_blank"]:
  161. # Abort on blank input
  162. if line.strip() == "":
  163. # Yes, input is blank, abort.
  164. log.info("errback, abort_blank")
  165. reactor.callLater(
  166. 0, self.deferred.errback, Exception("abort_blank")
  167. )
  168. self.deferred = None
  169. return
  170. # Ok, use deferred.callback, or reactor.callLater?
  171. # self.deferred.callback(line)
  172. reactor.callLater(0, self.deferred.callback, line)
  173. self.deferred = None
  174. return
  175. elif ch.isprintable():
  176. # Printable, but is it acceptable?
  177. if "digits" in self.kw:
  178. if not ch.isdigit():
  179. self.queue_game.put("\a")
  180. continue
  181. if len(self.input) + 1 <= self.limit:
  182. self.input += ch
  183. self.queue_game.put(ch)
  184. else:
  185. self.queue_game.put("\a")
  186. def output(self, line):
  187. """ A default display of what they just input. """
  188. log.debug("PlayerInput.output({0})".format(line))
  189. self.game.queue_game.put(self.r + "[{0}]".format(line) + self.nl)
  190. return line
  191. import re
  192. # The CIMWarpReport -- is only needed if the json file gets damaged in some way.
  193. # Like when the universe gets bigbanged. :P
  194. # or needs to be reset. The warps should automatically update themselves now.
  195. class CIMWarpReport(object):
  196. def __init__(self, game):
  197. self.game = game
  198. self.queue_game = game.queue_game
  199. self.queue_player = game.queue_player
  200. self.observer = game.observer
  201. # Yes, at this point we would activate
  202. self.prompt = game.buffer
  203. self.save = self.observer.save()
  204. self.days = ("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun")
  205. # I actually don't want the player input, but I'll grab it anyway.
  206. self.observer.connect("player", self.player)
  207. self.observer.connect("prompt", self.game_prompt)
  208. self.observer.connect("game-line", self.game_line)
  209. # If we want it, it's here.
  210. self.defer = None
  211. self.to_player = self.game.to_player
  212. # Hide what's happening from the player
  213. self.game.to_player = False
  214. self.queue_player.put("^") # Activate CIM
  215. self.state = 1
  216. # self.warpdata = {}
  217. tm = localtime()
  218. log.debug("Today is {0}".format(self.days[tm[6]]))
  219. self.queue_game.put("Loading ") # cycle eats last char.
  220. self.warpcycle = SpinningCursor()
  221. def game_prompt(self, prompt):
  222. if prompt == ": ":
  223. if self.state == 1:
  224. # Ok, then we're ready to request the port report
  225. self.warpcycle.reset()
  226. self.queue_player.put("I")
  227. self.state = 2
  228. elif self.state == 2:
  229. self.queue_player.put("Q")
  230. self.state = 3
  231. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  232. if self.state == 3:
  233. # Ok, time to exit
  234. # exit from this...
  235. self.game.to_player = self.to_player
  236. self.observer.load(self.save)
  237. self.save = None
  238. # self.game.warpdata = self.warpdata
  239. self.queue_game.put("\b \b\r\n")
  240. if not self.defer is None:
  241. self.defer.callback(self.game.gamedata.warps)
  242. self.defer = None
  243. def game_line(self, line):
  244. if line == "" or line == ": ":
  245. return
  246. if line == ": ENDINTERROG":
  247. return
  248. if line.startswith("Command [TL="):
  249. return
  250. # This should be the CIM Report Data -- parse it
  251. if self.warpcycle:
  252. if self.warpcycle.click():
  253. self.queue_game.put("\b")
  254. if self.warpcycle.again(1000):
  255. self.queue_game.put(".")
  256. self.queue_game.put(self.warpcycle.cycle())
  257. work = line.strip()
  258. parts = re.split(r"(?<=\d)\s", work)
  259. parts = [int(x) for x in parts]
  260. sector = parts.pop(0)
  261. # tuples are nicer on memory, and the warpdata map isn't going to be changing.
  262. # self.warpdata[sector] = tuple(parts)
  263. self.game.gamedata.warp_to(sector, *parts)
  264. def __del__(self):
  265. log.debug("CIMWarpReport {0} RIP".format(self))
  266. def whenDone(self):
  267. self.defer = defer.Deferred()
  268. # Call this to chain something after we exit.
  269. return self.defer
  270. def player(self, chunk):
  271. """ Data from player (in bytes). """
  272. chunk = chunk.decode("latin-1", "ignore")
  273. key = chunk.upper()
  274. log.warn("CIMWarpReport.player({0}) : I AM stopping...".format(key))
  275. # Stop the keepalive if we are activating something else
  276. # or leaving...
  277. # self.keepalive.stop()
  278. self.queue_game.put("\b \b\r\n")
  279. if not self.defer is None:
  280. # We have something, so:
  281. self.game.to_player = self.to_player
  282. self.observer.load(self.save)
  283. self.save = None
  284. self.defer.errback(Exception("User Abort"))
  285. self.defer = None
  286. else:
  287. # Still "exit" out.
  288. self.game.to_player = self.to_player
  289. self.observer.load(self.save)
  290. # the CIMPortReport will still be needed.
  291. # We can't get fresh report data (that changes) any other way.
  292. class CIMPortReport(object):
  293. """ Parse data from CIM Port Report
  294. Example:
  295. from flexible import CIMPortReport
  296. report = CIMPortReport(self.game)
  297. d = report.whenDone()
  298. d.addCallback(self.port_report)
  299. d.addErrback(self.welcome_back)
  300. def port_report(self, portdata):
  301. self.portdata = portdata
  302. self.queue_game.put("Loaded {0} records.".format(len(portdata)) + self.nl)
  303. self.welcome_back()
  304. def welcome_back(self,*_):
  305. ... restore keep alive timers, etc.
  306. """
  307. def __init__(self, game):
  308. self.game = game
  309. self.queue_game = game.queue_game
  310. self.queue_player = game.queue_player
  311. self.observer = game.observer
  312. # Yes, at this point we would activate
  313. self.prompt = game.buffer
  314. self.save = self.observer.save()
  315. self.days = ("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun")
  316. # I actually don't want the player input, but I'll grab it anyway.
  317. self.observer.connect("player", self.player)
  318. self.observer.connect("prompt", self.game_prompt)
  319. self.observer.connect("game-line", self.game_line)
  320. # If we want it, it's here.
  321. self.defer = None
  322. self.to_player = self.game.to_player
  323. log.debug("to_player (stored) {0}".format(self.to_player))
  324. # Hide what's happening from the player
  325. self.game.to_player = False
  326. self.queue_player.put("^") # Activate CIM
  327. self.state = 1
  328. # self.portdata = {}
  329. tm = localtime()
  330. log.debug("Today is {0}".format(self.days[tm[6]]))
  331. self.queue_game.put("Loading ") # cycle eats last char.
  332. self.portcycle = SpinningCursor()
  333. def game_prompt(self, prompt):
  334. if prompt == ": ":
  335. if self.state == 1:
  336. # Ok, then we're ready to request the port report
  337. self.portcycle.reset()
  338. self.queue_player.put("R")
  339. self.state = 2
  340. elif self.state == 2:
  341. self.queue_player.put("Q")
  342. self.state = 3
  343. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  344. if self.state == 3:
  345. # Ok, time to exit
  346. # exit from this...
  347. self.game.to_player = self.to_player
  348. self.observer.load(self.save)
  349. self.save = None
  350. # self.game.portdata = self.portdata
  351. self.queue_game.put("\b \b\r\n")
  352. if not self.defer is None:
  353. self.defer.callback(self.game.gamedata.ports)
  354. self.defer = None
  355. def game_line(self, line: str):
  356. if line == "" or line == ": ":
  357. return
  358. if line == ": ENDINTERROG":
  359. return
  360. # This should be the CIM Report Data -- parse it
  361. if self.portcycle:
  362. if self.portcycle.click():
  363. self.queue_game.put("\b")
  364. if self.portcycle.again(1000):
  365. self.queue_game.put(".")
  366. self.queue_game.put(self.portcycle.cycle())
  367. work = line.replace("%", "")
  368. parts = re.split(r"(?<=\d)\s", work)
  369. if len(parts) == 8:
  370. port = int(parts[0].strip())
  371. data = dict()
  372. def portBS(info):
  373. if info[0] == "-":
  374. bs = "B"
  375. else:
  376. bs = "S"
  377. return (bs, int(info[1:].strip()))
  378. data["fuel"] = dict()
  379. data["fuel"]["sale"], data["fuel"]["units"] = portBS(parts[1])
  380. data["fuel"]["pct"] = int(parts[2].strip())
  381. data["org"] = dict()
  382. data["org"]["sale"], data["org"]["units"] = portBS(parts[3])
  383. data["org"]["pct"] = int(parts[4].strip())
  384. data["equ"] = dict()
  385. data["equ"]["sale"], data["equ"]["units"] = portBS(parts[5])
  386. data["equ"]["pct"] = int(parts[6].strip())
  387. # Store what this port is buying/selling
  388. data["port"] = (
  389. data["fuel"]["sale"] + data["org"]["sale"] + data["equ"]["sale"]
  390. )
  391. # Convert BBS/SBB to Class number 1-8
  392. data["class"] = CLASSES_PORT[data["port"]]
  393. self.game.gamedata.set_port(port, data)
  394. # self.portdata[port] = data
  395. else:
  396. log.error("CIMPortReport: {0} ???".format(line))
  397. def __del__(self):
  398. log.debug("CIMPortReport {0} RIP".format(self))
  399. def whenDone(self):
  400. self.defer = defer.Deferred()
  401. # Call this to chain something after we exit.
  402. return self.defer
  403. def player(self, chunk):
  404. """ Data from player (in bytes). """
  405. chunk = chunk.decode("latin-1", "ignore")
  406. key = chunk.upper()
  407. log.warn("CIMPortReport.player({0}) : I AM stopping...".format(key))
  408. # Stop the keepalive if we are activating something else
  409. # or leaving...
  410. # self.keepalive.stop()
  411. self.queue_game.put("\b \b\r\n")
  412. if not self.defer is None:
  413. # We have something, so:
  414. self.game.to_player = self.to_player
  415. self.observer.load(self.save)
  416. self.save = None
  417. self.defer.errback(Exception("User Abort"))
  418. self.defer = None
  419. else:
  420. # Still "exit" out.
  421. self.game.to_player = self.to_player
  422. self.observer.load(self.save)
  423. class ScriptPort(object):
  424. """ Performs the Port script.
  425. This is close to the original.
  426. We don't ask for the port to trade with --
  427. because that information is available to us after "D" (display).
  428. We look at the adjacent sectors, and see if we know any ports.
  429. If the ports are burnt (< 20%), we remove them from the list.
  430. We sort the best trades first.
  431. If there's just one, we use it. Otherwise we ask them to choose.
  432. We have options Trade_UseFirst, which uses the first one, if
  433. there is more then one.
  434. Option Trade_Turns, will use this as default turns, without
  435. asking.
  436. state = 1 "D"
  437. Get current sector, store possible warps.
  438. state = 2 Done with display sector.
  439. Look for possible trades.
  440. If possible, or only one, state to 3.
  441. state = 3 Command prompt, state = 4
  442. Prompt for port to trade with (If not Trade_UserFirst).
  443. Port found/given to trade with, state = 5, trade()
  444. trade() "PT"
  445. state = 5 "-----" in line, state = 6
  446. state = 6 "We are buying", "\r" (sell all!), state = 7
  447. "We are selling", state = 8
  448. state = 7 "Haggle sell"
  449. "We are buying", "\r" (sell all!), state = 7
  450. "We are selling", state = 8
  451. state = 8 "Haggle buy"
  452. Done, if times_left > 0 then
  453. move and state = 10
  454. """
  455. def __init__(self, game):
  456. self.game = game
  457. self.queue_game = game.queue_game
  458. self.queue_player = game.queue_player
  459. self.observer = game.observer
  460. self.r = Style.RESET_ALL
  461. self.nl = "\n\r"
  462. self.this_sector = None # Starting sector
  463. self.sector1 = None # Current Sector
  464. self.sector2 = None # Next Sector Stop
  465. self.percent = self.game.gamedata.get_config("Trade_Percent", "5")
  466. self.stop = self.game.gamedata.get_config("Trade_Stop", "10")
  467. try:
  468. self.stop = int(self.stop)
  469. except ValueError:
  470. self.stop = 10
  471. # Validate what we got from the config.
  472. # Not an int: make it 5, and update.
  473. # > 50, make it 5 and update.
  474. # < 0, make it 0 and update.
  475. update_config = False
  476. try:
  477. self.percent = int(self.percent)
  478. except ValueError:
  479. self.percent = 5
  480. update_config = True
  481. if self.percent > 50:
  482. self.percent = 5
  483. update_config = True
  484. if self.percent < 0:
  485. self.percent = 0
  486. update_config = True
  487. if update_config:
  488. self.game.gamedata.set_config("Trade_Percent", self.percent)
  489. self.credits = 0
  490. self.last_credits = None
  491. self.times_left = 0
  492. # Activate
  493. self.prompt = game.buffer
  494. self.save = self.observer.save()
  495. self.observer.connect("player", self.player)
  496. self.observer.connect("prompt", self.game_prompt)
  497. self.observer.connect("game-line", self.game_line)
  498. self.defer = None
  499. self.send2player(self.r + "Script based on: Port Pair Trading v2.00" + self.nl)
  500. self.possible_sectors = None
  501. self.state = 1
  502. self.queue_player.put("D")
  503. # Original, send 'D' to display current sector.
  504. # We could get the sector number from the self.prompt string -- HOWEVER:
  505. # IF! We send 'D', we can also get the sectors around -- we might not even need to
  506. # prompt for sector to trade with (we could possibly figure it out ourselves).
  507. # [Command [TL=00:00:00]:[967] (?=Help)? : D]
  508. # [<Re-Display>]
  509. # []
  510. # [Sector : 967 in uncharted space.]
  511. # [Planets : (M) Into the Darkness]
  512. # [Warps to Sector(s) : 397 - (562) - (639)]
  513. # []
  514. def whenDone(self):
  515. self.defer = defer.Deferred()
  516. # Call this to chain something after we exit.
  517. return self.defer
  518. def deactivate(self, andExit=True):
  519. self.state = 0
  520. log.debug("ScriptPort.deactivate ({0})".format(self.times_left))
  521. self.queue_game.put(self.nl + Boxes.alert("Trading Script deactivating..."))
  522. assert not self.save is None
  523. self.observer.load(self.save)
  524. self.save = None
  525. if self.defer:
  526. if andExit:
  527. self.defer.callback({"exit": True})
  528. else:
  529. self.defer.callback("done")
  530. self.defer = None
  531. def player(self, chunk: bytes):
  532. # If we receive anything -- ABORT!
  533. self.deactivate()
  534. def send2game(self, txt):
  535. log.debug("ScriptPort.send2game({0})".format(txt))
  536. self.queue_player.put(txt)
  537. def send2player(self, txt):
  538. log.debug("ScriptPort.send2player({0})".format(txt))
  539. self.queue_game.put(txt)
  540. def game_prompt(self, prompt: str):
  541. log.debug("{0} : {1}".format(self.state, prompt))
  542. if self.state == 3:
  543. # log.("game_prompt: ", prompt)
  544. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  545. self.state = 4
  546. log.debug("Ok, state 4")
  547. use_first = (
  548. self.game.gamedata.get_config("Trade_UseFirst", "N").upper()[0]
  549. == "Y"
  550. )
  551. if self.sector2 is None and use_first:
  552. # Use the first one by default
  553. self.sector2 = self.possible[0]
  554. log.info("default to {0}".format(self.sector2))
  555. if self.sector2 is None:
  556. # Ok, we need to prompt for this.
  557. self.queue_game.put(
  558. self.r
  559. + self.nl
  560. + "Which sector to trade with? {0}".format(
  561. GameData.port_show_part(
  562. self.this_sector,
  563. self.game.gamedata.ports[self.this_sector],
  564. )
  565. )
  566. + self.nl
  567. )
  568. for i, p in enumerate(self.possible):
  569. self.queue_game.put(
  570. " "
  571. + Fore.CYAN
  572. + str(i + 1)
  573. + " : "
  574. + GameData.port_show_part(p, self.game.gamedata.ports[p])
  575. + self.nl
  576. )
  577. pi = PlayerInput(self.game)
  578. def got_need1(*_):
  579. log.debug("Ok, I have: {0}".format(pi.keep))
  580. if pi.keep["count"].strip() == "":
  581. self.deactivate()
  582. return
  583. self.times_left = int(pi.keep["count"])
  584. if pi.keep["choice"].strip() == "":
  585. self.deactivate()
  586. return
  587. c = int(pi.keep["choice"]) - 1
  588. if c < 0 or c >= len(self.possible):
  589. self.deactivate()
  590. return
  591. self.sector2 = self.possible[int(pi.keep["choice"]) - 1]
  592. # self.queue_game.put(pformat(pi.keep).replace("\n", "\n\r"))
  593. self.state = 5
  594. self.trade()
  595. d = pi.prompt("Choose -=>", 5, name="choice", digits=True)
  596. d.addCallback(
  597. lambda ignore: pi.prompt(
  598. "Times to execute script:", 5, name="count", digits=True
  599. )
  600. )
  601. d.addCallback(got_need1)
  602. else:
  603. # We already have our target port, so...
  604. self.queue_game.put(
  605. self.r
  606. + self.nl
  607. + "Trading from {0} ({1}) to default {2} ({3}).".format(
  608. self.this_sector,
  609. self.game.gamedata.ports[self.this_sector]["port"],
  610. self.sector2,
  611. self.game.gamedata.ports[self.sector2]["port"],
  612. )
  613. + self.nl
  614. )
  615. self.queue_game.put(
  616. self.r
  617. + self.nl
  618. + "Trading {0}".format(
  619. self.game.gamedata.port_trade_show(
  620. self.this_sector, self.sector2, 0
  621. )
  622. )
  623. )
  624. pi = PlayerInput(self.game)
  625. def got_need2(*_):
  626. if pi.keep["count"].strip() == "":
  627. self.deactivate()
  628. return
  629. self.times_left = int(pi.keep["count"])
  630. log.debug("Ok, I have: {0}".format(pi.keep))
  631. # self.queue_game.put(pformat(pi.keep).replace("\n", "\n\r"))
  632. self.state = 5
  633. self.trade()
  634. self.queue_game.put(self.r + self.nl)
  635. default_turns = self.game.gamedata.get_config("Trade_Turns", "0")
  636. if default_turns == "0":
  637. # No default given, ask.
  638. d = pi.prompt("Times to execute script", 5, name="count")
  639. d.addCallback(got_need2)
  640. else:
  641. try:
  642. self.times_left = int(default_turns)
  643. except ValueError:
  644. self.times_left = 30
  645. self.state = 5
  646. self.trade()
  647. elif self.state == 6:
  648. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  649. if self.end_trans:
  650. self.deactivate()
  651. return
  652. if self.fixable:
  653. # self.queue_game.put("Ok! Let's fix this by going to the other sector..." + self.nl)
  654. self.queue_game.put(
  655. self.nl
  656. + Boxes.alert(
  657. "Ok, FINE. We'll trade with the other port.",
  658. base="green",
  659. style=0,
  660. )
  661. )
  662. log.debug("Fixing...")
  663. # Swap this and other sector
  664. self.this_sector, self.other_sector = (
  665. self.other_sector,
  666. self.this_sector,
  667. )
  668. self.queue_player.put("{0}\r".format(self.sector2))
  669. self.state = 5
  670. self.trade()
  671. elif self.state == 7:
  672. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  673. # Done
  674. if self.end_trans:
  675. self.deactivate()
  676. return
  677. # Swap this and other sector
  678. self.this_sector, self.other_sector = (
  679. self.other_sector,
  680. self.this_sector,
  681. )
  682. if self.this_sector == self.sector2:
  683. self.times_left -= 1
  684. if self.times_left <= 0:
  685. # Ok, exit out
  686. self.deactivate()
  687. return
  688. if self.last_credits is None:
  689. self.last_credits = self.credits
  690. else:
  691. if self.credits <= self.last_credits:
  692. log.warn("We don't seem to be making any money here...")
  693. self.queue_game.put(
  694. self.r
  695. + self.nl
  696. + "We don't seem to be making any money here. I'm stopping!"
  697. + self.nl
  698. )
  699. self.deactivate()
  700. return
  701. self.queue_player.put("{0}\r".format(self.this_sector))
  702. self.state = 10
  703. elif re.match(r"Your offer \[\d+\] \?", prompt):
  704. log.info("Your offer? [{0}]".format(self.fix_offer))
  705. if self.fix_offer:
  706. # Make real offer / WHAT?@?!
  707. work = prompt.replace(",", "")
  708. parts = re.split(r"\s+", work)
  709. amount = parts[2]
  710. # Ok, we have the amount, now to figure pct...
  711. if self.sell_percent > 100:
  712. self.sell_percent -= 1
  713. else:
  714. self.sell_percent += 1
  715. price = amount * self.sell_percent // 100
  716. log.debug(
  717. "start: {0} % {1} price {2}".format(
  718. amount, self.sell_percent, price
  719. )
  720. )
  721. if self.sell_percent > 100:
  722. self.sell_percent -= 1
  723. else:
  724. self.sell_percent += 1
  725. self.queue_player.put("{0}\r".format(price))
  726. # elif re.match(r"How many holds of .+ do you want to sell \[\d+\]\?", prompt):
  727. # log.info("Sell everything we can...")
  728. # this seems to screw up the sync of everything.
  729. # self.queue_player.put("\r")
  730. elif self.state == 8:
  731. # What are we trading
  732. # How many holds of Equipment do you want to buy [75]?
  733. if re.match(r"How many holds of .+ do you want to buy \[\d+\]\?", prompt):
  734. parts = prompt.split()
  735. trade_type = parts[4]
  736. log.info("Buy {0} [{1} ~ {2}]".format(trade_type, self.tpc, self.opc))
  737. if trade_type == "Fuel":
  738. if (self.tpc in (5, 7)) and (self.opc in (2, 3, 4, 8)):
  739. # Can buy equipment - fuel ore is worthless.
  740. self.queue_player.put("0\r")
  741. return
  742. if (self.tpc in (4, 7)) and (self.opc in (1, 3, 5, 8)):
  743. # Can buy organics - fuel ore is worthless.
  744. self.queue_player.put("0\r")
  745. return
  746. if (self.tpc in (4, 7, 3, 5)) and (self.opc in (3, 4, 5, 7)):
  747. # No point in buying fuel ore if it can't be sold.
  748. self.queue_player.put("0\r")
  749. return
  750. elif trade_type == "Organics":
  751. if (self.tpc in (6, 7)) and (self.opc in (2, 3, 4, 8)):
  752. # Can buy equipment - organics is worthless.
  753. self.queue_player.put("0\r")
  754. return
  755. if (self.tpc in (2, 4, 6, 7)) and (self.opc in (2, 4, 6, 7)):
  756. # No point in buying organics if it can't be sold.
  757. self.queue_player.put("0\r")
  758. return
  759. elif trade_type == "Equipment":
  760. if self.opc in (1, 5, 6, 7):
  761. # No point in buying equipment if it can't be sold.
  762. self.queue_player.put("0\r")
  763. return
  764. self.queue_player.put("\r")
  765. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  766. # Done
  767. if self.end_trans:
  768. self.deactivate()
  769. return
  770. # Swap this and other sector
  771. self.this_sector, self.other_sector = (
  772. self.other_sector,
  773. self.this_sector,
  774. )
  775. if self.this_sector == self.sector2:
  776. self.times_left -= 1
  777. if self.times_left <= 0:
  778. # Ok, exit out
  779. self.deactivate()
  780. return
  781. if self.last_credits is None:
  782. self.last_credits = self.credits
  783. else:
  784. if self.credits <= self.last_credits:
  785. log.warn("We don't seem to be making any money here...")
  786. self.queue_game.put(
  787. self.r
  788. + self.nl
  789. + "We don't seem to be making any money here. I'm stopping!"
  790. + self.nl
  791. )
  792. self.deactivate()
  793. return
  794. self.queue_player.put("{0}\r".format(self.this_sector))
  795. self.state = 10
  796. elif self.state == 10:
  797. # DANGER! You have marked sector X to be avoided!
  798. if prompt.startswith("Do you really want to warp there? (Y/N) "):
  799. self.queue_player.put("Y")
  800. elif self.state == 99:
  801. # This is a good place to deactivate at.
  802. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  803. if hasattr(self, "message"):
  804. if self.message is not None:
  805. self.queue_game.put(self.message)
  806. self.message = None
  807. self.deactivate()
  808. def trade(self, *_):
  809. # state 5
  810. log.debug("trade!")
  811. self.queue_player.put("pt") # Port Trade
  812. self.end_trans = False
  813. self.fixable = False
  814. self.this_port = self.game.gamedata.ports[self.this_sector]
  815. # I think other_sector will alway be correct, but leaving this
  816. # for now. FUTURE: TODO: REMOVE
  817. if self.this_sector == self.sector1:
  818. self.other_sector = self.sector2
  819. else:
  820. self.other_sector = self.sector1
  821. self.other_port = self.game.gamedata.ports[self.other_sector]
  822. # Ok, perform some calculations
  823. self.tpc = self.this_port["class"]
  824. self.opc = self.other_port["class"]
  825. self.fixable = 0
  826. self.fix_offer = 0
  827. # [ Items Status Trading % of max OnBoard]
  828. # [ ----- ------ ------- -------- -------]
  829. # [Fuel Ore Selling 2573 93% 0]
  830. # [Organics Buying 2960 100% 0]
  831. # [Equipment Buying 1958 86% 0]
  832. # []
  833. # []
  834. # [You have 1,000 credits and 20 empty cargo holds.]
  835. # []
  836. # [We are selling up to 2573. You have 0 in your holds.]
  837. # [How many holds of Fuel Ore do you want to buy [20]? 0]
  838. def game_line(self, line: str):
  839. if line.startswith("You have ") and "credits and" in line:
  840. parts = line.replace(",", "").split()
  841. credits = int(parts[2])
  842. log.debug("Credits: {0}".format(credits))
  843. self.credits = credits
  844. if self.state == 1:
  845. # First exploration
  846. if line.startswith("Sector :"):
  847. # We have starting sector information
  848. parts = re.split(r"\s+", line)
  849. self.this_sector = int(parts[2])
  850. # These will be the ones swapped around as we trade back and forth.
  851. self.sector1 = self.this_sector
  852. elif line.startswith("Warps to Sector(s) : "):
  853. # Warps to Sector(s) : 397 - (562) - (639)
  854. _, _, warps = line.partition(":")
  855. warps = warps.replace("-", "").replace("(", "").replace(")", "").strip()
  856. log.debug("Warps: [{0}]".format(warps))
  857. self.warps = [int(x) for x in re.split(r"\s+", warps)]
  858. log.debug("Warps: [{0}]".format(self.warps))
  859. self.state = 2
  860. elif self.state == 2:
  861. if line == "":
  862. # Ok, we're done
  863. self.state = 3
  864. # Check to see if we have information on any possible ports
  865. # if hasattr(self.game, 'portdata'):
  866. if True:
  867. if not self.this_sector in self.game.gamedata.ports:
  868. self.state = 0
  869. log.debug(
  870. "Current sector {0} not in portdata.".format(
  871. self.this_sector
  872. )
  873. )
  874. self.queue_game.put(
  875. self.r
  876. + self.nl
  877. + "I can't find the current sector in the portdata."
  878. + self.nl
  879. )
  880. self.deactivate()
  881. return
  882. else:
  883. # Ok, we are in the portdata
  884. pd = self.game.gamedata.ports[self.this_sector]
  885. if GameData.port_burnt(pd):
  886. log.debug(
  887. "Current sector {0} port is burnt (<= 20%).".format(
  888. self.this_sector
  889. )
  890. )
  891. self.queue_game.put(
  892. self.r
  893. + self.nl
  894. + "Current sector port is burnt out. <= 20%."
  895. + self.nl
  896. )
  897. self.deactivate()
  898. return
  899. possible = [x for x in self.warps if x in self.game.gamedata.ports]
  900. log.debug("Possible: {0}".format(possible))
  901. # BUG: Sometimes links to another sector, don't link back!
  902. # This causes the game to plot a course / autopilot.
  903. # if hasattr(self.game, 'warpdata'):
  904. if True:
  905. # Great! verify that those warps link back to us!
  906. possible = [
  907. x
  908. for x in possible
  909. if x in self.game.gamedata.warps
  910. and self.this_sector in self.game.gamedata.warps[x]
  911. ]
  912. if len(possible) == 0:
  913. self.state = 0
  914. self.queue_game.put(
  915. self.r
  916. + self.nl
  917. + "I don't see any ports in [{0}].".format(self.warps)
  918. + self.nl
  919. )
  920. self.deactivate()
  921. return
  922. possible = [
  923. x
  924. for x in possible
  925. if not GameData.port_burnt(self.game.gamedata.ports[x])
  926. ]
  927. log.debug("Possible: {0}".format(possible))
  928. if len(possible) == 0:
  929. self.state = 0
  930. self.queue_game.put(
  931. self.r
  932. + self.nl
  933. + "I don't see any unburnt ports in [{0}].".format(
  934. self.warps
  935. )
  936. + self.nl
  937. )
  938. self.deactivate()
  939. return
  940. possible = [
  941. x
  942. for x in possible
  943. if GameData.port_trading(
  944. self.game.gamedata.ports[self.this_sector]["port"],
  945. self.game.gamedata.ports[x]["port"],
  946. )
  947. ]
  948. # sort by best, then by %
  949. start_port = self.game.gamedata.ports[self.this_sector]
  950. if "port" in start_port:
  951. start_port_port = start_port["port"]
  952. start_with = start_port_port[1:]
  953. if start_with in ("BS", "SB"):
  954. # Ok, good trades may be possible
  955. best = GameData.flip(start_with)
  956. log.info("Sorting the best ({0}) to the top.".format(best))
  957. log.info("{0}".format(possible))
  958. dec = [
  959. [
  960. self.game.gamedata.ports[p].get("port", "---")[1:]
  961. == best,
  962. p,
  963. ]
  964. for p in possible
  965. ]
  966. dec = sorted(dec, reverse=True)
  967. possible = [x[1] for x in dec]
  968. log.info("{0}".format(possible))
  969. self.possible = possible
  970. if len(possible) == 0:
  971. self.state = 0
  972. self.queue_game.put(
  973. self.r
  974. + self.nl
  975. + "I don't see any possible port trades in [{0}].".format(
  976. self.warps
  977. )
  978. + self.nl
  979. )
  980. self.deactivate()
  981. return
  982. elif len(possible) == 1:
  983. # Ok! there's only one!
  984. self.sector2 = possible[0]
  985. # Display possible ports:
  986. # spos = [ str(x) for x in possible]
  987. # self.queue_game.put(self.r + self.nl + self.nl.join(spos) + self.nl)
  988. # At state 3, we only get a prompt.
  989. return
  990. else:
  991. self.state = 0
  992. log.warn("We don't have any portdata!")
  993. self.queue_game.put(
  994. self.r
  995. + self.nl
  996. + "I have no portdata. Please run CIM Port Report."
  997. + self.nl
  998. )
  999. self.deactivate()
  1000. return
  1001. elif self.state == 5:
  1002. if "-----" in line:
  1003. self.state = 6
  1004. elif self.state == 6:
  1005. if "We are buying up to" in line:
  1006. log.info("buying up to -- so sell all")
  1007. # Sell
  1008. self.state = 7
  1009. self.queue_player.put("\r")
  1010. self.sell_percent = 100 + self.percent
  1011. if "We are selling up to" in line:
  1012. log.info("selling up to -- state 8 / set percent")
  1013. # Buy
  1014. self.state = 8
  1015. self.sell_percent = 100 - self.percent
  1016. if (
  1017. line.startswith("Fuel Ore")
  1018. or line.startswith("Organics")
  1019. or line.startswith("Equipment")
  1020. ):
  1021. work = line.replace("Fuel Ore", "Fuel").replace("%", "")
  1022. parts = re.split(r"\s+", work)
  1023. # log.debug(parts)
  1024. # Equipment, Selling xxx x% xxx
  1025. if parts[-1] != "0" and parts[2] != "0" and parts[1] != "Buying":
  1026. log.warn(
  1027. "We have a problem -- they aren't buying what we have in stock!"
  1028. )
  1029. stuff = line[0] # F O or E.
  1030. if self.game.gamedata.port_buying(self.other_sector, stuff):
  1031. log.info("fixable")
  1032. self.fixable = True
  1033. if int(parts[3]) < self.stop:
  1034. log.info("Port is burnt! % < {0} (end_trans)".format(self.stop))
  1035. self.end_trans = True
  1036. if "You don't have anything they want" in line:
  1037. log.warn("Don't have anything they want.")
  1038. # Neither! DRAT!
  1039. if not self.fixable:
  1040. self.state = 99
  1041. return
  1042. if "We're not interested." in line:
  1043. log.warn("Try, try again. :(")
  1044. self.state = 5
  1045. self.trade()
  1046. elif self.state == 7:
  1047. # Haggle Sell
  1048. if "We'll buy them for" in line or "Our final offer" in line:
  1049. if "Our final offer" in line:
  1050. self.sell_percent -= 1
  1051. parts = line.replace(",", "").split()
  1052. start_price = int(parts[4])
  1053. price = start_price * self.sell_percent // 100
  1054. log.debug(
  1055. "start: {0} % {1} price {2}".format(
  1056. start_price, self.sell_percent, price
  1057. )
  1058. )
  1059. self.sell_percent -= 1
  1060. self.queue_player.put("{0}\r".format(price))
  1061. if "We are selling up to" in line:
  1062. log.info("selling up to / state 8 / set percent")
  1063. # Buy
  1064. self.state = 8
  1065. self.sell_percent = 100 - self.percent
  1066. if "We are buying up to" in line:
  1067. log.info("buying up to -- so sell all")
  1068. # Sell
  1069. self.state = 7
  1070. self.queue_player.put("\r")
  1071. self.sell_percent = 100 + self.percent
  1072. if "We're not interested." in line:
  1073. log.info("Not interested. Try, try again. :(")
  1074. self.state = 5
  1075. self.trade()
  1076. if "WHAT?!@!? you must be crazy!" in line:
  1077. log.warn("fix offer")
  1078. self.fix_offer = 1
  1079. if "So, you think I'm as stupid as you look?" in line:
  1080. log.warn("fix offer")
  1081. self.fix_offer = 1
  1082. if "Quit playing around, you're wasting my time!" in line:
  1083. log.warn("fix offer")
  1084. self.fix_offer = 1
  1085. elif self.state == 8:
  1086. # Haggle Buy
  1087. if "We'll sell them for" in line or "Our final offer" in line:
  1088. if "Our final offer" in line:
  1089. self.sell_percent += 1
  1090. parts = line.replace(",", "").split()
  1091. start_price = int(parts[4])
  1092. price = start_price * self.sell_percent // 100
  1093. log.debug(
  1094. "start: {0} % {1} price {2}".format(
  1095. start_price, self.sell_percent, price
  1096. )
  1097. )
  1098. self.sell_percent += 1
  1099. self.queue_player.put("{0}\r".format(price))
  1100. if "We're not interested." in line:
  1101. log.info("Not interested. Try, try again. :(")
  1102. self.state = 5
  1103. self.trade()
  1104. elif self.state == 10:
  1105. if "Sector : " in line:
  1106. # Trade
  1107. self.state = 5
  1108. reactor.callLater(0, self.trade, 0)
  1109. # self.trade()
  1110. # elif self.state == 3:
  1111. # log.debug("At state 3 [{0}]".format(line))
  1112. # self.queue_game.put("At state 3.")
  1113. # self.deactivate()
  1114. # return
  1115. class ScriptExplore(object):
  1116. """ Exploration Script
  1117. WARNINGS:
  1118. We assume the player has lots o turns, or unlimited turns!
  1119. """
  1120. def __init__(self, game):
  1121. self.game = game
  1122. self.queue_game = game.queue_game
  1123. self.queue_player = game.queue_player
  1124. self.observer = game.observer
  1125. self.r = Style.RESET_ALL
  1126. self.c = merge(Style.BRIGHT + Fore.YELLOW)
  1127. self.nl = "\n\r"
  1128. # Our Stuff, Not our pants!
  1129. self.dense = [] # We did a density, store that info.
  1130. self.clear = [] # Warps that we know are clear.
  1131. self.highsector = 0 # Selected Sector to move to next!
  1132. self.highwarp = 0 # Selected Sector's Warp Count!
  1133. self.stacksector = (
  1134. []
  1135. ) # Set of sectors that we have not picked but are unexplored... even though we did a holo!
  1136. self.oneMoveSector = False
  1137. self.times = 0
  1138. self.maxtimes = 0
  1139. # Activate
  1140. self.prompt = game.buffer
  1141. self.save = self.observer.save()
  1142. self.observer.connect("player", self.player)
  1143. self.observer.connect("prompt", self.game_prompt)
  1144. self.observer.connect("game-line", self.game_line)
  1145. self.prefer_ports = (
  1146. self.game.gamedata.get_config("Explorer_PrefPorts", "N").upper()[0] == "Y"
  1147. )
  1148. self.defer = None
  1149. self.send2player(Boxes.alert("Explorer", base="green"))
  1150. # How many times we going to go today?
  1151. ask = PlayerInput(self.game)
  1152. def settimes(*_):
  1153. times = ask.keep["times"].strip()
  1154. log.debug("settimes got '{0}'".format(times))
  1155. if times == "":
  1156. self.deactivate()
  1157. else:
  1158. times = int(times)
  1159. self.times = times
  1160. self.maxtimes = times
  1161. self.send2game("D")
  1162. log.debug("times: {0} maxtimes: {0}".format(self.times))
  1163. self.state = 1
  1164. d = ask.prompt(
  1165. "How many sectors would you like to explorer?", 5, name="times", digits=True
  1166. )
  1167. # d.addCallback(ask.output)
  1168. # d.addCallback(lambda ignore: self.settimes(ask.keep))
  1169. d.addCallback(settimes)
  1170. def whenDone(self):
  1171. self.defer = defer.Deferred()
  1172. # Call this to chain something after we exit.
  1173. return self.defer
  1174. def deactivate(self, andExit=False):
  1175. self.state = 0
  1176. log.debug("ScriptExplore.deactivate()")
  1177. assert not self.save is None
  1178. self.observer.load(self.save)
  1179. self.save = None
  1180. if self.defer:
  1181. if andExit:
  1182. self.defer.callback({"exit": True})
  1183. else:
  1184. self.defer.callback("done")
  1185. self.defer = None
  1186. def player(self, chunk: bytes):
  1187. # If we receive anything -- ABORT!
  1188. self.deactivate(True)
  1189. def send2game(self, txt):
  1190. log.debug("ScriptExplore.send2game({0})".format(txt))
  1191. self.queue_player.put(txt)
  1192. def send2player(self, txt):
  1193. log.debug("ScriptExplore.send2player({0})".format(txt))
  1194. self.queue_game.put(txt)
  1195. def resetStuff(self):
  1196. self.dense = []
  1197. self.clear = []
  1198. self.highwarp = 0
  1199. self.highsector = 0
  1200. log.debug("ScriptExplore.resetStuff()")
  1201. def dead_end(self):
  1202. """ We've reached a dead end.
  1203. Either pop a new location to travel to, or give it up.
  1204. """
  1205. self.send2player(self.nl + Boxes.alert("** DEAD END **", base="blue"))
  1206. if self.stacksector:
  1207. # Ok, there's somewhere to go ...
  1208. self.highsector = self.stacksector.pop()
  1209. # travel state
  1210. self.state = 10
  1211. self.send2game("{0}\r".format(self.highsector))
  1212. else:
  1213. self.send2player(
  1214. self.nl
  1215. + Boxes.alert(
  1216. "I've run out of places to look ({0}/{1}).".format(
  1217. self.maxtimes - self.times, self.maxtimes
  1218. )
  1219. )
  1220. )
  1221. self.deactivate(True)
  1222. def game_over(self, msg):
  1223. self.send2player(
  1224. self.nl
  1225. + Boxes.alert(
  1226. "STOP: {0} ({1}/{2}).".format(
  1227. msg, self.maxtimes - self.times, self.maxtimes
  1228. )
  1229. )
  1230. )
  1231. self.deactivate()
  1232. def game_prompt(self, prompt: str):
  1233. log.debug("{0} : {1}".format(self.state, prompt))
  1234. if self.state == 2:
  1235. if "Select (H)olo Scan or (D)ensity Scan or (Q)uit" in prompt:
  1236. self.send2game("D")
  1237. # self.state += 1
  1238. elif self.state == 5:
  1239. log.debug("dense is {0} sectors big".format(len(self.dense)))
  1240. self.state += 1
  1241. self.send2game("SH")
  1242. elif self.state == 10:
  1243. if prompt.startswith("Do you want to engage the TransWarp drive? "):
  1244. self.send2game("N")
  1245. elif self.state == 12:
  1246. # Looking for "Engage the Autopilot?"
  1247. if prompt.startswith("Engage the Autopilot? (Y/N/Single step/Express) [Y]"):
  1248. self.send2game("S")
  1249. self.travel_path.pop(0)
  1250. if prompt.startswith(
  1251. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N]"
  1252. ):
  1253. self.send2game("SD")
  1254. self.state += 1
  1255. # Arriving sector :1691 Autopilot disengaging.
  1256. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  1257. log.info("We made it to where we wanted to go!")
  1258. # can't init state 1, because we're at a prompt, so...
  1259. self.send2game("S")
  1260. self.state = 2
  1261. return
  1262. elif self.state == 15:
  1263. if prompt.startswith(
  1264. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N]"
  1265. ):
  1266. self.send2game("N")
  1267. self.travel_path.pop(0)
  1268. self.state = 12
  1269. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  1270. log.info("We made it to where we wanted to go!")
  1271. # can't init state 1, because we're at a prompt, so...
  1272. self.send2game("S")
  1273. self.state = 2
  1274. return
  1275. elif self.state == 20:
  1276. if prompt.startswith(
  1277. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N]"
  1278. ):
  1279. # Stop in this sector / Yes!
  1280. self.send2game("Y")
  1281. self.state = 1
  1282. # this should re-trigger a scan
  1283. def game_line(self, line: str):
  1284. log.debug("{0} | {1}".format(self.state, line))
  1285. # if "Mine Control" in line: # If we don't have a Holo-Scanner and we attempted to do a Holo-scan, abort
  1286. # self.deactivate()
  1287. if line.startswith("You don't have enough turns left."):
  1288. self.send2player(self.nl + Boxes.alert("You're out of turns!"))
  1289. self.deactivate(True)
  1290. return
  1291. if self.state == 1:
  1292. if line.startswith("You have ") and "turns left." in line:
  1293. # Ok, you're in trouble!
  1294. self.send2player(self.nl + Boxes.alert("You're running low on turns!"))
  1295. self.deactivate(True)
  1296. return
  1297. self.send2game("S")
  1298. self.state += 1
  1299. elif self.state == 2:
  1300. if "Relative Density Scan" in line:
  1301. self.state = 3
  1302. elif "You don't have a long range scanner." in line:
  1303. log.warn("FATAL: No Long Range Scanner Installed!")
  1304. self.send2player(Boxes.alert("You need a Long Range Scanner!"))
  1305. self.deactivate(True)
  1306. return
  1307. # elif "Long Range Scan" in line:
  1308. # self.state += 1
  1309. elif self.state == 3:
  1310. # Get the Density Data!
  1311. if line.startswith("Sector"):
  1312. new_sector = "(" in line
  1313. work = (
  1314. line.replace(":", "")
  1315. .replace(")", "")
  1316. .replace("(", "")
  1317. .replace("%", "")
  1318. .replace("==>", "")
  1319. )
  1320. work = re.split(r"\s+", work)
  1321. log.debug(work)
  1322. # 'Sector', '8192', '0', 'Warps', '4', 'NavHaz', '0', 'Anom', 'No'
  1323. # 'Sector', '(', '8192)', '0', 'Warps', '4', 'NavHaz', '0', 'Anom', 'No'
  1324. # New Sector?
  1325. if new_sector:
  1326. # Switch Anom into bool state
  1327. # if(work[8] == 'No'):
  1328. # temp = False
  1329. # else:
  1330. # temp = True
  1331. # self.dense.append( {'sector': int(work[1]), 'density': int(work[2]), 'warps': int(work[4]), 'navhaz': int(work[6]), 'anom': temp} )
  1332. self.dense.append(
  1333. {
  1334. "sector": int(work[1]),
  1335. "density": int(work[2]),
  1336. "warps": int(work[4]),
  1337. "navhaz": int(work[6]),
  1338. "anom": work[8] == "Yes",
  1339. }
  1340. )
  1341. log.debug(self.dense)
  1342. # {'sector': 8192, 'density': 0, 'warps': 4, 'navhaz': 0, 'anom': False}
  1343. elif line == "":
  1344. self.state += 1
  1345. # yeah, this would be better in the above line...
  1346. # leaving it for now.
  1347. # Which is why I broke the elif chain. ...
  1348. if self.state == 4:
  1349. # Begin Processing our data we got from density scan and find highest warp count in what sectors
  1350. # Remove sectors with one warp
  1351. log.debug("state 4: {0}".format(self.dense))
  1352. # Do we have a new place to go? (That is also worth going to)
  1353. if not self.dense: # Dense contains no new sectors, abort
  1354. log.info("No New Sectors Found!")
  1355. self.dead_end()
  1356. return
  1357. # Is the sector safe to go into?
  1358. # self.clear = [ x['sector'] for x in self.dense if not x['anom'] and not x['navhaz'] and x['density'] in (0,1,100,101) and x['warps'] > 1 ]
  1359. self.clear = [
  1360. x
  1361. for x in self.dense
  1362. if not x["anom"]
  1363. and not x["navhaz"]
  1364. and x["density"] in (0, 1, 100, 101)
  1365. ]
  1366. if self.clear: # We have sector(s) we can move to!
  1367. log.debug("Clear Sectors: {0}".format(len(self.clear)))
  1368. # This was state 5 but why can't we reduce number of states? ( Yeah let's kick California and New York out of the US, oh wrong states :P )
  1369. # Sort to find greatest warp count
  1370. if self.prefer_ports:
  1371. _, self.highwarp, self.highsector = max(
  1372. (x["density"], x["warps"], x["sector"]) for x in self.clear
  1373. )
  1374. else:
  1375. self.highwarp, self.highsector = max(
  1376. (x["warps"], x["sector"]) for x in self.clear
  1377. )
  1378. log.info(
  1379. "Sector: {0:5d} Warps: {1}".format(self.highsector, self.highwarp)
  1380. )
  1381. self.state += 1
  1382. else:
  1383. log.warn("No (safe) sectors to move to!")
  1384. # Let's try this?!
  1385. # self.dead_end() # NO!
  1386. self.game_over("No SAFE moves.")
  1387. # Another NOP state. This also could be merged into above.
  1388. # break the elif chain.
  1389. if self.state == 5:
  1390. # Add the dense scan of unknown sectors onto the stack of sectors, only save the ones we think are clear... for now.
  1391. for c in self.clear:
  1392. sector = c["sector"]
  1393. if sector != self.highsector:
  1394. if sector not in self.stacksector:
  1395. self.stacksector.append(sector)
  1396. # Or simply not add it in the first place ...
  1397. # Remove the sector we are just about to go to, we use discard so if the sector does not exist we don't throw a error!
  1398. # self.stacksector.discard(self.highsector)
  1399. # Ok, we need to decide to stop exploring -- before we
  1400. # issue the sector move! :P
  1401. #
  1402. # Warning! Yes we can and will eat all the turns! :P
  1403. if self.times == 0:
  1404. self.send2player(
  1405. Boxes.alert("Completed {0}".format(self.maxtimes), base="green")
  1406. )
  1407. log.info("Completed {0}".format(self.maxtimes))
  1408. self.deactivate()
  1409. return
  1410. self.times -= 1
  1411. # Ok we know the sector we want to go to now let's move it!
  1412. self.send2game("m{0}\r".format(self.highsector))
  1413. if self.highsector in self.stacksector:
  1414. log.info("Removing {0} from stacksector list.".format(self.highsector))
  1415. self.stacksector.remove(self.highsector)
  1416. # Reset Variables for fresh data
  1417. self.resetStuff()
  1418. self.state = 1
  1419. elif self.state == 10:
  1420. if line.startswith("You are already in that sector!"):
  1421. log.info("Already here. (Whoops!)")
  1422. self.state = 1
  1423. return
  1424. if line.startswith("Sector : {0}".format(self.highsector)):
  1425. log.info("We're here!")
  1426. # Ok, we're already there! no autopilot needed!
  1427. self.state = 1
  1428. return
  1429. # Warping
  1430. self.go_on = True
  1431. if line.startswith("The shortest path ("):
  1432. # Ok, we've got a path.
  1433. self.state += 1
  1434. self.travel_path = []
  1435. elif self.state == 11:
  1436. if line == "":
  1437. # The end of the (possibly) multiline warp.
  1438. self.state += 1
  1439. self.travel_path.pop(0) # First sector is one we're in.
  1440. self.stophere = False
  1441. self.go_on = True
  1442. else:
  1443. self.travel_path.extend(
  1444. line.replace("(", "").replace(")", "").split(" > ")
  1445. )
  1446. log.debug("Travel path: {0}".format(self.travel_path))
  1447. elif self.state == 12:
  1448. # Arriving sector :1691 Autopilot disengaging.
  1449. if "Autopilot disengaging." in line:
  1450. log.info("We made it to where we wanted to go!")
  1451. self.state = 1
  1452. return
  1453. elif self.state == 13:
  1454. if "Relative Density Scan" in line:
  1455. self.state += 1
  1456. elif self.state == 14:
  1457. if line == "":
  1458. log.debug("PATH: {0}".format(self.travel_path))
  1459. # end of the scan, decision time
  1460. if self.stophere:
  1461. log.info("STOPHERE")
  1462. # Ok, let's stop here!
  1463. # Re-save the sector we were trying to get to. (we didn't make it there)
  1464. if self.highsector not in self.stacksector:
  1465. self.stacksector.append(self.highsector)
  1466. self.state = 20
  1467. else:
  1468. if self.go_on:
  1469. log.info("GO ON")
  1470. # Ok, carry on!
  1471. self.state = 15
  1472. else:
  1473. log.warn("Our way is blocked...")
  1474. if self.highsector not in self.stacksector:
  1475. self.stacksector.append(self.highsector)
  1476. self.state = 20
  1477. else:
  1478. if line.strip("-") != "":
  1479. work = (
  1480. line.replace(" :", "")
  1481. .replace("%", "")
  1482. .replace(")", "")
  1483. .replace("==>", "")
  1484. )
  1485. # Does this contain something new? unseen?
  1486. stophere = "(" in work
  1487. work = work.replace("(", "")
  1488. # Sector XXXX DENS Warps N NavHaz P Anom YN
  1489. parts = re.split(r"\s+", work)
  1490. # Don't bother stopping if there's only one warp
  1491. # YES! Stop, even if there is just one warp!
  1492. # if stophere and parts[4] == '1':
  1493. # stophere = False
  1494. if stophere:
  1495. self.stophere = True
  1496. next_stop = self.travel_path[0]
  1497. log.debug(
  1498. "next_stop {0} from {1}".format(next_stop, self.travel_path)
  1499. )
  1500. log.debug("parts: {0}".format(parts))
  1501. if parts[1] == next_stop:
  1502. log.info("next_stop {0} found...".format(next_stop))
  1503. # Ok, this is our next stop. Is it safe to travel to?
  1504. if parts[2] not in ("100", "0", "1", "101"):
  1505. # Ok, it's not safe to go on.
  1506. self.go_on = False
  1507. # Check the rest navhav and anom ...
  1508. class ScriptSpace(object):
  1509. """ Space Exploration script.
  1510. Send "SD", verify paths are clear.
  1511. Find nearest unknown. Sector + CR.
  1512. Save "shortest path from to" information.
  1513. At 'Engage the Autopilot', Send "S" (Single Step)
  1514. At '[Stop in this sector', Send "SD", verify path is clear.
  1515. Send "SH" (glean sector/port information along the way.)
  1516. Send "N" (Next)!
  1517. Send "SD" / Verify clear.
  1518. Send "SH"
  1519. Repeat for Next closest.
  1520. """
  1521. def __init__(self, game):
  1522. self.game = game
  1523. self.queue_game = game.queue_game
  1524. self.queue_player = game.queue_player
  1525. self.observer = game.observer
  1526. self.r = Style.RESET_ALL
  1527. self.nl = "\n\r"
  1528. self.this_sector = None # Starting sector
  1529. self.target_sector = None # Sector going to
  1530. self.path = []
  1531. self.times_left = 0 # How many times to look for target
  1532. self.density = dict() # Results of density scan. (Just the numbers)
  1533. # Activate
  1534. self.prompt = game.buffer
  1535. self.save = self.observer.save()
  1536. self.observer.connect("player", self.player)
  1537. self.observer.connect("prompt", self.game_prompt)
  1538. self.observer.connect("game-line", self.game_line)
  1539. self.defer = None
  1540. self.queue_game.put(self.nl + "Bugz (like space), is big." + self.r + self.nl)
  1541. self.state = 1
  1542. self.queue_player.put("SD")
  1543. # Get current density scan + also get the current sector.
  1544. # [Command [TL=00:00:00]:[XXXX] (?=Help)? : D]
  1545. def whenDone(self):
  1546. self.defer = defer.Deferred()
  1547. # Call this to chain something after we exit.
  1548. return self.defer
  1549. def deactivate(self, andExit=False):
  1550. self.state = 0
  1551. log.debug("ScriptPort.deactivate ({0})".format(self.times_left))
  1552. assert not self.save is None
  1553. self.observer.load(self.save)
  1554. self.save = None
  1555. if self.defer:
  1556. if andExit:
  1557. self.defer.callback({"exit": True})
  1558. else:
  1559. self.defer.callback("done")
  1560. self.defer = None
  1561. def player(self, chunk: bytes):
  1562. # If we receive anything -- ABORT!
  1563. self.deactivate(True)
  1564. def unknown_search(self, starting_sector):
  1565. seen = set()
  1566. possible = set()
  1567. possible.add(int(starting_sector))
  1568. done = False
  1569. while not done:
  1570. next_possible = set()
  1571. for s in possible:
  1572. p = self.game.gamedata.get_warps(s)
  1573. if p is not None:
  1574. for pos in p:
  1575. if pos not in seen:
  1576. next_possible.add(pos)
  1577. else:
  1578. log.debug("unknown found: {0}".format(s))
  1579. self.unknown = s
  1580. done = True
  1581. break
  1582. seen.add(s)
  1583. if self.unknown is None:
  1584. log.debug("possible: {0}".format(next_possible))
  1585. possible = next_possible
  1586. yield
  1587. def find_unknown(self, starting_sector):
  1588. log.debug("find_unknown( {0})".format(starting_sector))
  1589. d = defer.Deferred()
  1590. # Process things
  1591. self.unknown = None
  1592. c = coiterate(self.unknown_search(starting_sector))
  1593. c.addCallback(lambda unknown: d.callback(self.unknown))
  1594. return d
  1595. def show_unknown(self, sector):
  1596. if sector is None:
  1597. self.deactivate()
  1598. return
  1599. log.debug("Travel to {0}...".format(sector))
  1600. self.queue_player.put("{0}\r".format(sector))
  1601. def game_prompt(self, prompt: str):
  1602. log.debug("{0} : {1}".format(self.state, prompt))
  1603. if self.state == 3:
  1604. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  1605. # this_sector code isn't working -- so! Get sector from prompt
  1606. self.state = 4
  1607. _, _, sector = prompt.partition("]:[")
  1608. sector, _, _ = sector.partition("]")
  1609. self.this_sector = int(sector)
  1610. # Ok, we're done with Density Scan, and we're back at the command prompt
  1611. log.debug("Go find the nearest unknown...")
  1612. d = self.find_unknown(sector)
  1613. d.addCallback(self.show_unknown)
  1614. elif self.state == 6:
  1615. # Engage the autopilot?
  1616. if prompt.startswith("Engage the Autopilot? (Y/N/Single step/Express) [Y]"):
  1617. self.state = 7
  1618. sector = self.path.pop(0)
  1619. if sector in self.density:
  1620. if self.density[sector] in (0, 100):
  1621. # Ok, looks safe!
  1622. self.queue_player.put("S")
  1623. self.this_sector = sector
  1624. else:
  1625. log.warn(
  1626. "FATAL: Density for {0} is {1}".format(
  1627. sector, self.density[sector]
  1628. )
  1629. )
  1630. self.deactivate(True)
  1631. return
  1632. else:
  1633. log.error(
  1634. "{0} not in density scan? (how's that possible?)".format(sector)
  1635. )
  1636. self.deactivate(True)
  1637. return
  1638. elif self.state == 7:
  1639. # Ok, we're in a new sector (single stepping through space)
  1640. # update density scan
  1641. if prompt.startswith(
  1642. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  1643. ):
  1644. self.queue_player.put("SD")
  1645. self.state = 8
  1646. elif self.state == 10:
  1647. # Because we're here
  1648. if prompt.startswith(
  1649. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  1650. ):
  1651. self.queue_player.put("SH")
  1652. self.state = 11
  1653. elif self.state == 11:
  1654. if prompt.startswith(
  1655. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  1656. ):
  1657. # Ok, is the density scan clear?
  1658. sector = self.path.pop(0)
  1659. if sector in self.density:
  1660. if self.density[sector] in (0, 100):
  1661. # Ok, looks safe
  1662. self.queue_player.put("N")
  1663. self.state = 7
  1664. self.this_sector = sector
  1665. else:
  1666. log.warn(
  1667. "FATAL: Density for {0} is {1}".format(
  1668. sector, self.density[sector]
  1669. )
  1670. )
  1671. self.deactivate()
  1672. return
  1673. else:
  1674. log.error(
  1675. "{0} not in density scane? (how's that possible...)".format(
  1676. sector
  1677. )
  1678. )
  1679. self.deactivate()
  1680. return
  1681. def next_unknown(self, sector):
  1682. log.info("Unknown is : {0}".format(sector))
  1683. self.deactivate()
  1684. def game_line(self, line: str):
  1685. log.debug("line {0} : {1}".format(self.state, line))
  1686. if line.startswith("Sector : "):
  1687. work = line.strip()
  1688. parts = re.split(r"\s+", work)
  1689. self.this_sector = int(parts[2])
  1690. log.debug("game_line sector {0}".format(self.this_sector))
  1691. elif line.startswith("Command [TL=]"):
  1692. # Ok, get the current sector from this
  1693. _, _, sector = line.partition("]:[")
  1694. sector, _, _ = sector.partition("]")
  1695. self.this_sector = int(sector)
  1696. log.debug("current sector: {0}".format(self.this_sector))
  1697. elif line.startswith("Warps to Sector(s) :"):
  1698. # Warps to Sector(s) : 5468
  1699. _, _, work = line.partition(":")
  1700. work = work.strip().replace("(", "").replace(")", "").replace(" - ", " ")
  1701. parts = [int(x) for x in work.split(" ")]
  1702. self.path = list(parts)
  1703. if self.state in (1, 8):
  1704. if "Relative Density Scan" in line:
  1705. # Start Density Scan
  1706. self.state += 1
  1707. self.density = {}
  1708. elif self.state in (2, 9):
  1709. if line == "":
  1710. # End of Density Scan
  1711. self.state += 1
  1712. log.debug("Density: {0}".format(self.density))
  1713. # self.deactivate()
  1714. elif line.startswith("Sector"):
  1715. # Parse Density Scan values
  1716. work = (
  1717. line.replace("(", "")
  1718. .replace(")", "")
  1719. .replace(":", "")
  1720. .replace("%", "")
  1721. .replace(",", "")
  1722. )
  1723. parts = re.split(r"\s+", work)
  1724. log.debug("Sector {0}".format(parts))
  1725. sector = int(parts[1])
  1726. self.density[sector] = int(parts[3])
  1727. if parts[7] != "0":
  1728. log.warn("NavHaz {0} : {1}".format(parts[7], work))
  1729. # navhaz already alters density
  1730. # self.density[sector] += 99
  1731. if parts[9] != "No":
  1732. log.warn("Anom {0} : {1}".format(parts[9], work))
  1733. # anom already alters density
  1734. self.density[sector] += 990
  1735. elif self.state == 4:
  1736. # Looking for shortest path message / warp info
  1737. # Or possibly, "We're here!"
  1738. if line.startswith("Sector :") and str(self.unknown) in line:
  1739. # Ok, I'd guess that we're already there!
  1740. # Try it again!
  1741. self.queue_player.put("SD")
  1742. self.state = 1
  1743. if line.startswith("The shortest path"):
  1744. self.state = 5
  1745. elif self.state == 5:
  1746. # This is the warps line
  1747. # Can this be multiple lines?
  1748. if line == "":
  1749. self.state = 6
  1750. else:
  1751. work = line.replace("(", "").replace(")", "").replace(">", "").strip()
  1752. self.path = [int(x) for x in work.split()]
  1753. log.debug("Path: {0}".format(self.path))
  1754. # Verify
  1755. current = self.path.pop(0)
  1756. if current != self.this_sector:
  1757. log.warn("Failed: {0} != {1}".format(current, self.this_sector))
  1758. self.deactivate()
  1759. return
  1760. elif self.state == 7:
  1761. if self.unknown == self.this_sector:
  1762. # We have arrived!
  1763. log.info("We're here!")
  1764. self.deactivate()
  1765. class ScriptTerror(object):
  1766. """ Terror script.
  1767. This uses the Port Trading script.
  1768. Basically, we look for the next best port trading pair.
  1769. Move to it, fire off the Port Trading script.
  1770. Repeat until our loop is done, or there's no more
  1771. pairs.
  1772. Terror_Use:
  1773. 'F' First available/Trade report ordering.
  1774. 'C' Closest trade pair
  1775. state=1 entered sector number to move to.
  1776. state=2 (route "The shortest path")
  1777. Fire ScriptPort. Callback journey_on.
  1778. """
  1779. def __init__(self, game, proxy, count):
  1780. self.game = game
  1781. self.queue_game = game.queue_game
  1782. self.queue_player = game.queue_player
  1783. self.proxy = proxy
  1784. self.count = count
  1785. self.observer = game.observer
  1786. self.r = Style.RESET_ALL
  1787. self.nl = "\n\r"
  1788. self.target_sector = None
  1789. # Activate
  1790. self.prompt = game.buffer
  1791. self.save = self.observer.save()
  1792. self.observer.connect("player", self.player)
  1793. self.observer.connect("prompt", self.game_prompt)
  1794. self.observer.connect("game-line", self.game_line)
  1795. self.state = 0
  1796. self.defer = None
  1797. # Verify that they have configured auto-port trading.
  1798. # Otherwise, this doesn't work!
  1799. usefirst = self.game.gamedata.get_config("Trade_UseFirst")
  1800. if usefirst is None:
  1801. usefirst = "?"
  1802. if usefirst.upper()[0] != "Y":
  1803. self.queue_game.put(
  1804. Boxes.alert("Sorry! You need to config Trade_UseFirst=Y", base="red")
  1805. )
  1806. self.deactivate()
  1807. return
  1808. turns = self.game.gamedata.get_config("Trade_Turns")
  1809. if turns is None:
  1810. turns = "0"
  1811. try:
  1812. t = int(turns)
  1813. except ValueError:
  1814. self.queue_game.put(
  1815. Boxes.alert("Sorry! You need to config Trade_Turns", base="red")
  1816. )
  1817. self.deactivate()
  1818. return
  1819. if t < 5:
  1820. self.queue_game.put(
  1821. Boxes.alert("Sorry! You need to config Trade_Turns >", base="red")
  1822. )
  1823. self.deactivate()
  1824. return
  1825. self.usewhich = self.game.gamedata.get_config("Terror_Use", "F").upper()[0]
  1826. if self.usewhich == "F":
  1827. c = coiterate(self.find_next_good_trade_pair())
  1828. c.addCallback(lambda unknown: self.scary())
  1829. return
  1830. if self.usewhich == "C":
  1831. # Where are we?
  1832. # Command [TL=00:00:00]:[10202] (?=Help)? :
  1833. prompt = self.game.getPrompt()
  1834. _, _, sector = prompt.partition("]:[")
  1835. sector, _, _ = sector.partition("]")
  1836. self.sector = int(sector)
  1837. log.info("find_nearest_tradepairs({0})".format(self.sector))
  1838. c = coiterate(self.game.gamedata.find_nearest_tradepairs(self.sector, self))
  1839. c.addCallback(lambda unknown: self.scary())
  1840. return
  1841. self.queue_game.put(Boxes.alert("What? What?", base="red"))
  1842. self.deactivate()
  1843. def scary(self):
  1844. if self.target_sector is None:
  1845. self.queue_game.put(
  1846. Boxes.alert("Sorry! I don't see any ports to trade with.", base="red")
  1847. )
  1848. self.deactivate()
  1849. else:
  1850. self.state = 1
  1851. self.queue_player.put("{0}\r".format(self.target_sector))
  1852. # This will have to be our best guess. :P
  1853. self.sector = self.target_sector
  1854. def find_next_good_trade_pair(self):
  1855. """ Find the next GOOD trade pair sector.
  1856. This is sequential (just like Trade report)
  1857. """
  1858. # This should be using the setting in the config, not a hard coded value!
  1859. # show_limit (galaxy.port_trade_show) is pct >= show_limit.
  1860. show_limit = self.game.gamedata.get_config("Display_Percent", "90")
  1861. try:
  1862. show_limit = int(show_limit)
  1863. except ValueError:
  1864. show_limit = 90
  1865. if show_limit < 15:
  1866. show_limit = 15
  1867. if show_limit > 90:
  1868. show_limit = 90
  1869. # Look for "GOOD" trades
  1870. for sector in sorted(self.game.gamedata.ports.keys()):
  1871. pd = self.game.gamedata.ports[sector]
  1872. if not GameData.port_burnt(pd):
  1873. # This happens when you trade with a StarDock
  1874. if "class" not in pd:
  1875. continue
  1876. pc = pd["class"]
  1877. # Ok, let's look into it.
  1878. if not sector in self.game.gamedata.warps:
  1879. continue
  1880. # Busted port
  1881. if not sector in self.game.gamedata.busts:
  1882. continue
  1883. warps = self.game.gamedata.warps[sector]
  1884. for w in warps:
  1885. # We can get there, and get back.
  1886. if (
  1887. w in self.game.gamedata.warps
  1888. and sector in self.game.gamedata.warps[w]
  1889. ):
  1890. # Ok, we can get there -- and get back!
  1891. if (
  1892. w > sector
  1893. and w in self.game.gamedata.ports
  1894. and not GameData.port_burnt(self.game.gamedata.ports[w])
  1895. ):
  1896. wd = self.game.gamedata.ports[w]
  1897. if "class" not in wd:
  1898. continue
  1899. wc = wd["class"]
  1900. if pc in (1, 5) and wc in (2, 4):
  1901. data = self.game.gamedata.port_trade_show(
  1902. sector, w, show_limit
  1903. )
  1904. if data:
  1905. self.target_sector = sector
  1906. return sector
  1907. elif pc in (2, 4) and wc in (1, 5):
  1908. data = self.game.gamedata.port_trade_show(
  1909. sector, w, show_limit
  1910. )
  1911. if data:
  1912. self.target_sector = sector
  1913. return sector
  1914. yield
  1915. # Look for OK trades
  1916. for sector in sorted(self.game.gamedata.ports.keys()):
  1917. pd = self.game.gamedata.ports[sector]
  1918. if not GameData.port_burnt(pd):
  1919. if "class" not in pd:
  1920. continue
  1921. pc = pd["class"]
  1922. # Ok, let's look into it.
  1923. if not sector in self.game.gamedata.warps:
  1924. continue
  1925. # Busted port
  1926. if not sector in self.game.gamedata.busts:
  1927. continue
  1928. warps = self.game.gamedata.warps[sector]
  1929. for w in warps:
  1930. # We can get there, and get back.
  1931. if (
  1932. w in self.game.gamedata.warps
  1933. and sector in self.game.gamedata.warps[w]
  1934. ):
  1935. # Ok, we can get there -- and get back!
  1936. if (
  1937. w > sector
  1938. and w in self.game.gamedata.ports
  1939. and not GameData.port_burnt(self.game.gamedata.ports[w])
  1940. ):
  1941. wd = self.game.gamedata.ports[w]
  1942. if "class" not in wd:
  1943. continue
  1944. wc = wd["class"]
  1945. if GameData.port_trading(
  1946. pd["port"], self.game.gamedata.ports[w]["port"]
  1947. ):
  1948. data = self.game.gamedata.port_trade_show(
  1949. sector, w, show_limit
  1950. )
  1951. if data:
  1952. self.target_sector = sector
  1953. return sector
  1954. yield
  1955. self.target_sector = None
  1956. def whenDone(self):
  1957. self.defer = defer.Deferred()
  1958. # Call this to chain something after we exit.
  1959. return self.defer
  1960. def deactivate(self, andExit=False):
  1961. self.state = 0
  1962. log.debug("ScriptTerror.deactivate")
  1963. assert not self.save is None
  1964. self.observer.load(self.save)
  1965. self.save = None
  1966. if self.defer:
  1967. if andExit:
  1968. self.defer.callback({"exit": True})
  1969. else:
  1970. self.defer.callback("done")
  1971. self.defer = None
  1972. def player(self, chunk: bytes):
  1973. # If we receive anything -- ABORT!
  1974. self.deactivate(True)
  1975. def journey_on(self, *_):
  1976. log.info("journey_on( {0})".format(self.count))
  1977. if self.count > 0:
  1978. self.count -= 1
  1979. if self.usewhich == "F":
  1980. c = coiterate(self.find_next_good_trade_pair())
  1981. c.addCallback(lambda unknown: self.scary())
  1982. return
  1983. if self.usewhich == "C":
  1984. log.info("find_nearest_tradepairs({0})".format(self.sector))
  1985. c = coiterate(
  1986. self.game.gamedata.find_nearest_tradepairs(self.sector, self)
  1987. )
  1988. c.addCallback(lambda unknown: self.scary())
  1989. return
  1990. self.deactivate()
  1991. # c = coiterate(self.find_next_good_trade_pair())
  1992. # c.addCallback(lambda unknown: self.scary())
  1993. # self.target_sector = self.proxy.find_next_good_trade_pair() # Sector going to
  1994. # self.state = 1
  1995. # self.queue_player.put("{0}\r".format(self.target_sector))
  1996. else:
  1997. self.deactivate()
  1998. def game_prompt(self, prompt: str):
  1999. log.debug("{0} : {1}".format(self.state, prompt))
  2000. if self.state == 1:
  2001. if prompt.startswith("Do you want to engage the TransWarp drive? "):
  2002. self.queue_player.put("N")
  2003. elif self.state == 2:
  2004. if prompt.startswith("Do you want to engage the TransWarp drive? "):
  2005. self.queue_player.put("N")
  2006. elif prompt.startswith(
  2007. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2008. ):
  2009. self.queue_player.put("E")
  2010. elif prompt.startswith(
  2011. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  2012. ):
  2013. self.queue_player.put("N")
  2014. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2015. # We should be where we wanted to.
  2016. ports = ScriptPort(self.game)
  2017. d = ports.whenDone()
  2018. d.addCallback(self.journey_on)
  2019. d.addErrback(self.journey_on)
  2020. def game_line(self, line: str):
  2021. log.debug("line {0} : {1}".format(self.state, line))
  2022. if self.state == 1:
  2023. if line.startswith("The shortest path ("):
  2024. self.state = 2
  2025. elif line.startswith("Warping to Sector "):
  2026. self.state = 2
  2027. elif line.startswith("You are already in that sector!"):
  2028. # Whoops.
  2029. ports = ScriptPort(self.game)
  2030. d = ports.whenDone()
  2031. d.addCallback(self.journey_on)
  2032. d.addErrback(self.journey_on)
  2033. class PlanetUpScript(object):
  2034. """
  2035. Planet Upgrade Script
  2036. state=1 Pulling TLQ (Team/Corp List Planets)
  2037. Pulling CYQ (Computer, Your planets)
  2038. state=2 'Personal Planet Scan' or 'Corporate Planet Scan' parse.
  2039. Display list of planets, and prompt user for planet number to upgrade.
  2040. state=3 Moving to planet
  2041. state=4 Landing on planet, parse planet contents. select 'C'
  2042. state=5 Parse requirements for next upgrade
  2043. state=6 move to next needed item. (Colonists, F, O, E)
  2044. If completed, 'L' and state=4
  2045. Otherwise move, fetch=ITEM, and state=7
  2046. state=7 travel to where we need something.
  2047. Once there, L (land) for Colonist, otherwise PT (Port trade)
  2048. state=8 Return to planet.
  2049. state=9 At planet, or in route.
  2050. Land. Transfer Colonists/Cargo. state=6
  2051. """
  2052. def __init__(self, game):
  2053. self.game = game
  2054. self.queue_game = game.queue_game
  2055. self.queue_player = game.queue_player
  2056. self.observer = game.observer
  2057. # Yes, at this point we would activate
  2058. self.prompt = game.buffer
  2059. self.save = self.observer.save()
  2060. self.nl = "\n\r"
  2061. self.cargo_index = {"F": 0, "O": 1, "E": 2}
  2062. self.index_cargo = ("F", "O", "E")
  2063. # I actually don't want the player input, but I'll grab it anyway.
  2064. self.observer.connect("player", self.player)
  2065. self.observer.connect("prompt", self.game_prompt)
  2066. self.observer.connect("game-line", self.game_line)
  2067. # If we want it, it's here.
  2068. self.defer = None
  2069. self.to_player = self.game.to_player
  2070. self.planets = {}
  2071. self.citadel = False
  2072. # Hide what's happening from the player
  2073. self.game.to_player = False
  2074. # self.queue_player.put("CYQ") # Computer -> Your Planets -> Quit
  2075. self.queue_player.put("TLQ") # Team/Corp -> List Corp Planets -> Quit
  2076. self.corp = True
  2077. self.state = 1
  2078. # self.warpdata = {}
  2079. self.queue_game.put(Boxes.alert("Let me see what I can see here..."))
  2080. def display_planets(self, justLocal=True):
  2081. tc = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  2082. c1 = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  2083. c2 = merge(Style.BRIGHT + Fore.CYAN + Back.BLUE)
  2084. box = Boxes(44, color=tc)
  2085. self.queue_game.put(box.top())
  2086. # Are we just displaying local only? Then say so.
  2087. if justLocal:
  2088. planet_label = "LOCAL Planet Name"
  2089. else:
  2090. planet_label = "Planet Name"
  2091. self.queue_game.put(
  2092. box.row(
  2093. tc
  2094. + "{0:3} {1:6} {2:20} {3} ".format(
  2095. " # ", "Sector", planet_label, "Citadel LVL"
  2096. )
  2097. )
  2098. )
  2099. self.queue_game.put(box.middle())
  2100. def planet_output(number, sector, name, citadel):
  2101. row = "{0}{1:^3} {2:6} {3}{4:29} {0}{5:2} ".format(
  2102. c1, number, sector, c2, name, citadel
  2103. )
  2104. self.queue_game.put(box.row(row))
  2105. for s in sorted(self.planets.keys()):
  2106. if (justLocal == False) or (
  2107. self.current_sector == self.planets[s]["sector"]
  2108. ):
  2109. planet_output(
  2110. s,
  2111. self.planets[s]["sector"],
  2112. self.planets[s]["name"],
  2113. self.planets[s]["citadel"],
  2114. )
  2115. self.queue_game.put(box.bottom())
  2116. def game_prompt(self, prompt):
  2117. log.info("prompt {0} : {1}".format(self.state, prompt))
  2118. if self.state == 1 and re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2119. # Ok, you're not on a team. :P
  2120. self.queue_player.put("CYQ")
  2121. if self.state == 2 and re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2122. if self.corp:
  2123. self.corp = False
  2124. self.state = 1
  2125. self.queue_player.put("CYQ")
  2126. return
  2127. self.game.to_player = True
  2128. # For now we output the information, and exit
  2129. # self.queue_game.put("{0}\r\n".format(self.planets))
  2130. # self.queue_game.put(pformat(self.planets).replace("\n", self.nl) + self.nl)
  2131. if len(self.planets) == 0:
  2132. # Ok, this is easy.
  2133. self.queue_game.put(
  2134. self.nl
  2135. + Boxes.alert(
  2136. "You don't have any planets? You poor, poor dear.", base="red"
  2137. )
  2138. )
  2139. self.deactivate(True)
  2140. return
  2141. # I need this to know if I can just land, or need to move to the planet.
  2142. # Get current sector from the prompt
  2143. # Command [TL=00:00:00]:[10202] (?=Help)? :
  2144. _, _, part = prompt.partition("]:[")
  2145. sector, _, _ = part.partition("]")
  2146. self.current_sector = int(sector)
  2147. # A better default is to ask which planet to upgrade.
  2148. self.display_planets(True)
  2149. ask = PlayerInput(self.game)
  2150. d = ask.prompt("Choose a planet (L to List)", 3, name="planet")
  2151. d.addCallback(self.planet_chosen)
  2152. elif self.state == 3:
  2153. if prompt.startswith("Do you want to engage the TransWarp drive? "):
  2154. self.queue_player.put("N")
  2155. elif prompt.startswith(
  2156. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2157. ):
  2158. self.queue_player.put("E")
  2159. elif prompt.startswith(
  2160. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  2161. ):
  2162. self.queue_player.put("N")
  2163. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2164. # We're here!
  2165. self.state = 4
  2166. self.queue_player.put("L")
  2167. elif self.state == 4:
  2168. # If you have a planet scanner, or if there's more then one planet.
  2169. if prompt.startswith("Land on which planet <Q to abort> ?"):
  2170. self.queue_player.put("{0}\r".format(self.planet_number))
  2171. if prompt.startswith("Planet command (?=help) [D] "):
  2172. # self.queue_game.put(self.nl + "{0} : {1}".format( self.colonists, self.cargo) + self.nl)
  2173. self.state = 5
  2174. self.queue_player.put("C")
  2175. elif self.state == 5:
  2176. if re.match(r"Do you wish to construct .+\?", prompt):
  2177. # 'Do you wish to construct a Combat Control Computer?'
  2178. # Have we met all the needs? If so, do it. ;)
  2179. # If not, xfer the cargo on the ship to the planet and get moving!
  2180. ready = True
  2181. for i in self.index_cargo: # ['F', 'O', 'E']:
  2182. if self.need[i] > self.cargo[i]:
  2183. ready = False
  2184. log.info("Need: {0}".format(i))
  2185. # break
  2186. if self.need["C"] > self.colonists:
  2187. log.info("Need: people")
  2188. ready = False
  2189. # self.queue_game.put(self.nl + "{0}".format(self.need))
  2190. if ready:
  2191. self.queue_game.put(self.nl + Boxes.alert("Party Planet Pants On!"))
  2192. self.queue_player.put("YQ")
  2193. if self.citadel:
  2194. # Need extra Quit to get out of citadel, then out of planet.
  2195. self.queue_player.put("Q")
  2196. self.deactivate(True)
  2197. return
  2198. if "construct one" in prompt:
  2199. # No, but start moving things around to build one.
  2200. self.queue_player.put("N")
  2201. else:
  2202. # No, and quit the Citadel menu.
  2203. self.queue_player.put("NQ")
  2204. # Xfer cargo, and get ready to travel...
  2205. elif prompt.startswith("Citadel command (?=help)"):
  2206. self.queue_player.put("U")
  2207. self.citadel = True
  2208. if prompt.startswith("Planet command (?=help) [D] "):
  2209. # self.queue_game.put(pformat(self.ship_cargo).replace("\n", self.nl) + self.nl)
  2210. # self.queue_game.put(pformat(self.cargo).replace("\n", self.nl) + self.nl)
  2211. for idx, c in enumerate(self.index_cargo): # ('F', 'O', 'E')):
  2212. if self.ship_cargo[c] > 0:
  2213. # Transfer Cargo, (No display), Leave [1,2, or 3], \r = All of it.
  2214. self.queue_player.put("TNL{0}\r".format(idx + 1))
  2215. self.cargo[c] += self.ship_cargo[c]
  2216. self.ship_cargo[c] = 0
  2217. return
  2218. break
  2219. self.queue_player.put("Q")
  2220. self.state = 6
  2221. # self.queue_game.put(pformat(self.ship_cargo).replace("\n", self.nl) + self.nl)
  2222. # self.queue_game.put(pformat(self.cargo).replace("\n", self.nl) + self.nl)
  2223. # self.deactivate()
  2224. elif self.state == 6:
  2225. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2226. # Ok, what do we need and where do we get it?
  2227. if self.need["C"] > self.colonists:
  2228. # NavPoint, T, Express
  2229. self.fetch = "C"
  2230. self.queue_player.put("NTE")
  2231. self.state = 7
  2232. self.send_land = False
  2233. else:
  2234. for i in ("F", "O", "E"):
  2235. if self.need[i] > self.cargo[i]:
  2236. self.fetch = i
  2237. # TODO: Make this a config setting.
  2238. place = self.game.gamedata.find_nearest_selling(
  2239. self.planet_sector, i, 400
  2240. )
  2241. if place == 0:
  2242. self.queue_game.put(
  2243. self.nl + Boxes.alert("Find Nearest Failed!")
  2244. )
  2245. self.deactivate(True)
  2246. return
  2247. self.queue_player.put("{0}\r".format(place))
  2248. # self.queue_player.put("{0}\rE".format(place))
  2249. self.state = 7
  2250. return
  2251. # Ok, upgrade time!
  2252. self.state = 4
  2253. self.queue_player.put("L")
  2254. # self.queue_game.put("No, not yet!" + self.nl)
  2255. # self.deactivate()
  2256. # for i in ['F', 'O', 'E']:
  2257. # if self.need[i] > self.cargo[i]:
  2258. # ready = False
  2259. # self.queue_game.put( "Need: {0}".format(i) + self.nl)
  2260. elif self.state == 7:
  2261. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2262. if self.fetch == "C":
  2263. # Colonist
  2264. # [How many groups of Colonists do you want to take ([125] empty holds) ? ]
  2265. if self.send_land == False:
  2266. self.send_land = True
  2267. self.queue_player.put("L") # "LT\r")
  2268. elif self.fetch in self.index_cargo: # ('F', 'O', 'E'):
  2269. # Port, Trade
  2270. self.queue_player.put("pt")
  2271. elif re.match(r"How many holds of .+ do you want to sell", prompt):
  2272. # This shouldn't occur...
  2273. self.queue_game.put("OH NOSE!" + self.nl)
  2274. self.deactivate(True)
  2275. return
  2276. elif prompt.startswith("Do you want to engage the TransWarp drive? "):
  2277. self.queue_player.put("N")
  2278. elif prompt.startswith(
  2279. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2280. ):
  2281. self.queue_player.put("E")
  2282. elif prompt.startswith(
  2283. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  2284. ):
  2285. self.queue_player.put("N")
  2286. elif re.match(
  2287. r"How many holds of .+ do you want to buy \[\d+\]\? ", prompt
  2288. ):
  2289. if prompt.startswith("How many holds of " + self.fetch):
  2290. _, _, holds = prompt.partition("[")
  2291. holds, _, _ = holds.partition("]")
  2292. self.fetch_amount = int(holds)
  2293. log.info("Buying {0} of {1}".format(holds, self.fetch))
  2294. # BTTZ.
  2295. if int(holds) == 0:
  2296. # FAIL-WHALE
  2297. self.queue_player.put("\r")
  2298. self.queue_game.put(
  2299. self.nl
  2300. + Boxes.alert(
  2301. "FAILURE: Just bought 0 holds! Out of money!?!",
  2302. base="red",
  2303. )
  2304. )
  2305. self.deactivate(True)
  2306. return
  2307. self.queue_player.put("\r\r")
  2308. self.state = 8
  2309. else:
  2310. # We don't want to buy this one. Skip it!
  2311. self.queue_player.put("0\r")
  2312. elif prompt.startswith("Land on which planet <Q to abort> ?"):
  2313. if self.fetch == "C":
  2314. self.queue_player.put("1\r")
  2315. elif prompt.startswith(
  2316. "Do you wish to (L)eave or (T)ake Colonists? [T] (Q to leave)"
  2317. ):
  2318. if self.fetch == "C":
  2319. self.queue_player.put("T\r")
  2320. self.state = 8
  2321. elif self.state == 8:
  2322. if re.match(r"How many holds of .+ do you want to buy \[\d+\]\? ", prompt):
  2323. # No, no, we're done buying!
  2324. self.queue_player.put("0\r")
  2325. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2326. # Ok, return to the planet...
  2327. self.queue_player.put("{0}\rE".format(self.planet_sector))
  2328. self.state = 9
  2329. elif self.state == 9:
  2330. log.info("prompt9 {0} : {1}".format(self.state, prompt))
  2331. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2332. # land
  2333. self.queue_player.put("L")
  2334. elif prompt.startswith("Do you want to engage the TransWarp drive? "):
  2335. self.queue_player.put("N")
  2336. elif prompt.startswith(
  2337. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2338. ):
  2339. self.queue_player.put("E")
  2340. elif prompt.startswith("Engage Express mode? (Y/N) [N] "):
  2341. self.queue_player.put("Y")
  2342. elif prompt.startswith(
  2343. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  2344. ):
  2345. self.queue_player.put("N")
  2346. elif prompt.startswith("Land on which planet <Q to abort> ?"):
  2347. self.queue_player.put("{0}\r".format(self.planet_number))
  2348. elif prompt.startswith("Planet command (?=help) [D]"):
  2349. if self.fetch == "C":
  2350. # Colonist / No display Planet / Leave
  2351. self.queue_player.put("SNL")
  2352. elif self.fetch in self.index_cargo: # ('F', 'O', 'E'):
  2353. # Cargo, No display / Leave
  2354. self.queue_player.put("TNL")
  2355. elif prompt.startswith("(1)Ore, (2)Org or (3)Equipment ?"):
  2356. self.queue_player.put(
  2357. "{0}\r\rQ".format(self.cargo_index[self.fetch] + 1)
  2358. )
  2359. self.cargo[self.fetch] += self.fetch_amount
  2360. self.state = 6
  2361. elif prompt.startswith("(1)Ore, (2)Org or (3)Equipment Production?"):
  2362. log.info("place_people: {0}".format(self.place_people))
  2363. safe_places = [
  2364. k for k in self.place_people.keys() if self.place_people[k]
  2365. ]
  2366. if len(safe_places) == 0:
  2367. # Ok, (GREAT) Class "U" Vaporous/Gaseus >:(
  2368. safe_places = ["F", "O", "E"]
  2369. # TO FIX: Use self.place_people to decide.
  2370. # Ok, I'd choose, but for right now.
  2371. log.info("Safe {0} index {1}".format(safe_places, self.place_start))
  2372. put_people = safe_places[self.place_start]
  2373. log.info("Use: {0}".format(put_people))
  2374. self.place_start += 1
  2375. if self.place_start >= len(safe_places):
  2376. self.place_start = 0
  2377. self.queue_player.put(
  2378. "{0}\r\rQ".format(self.cargo_index[put_people] + 1)
  2379. )
  2380. self.colonists += self.fetch_amount
  2381. self.state = 6
  2382. def planet_chosen(self, choice: str):
  2383. if choice.strip() == "":
  2384. self.deactivate()
  2385. elif choice.strip().upper()[0] == "L":
  2386. self.display_planets(False)
  2387. ask = PlayerInput(self.game)
  2388. d = ask.prompt("Choose a planet (L to List)", 3, name="planet")
  2389. d.addCallback(self.planet_chosen)
  2390. return
  2391. else:
  2392. try:
  2393. self.planet_number = int(choice)
  2394. except ValueError:
  2395. self.deactivate()
  2396. return
  2397. if self.planet_number in self.planets:
  2398. # Ok, this'll work
  2399. self.planet_sector = self.planets[self.planet_number]["sector"]
  2400. self.planet_name = self.planets[self.planet_number]["name"]
  2401. if self.current_sector == self.planet_sector:
  2402. # We're here. Land
  2403. self.state = 4
  2404. self.queue_player.put("L")
  2405. else:
  2406. # Get moving!
  2407. self.state = 3
  2408. self.queue_player.put("{0}\r".format(self.planet_sector))
  2409. else:
  2410. self.deactivate()
  2411. def game_line(self, line):
  2412. log.info("line {0} : {1}".format(self.state, line))
  2413. if self.state == 1:
  2414. if "Personal Planet Scan" in line or "Corporate Planet Scan" in line:
  2415. self.state = 2
  2416. elif self.state == 2:
  2417. # Ok, we're in the planet scan part of this
  2418. # 10202 #3 Home of Bugz Class M, Earth Type No Citadel]
  2419. if "#" in line:
  2420. # Ok, we have a planet detail line.
  2421. # There's an extra T when the planet is maxed out.
  2422. if line[7] == "T":
  2423. line = line[:7] + " " + line[8:]
  2424. details, _, citadel = line.partition("Class")
  2425. # log.info(details) # Is that what we are after?
  2426. # log.info(citadel)
  2427. sector, planet_number, name = re.split(r"\s+", details.strip(), 2)
  2428. sector = int(sector)
  2429. number = int(planet_number.replace("#", ""))
  2430. if "Level" in citadel:
  2431. cit = int(citadel[-1]) # Grab last item
  2432. else: # Oops, there looks like there is no citadel here.
  2433. cit = 0
  2434. self.last_seen = number
  2435. self.planets[number] = {"sector": sector, "name": name, "citadel": cit}
  2436. log.info(
  2437. "Planet # {0} in {1} called {2} with a lvl {3} citadel".format(
  2438. number, sector, name, cit
  2439. )
  2440. )
  2441. # detail, _, _ = line.partition('Class')
  2442. # detail = detail.strip() # Sector #X Name of planet
  2443. # sector, number, name = re.split(r'\s+', detail, 2)
  2444. # sector = int(sector)
  2445. # number = int(number[1:])
  2446. # self.last_seen = number
  2447. # self.planets[number] = {"sector": sector, "name": name}
  2448. # log.info("Planet # {0} in {1} called {2}".format( number, sector, name))
  2449. if "---" in line:
  2450. number = self.last_seen
  2451. # Ok, take the last_seen number, and use it for this line
  2452. # [ Sector Planet Name Ore Org Equ Ore Org Equ Fighters Citadel]
  2453. # [ Shields Population -=Productions=- -=-=-=-=-On Hands-=-=-=-=- Credits]
  2454. # [ 10202 #3 Home of Bugz Class M, Earth Type No Citadel]
  2455. # [ --- (1M) 144 49 26 145 75 12 10 0]
  2456. details = re.split(r"\s+", line.strip())
  2457. # OK: Likely, I'm not going to use these numbers AT ALL.
  2458. self.planets[number]["population"] = (
  2459. details[1].replace("(", "").replace(")", "")
  2460. )
  2461. # Ok, there's going to have to be some sort of modifier (K, M, etc.)
  2462. # to these numbers. Beware!
  2463. self.planets[number]["ore"] = details[5]
  2464. self.planets[number]["org"] = details[6]
  2465. self.planets[number]["equ"] = details[7]
  2466. elif self.state == 4:
  2467. # Combat Control Computer under construction, 4 day(s) till complete.
  2468. if "under construction, " in line and "day(s) till complete" in line:
  2469. # Ok, already building.
  2470. self.queue_game.put(self.nl + Boxes.alert("NO, NOT YET!") + self.nl)
  2471. self.queue_player.put("Q") # quit Planet menu.
  2472. self.deactivate(True)
  2473. return
  2474. # [ Item Colonists Colonists Daily Planet Ship Planet ]
  2475. # [Fuel Ore 0 1 0 0 0 1,000,000]
  2476. # [Organics 0 N/A 0 0 0 10,000]
  2477. # [Equipment 0 500 0 125 125 100,000]
  2478. # [Fighters N/A N/A 0 0 400 1,000,000]
  2479. items = ["Fuel Ore", "Organics", "Equipment"]
  2480. for i in items:
  2481. if line.startswith(i):
  2482. cargo = line[0].upper()
  2483. work = line.replace(",", "")
  2484. if i == "Fuel Ore":
  2485. work = work.replace(i, "Fuel")
  2486. self.colonists = 0
  2487. self.cargo = {}
  2488. self.need = {}
  2489. self.ship_cargo = {}
  2490. self.place_people = {}
  2491. parts = re.split(r"\s+", work)
  2492. log.info("parts: {0}".format(parts))
  2493. c = int(parts[1])
  2494. planet_has = int(parts[4])
  2495. self.colonists += c
  2496. self.cargo[cargo] = planet_has
  2497. self.ship_cargo[cargo] = int(parts[5])
  2498. # Boolean, can we place people here? If N/A, then don't!
  2499. self.place_people[cargo] = parts[2] != "N/A"
  2500. self.place_start = 0
  2501. elif self.state == 5:
  2502. # [Planet command (?=help) [D] C]
  2503. # [Be patient, your Citadel is not yet finished.]
  2504. if line.startswith("Be patient, your Citadel is not yet finished."):
  2505. # Ah HA!
  2506. self.queue_game.put(self.nl + Boxes.alert("NO, NOT YET!") + self.nl)
  2507. self.queue_player.put("Q") # quit Planet menu.
  2508. self.deactivate(True)
  2509. elif line.startswith("This Citadel cannot be upgraded further"):
  2510. self.queue_game.put(self.nl + Boxes.alert("NO MORE!") + self.nl)
  2511. self.queue_player.put("QQ") # quit Citadel, quit Planet menu.
  2512. self.deactivate(True)
  2513. else:
  2514. items = ["Colonists", "Fuel Ore", "Organics", "Equipment"]
  2515. work = line.replace(",", "").replace(" units of", "").strip()
  2516. # 800,000 Colonists to support the construction,
  2517. # 500 units of Fuel Ore,
  2518. # 300 units of Organics,
  2519. # 600 units of Equipment and
  2520. for i in items:
  2521. if i in line:
  2522. count = int(work.split()[0])
  2523. k = i[0].upper()
  2524. # keep colonists in same units.
  2525. if k == "C":
  2526. count //= 1000
  2527. self.need[k] = count
  2528. elif self.state == 8:
  2529. if re.match(
  2530. r"How many groups of Colonists do you want to take \(\[\d+\] empty holds\) \?",
  2531. line,
  2532. ):
  2533. # Ok, how many holds?
  2534. _, _, holds = line.partition("[")
  2535. holds, _, _ = holds.partition("]")
  2536. self.fetch_amount = int(holds)
  2537. if line.startswith("One turn deducted, "):
  2538. parts = line.split()
  2539. turns = int(parts[3])
  2540. if turns < 200:
  2541. self.queue_game.put(self.nl + Boxes.alert("LOW TURNS.") + self.nl)
  2542. self.deactivate(True)
  2543. elif self.state == 9:
  2544. if re.match(r"You have \d turns left.", line):
  2545. parts = line.split()
  2546. turns = int(parts[2])
  2547. log.debug("Turns: {0}".format(turns))
  2548. def __del__(self):
  2549. log.debug("PlanetUpScript {0} RIP".format(self))
  2550. def whenDone(self):
  2551. self.defer = defer.Deferred()
  2552. # Call this to chain something after we exit.
  2553. return self.defer
  2554. def deactivate(self, andExit=False):
  2555. self.state = 0
  2556. if not self.defer is None:
  2557. # We have something, so:
  2558. self.game.to_player = self.to_player
  2559. self.observer.load(self.save)
  2560. self.save = None
  2561. if andExit:
  2562. self.defer.callback({"exit": True})
  2563. else:
  2564. self.defer.callback("done")
  2565. self.defer = None
  2566. else:
  2567. # Still "exit" out.
  2568. self.game.to_player = self.to_player
  2569. self.observer.load(self.save)
  2570. def player(self, chunk):
  2571. """ Data from player (in bytes). """
  2572. chunk = chunk.decode("latin-1", "ignore")
  2573. key = chunk.upper()
  2574. log.warn(
  2575. "PlanetUpScript.player({0}) : I AM stopping...(user input)".format(key)
  2576. )
  2577. if not self.defer is None:
  2578. # We have something, so:
  2579. self.game.to_player = self.to_player
  2580. self.observer.load(self.save)
  2581. self.save = None
  2582. self.defer.errback(Exception("User Abort"))
  2583. self.defer = None
  2584. else:
  2585. # Still "exit" out.
  2586. self.game.to_player = self.to_player
  2587. self.observer.load(self.save)
  2588. class ColoScript2(object):
  2589. """ ColoScript 2.0
  2590. Goal:
  2591. * Allow a player to move people from anywhere to anywhere. (Acheived!)
  2592. States:
  2593. 1 = Computer talks with us giving corp and personal planet info
  2594. 2 = Grab's data and asks series of questions, TO, FROM, LOOPS
  2595. 3 = Move to FROM
  2596. 4 = Identify Population Categories / Is it terra?
  2597. 5 = Load People, then move to planet TO
  2598. 6 = Init Land on TO
  2599. 7 = Decide to loop (Jump back to 3), Unload People
  2600. """
  2601. def __init__(self, game):
  2602. self.game = game
  2603. self.queue_game = game.queue_game
  2604. self.queue_player = game.queue_player
  2605. self.observer = game.observer
  2606. self.r = Style.RESET_ALL
  2607. self.c = merge(Style.BRIGHT + Fore.YELLOW)
  2608. self.nl = "\n\r"
  2609. # My "stuff" in my pants!
  2610. self.state = 1
  2611. self.corp = True
  2612. self.planets = {}
  2613. self.loops = 0
  2614. self.maxloops = 0
  2615. self.last_seen = 0
  2616. self.valid2From = True
  2617. # Sector Numbers of Planets TO and FROM
  2618. self.TO = 0
  2619. self.FROM = 0
  2620. # Planet Numbers of Planets TO and FROM
  2621. self.to_number = 0
  2622. self.from_number = 0
  2623. # Activate
  2624. self.prompt = game.buffer
  2625. self.save = self.observer.save()
  2626. self.observer.connect("player", self.player)
  2627. self.observer.connect("prompt", self.game_prompt)
  2628. self.observer.connect("game-line", self.game_line)
  2629. self.defer = None
  2630. self.to_player = self.game.to_player
  2631. self.game.to_player = False
  2632. self.send2game("TLQ")
  2633. def whenDone(self):
  2634. self.defer = defer.Deferred()
  2635. return self.defer
  2636. def deactivate(self, andExit=False):
  2637. self.state = 0
  2638. log.debug("ColoScript2.deactivate()")
  2639. self.game.to_player = True
  2640. assert not self.save is None
  2641. self.observer.load(self.save)
  2642. self.save = None
  2643. if self.defer:
  2644. if andExit:
  2645. self.defer.callback({"exit": True})
  2646. else:
  2647. self.defer.callback("done")
  2648. self.defer = None
  2649. def player(self, chunk: bytes):
  2650. self.deactivate(True)
  2651. def send2game(self, txt):
  2652. # Removed debug info since I use this to also display Boxes.alert
  2653. self.queue_player.put(txt)
  2654. def send2player(self, txt):
  2655. # Removed debug since it really doesn't help with anything
  2656. self.queue_game.put(txt)
  2657. def to_chosen(self, choice: str):
  2658. if choice.strip() == "":
  2659. self.deactivate(True)
  2660. else:
  2661. self.to_number = int(choice)
  2662. if self.to_number == 1:
  2663. # Oooh Terra!
  2664. self.TO = 1
  2665. self.planet_name = "Terra"
  2666. ask1 = PlayerInput(self.game)
  2667. d1 = ask1.prompt("From: ", 3, name="from", digits=True)
  2668. d1.addCallback(self.from_chosen)
  2669. elif self.to_number in self.planets:
  2670. # Ok, this'll work
  2671. self.TO = self.planets[self.to_number]["sector"]
  2672. self.planet_name = self.planets[self.to_number]["name"]
  2673. # Are we really getting this? Yup
  2674. # log.debug("TO Planet Number: {0} Sector: {1}".format(self.to_number, self.TO))
  2675. ask1 = PlayerInput(self.game)
  2676. d1 = ask1.prompt("From: ", 3, name="from", digits=True)
  2677. d1.addCallback(self.from_chosen)
  2678. else:
  2679. self.deactivate(True)
  2680. def from_chosen(self, choice: str):
  2681. if choice.strip() == "":
  2682. self.deactivate(True)
  2683. else:
  2684. self.from_number = int(choice)
  2685. if self.from_number == self.to_number:
  2686. # Prevent the user from asking to move folks to the same planet they would be getting
  2687. # them from. See Recursion!
  2688. self.valid2From = False
  2689. if self.from_number in self.planets:
  2690. # Ok, this'll work
  2691. self.FROM = self.planets[self.from_number]["sector"]
  2692. self.planet_name = self.planets[self.from_number]["name"]
  2693. # Are we really getting this? Yup Yup
  2694. # log.debug("FROM Planet Number: {0} Sector: {1}".format(self.from_number, self.FROM))
  2695. ask1 = PlayerInput(self.game)
  2696. d1 = ask1.prompt("How many times ", 3, name="rolls", digits=True)
  2697. d1.addCallback(self.loop_chosen)
  2698. elif self.from_number == 1:
  2699. # Yup handle if the user picks to pull from Terra
  2700. self.FROM = 1
  2701. ask1 = PlayerInput(self.game)
  2702. d1 = ask1.prompt("How many times ", 3, name="rolls", digits=True)
  2703. d1.addCallback(self.loop_chosen)
  2704. else:
  2705. self.deactivate(True)
  2706. def loop_chosen(self, choice: str):
  2707. if choice.strip() == "":
  2708. self.deactivate(True)
  2709. else:
  2710. self.loops = abs(int(choice))
  2711. if self.loops == 0:
  2712. self.loops = 1
  2713. self.maxloops = self.loops
  2714. # ask2 = PlayerInput(self.game)
  2715. # d2 = ask2.prompt("From? ", 5, name="from", digits=True)
  2716. # d2.addCallback(self.from_chosen)
  2717. if self.valid2From:
  2718. self.state = 3
  2719. self.game.to_player = False
  2720. self.send2game("I")
  2721. else:
  2722. self.game.to_player = True
  2723. self.send2player(
  2724. self.nl
  2725. + Boxes.alert(
  2726. "Completed ({0}) Wow, it's like nothing happened.".format(
  2727. self.maxloops
  2728. )
  2729. )
  2730. )
  2731. self.deactivate(True)
  2732. def game_prompt(self, prompt: str):
  2733. log.debug("P {0} | {1}".format(self.state, prompt))
  2734. if self.state == 1 and re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2735. # Ok, you're not on a team. :P
  2736. self.queue_player.put("CYQ")
  2737. if self.state == 2 and re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2738. if self.corp:
  2739. self.corp = False
  2740. self.state = 1
  2741. self.queue_player.put("CYQ")
  2742. return
  2743. self.game.to_player = True
  2744. # For now we output the information, and exit
  2745. # self.queue_game.put("{0}\r\n".format(self.planets))
  2746. # self.queue_game.put(pformat(self.planets).replace("\n", self.nl) + self.nl)
  2747. if len(self.planets) == 0:
  2748. # Ok, this is easy.
  2749. self.queue_game.put(
  2750. self.nl
  2751. + Boxes.alert(
  2752. "You don't have any planets? You poor, poor dear.", base="red"
  2753. )
  2754. )
  2755. self.deactivate(True)
  2756. return
  2757. # I need this to know if I can just land, or need to move to the planet.
  2758. # Get current sector from the prompt
  2759. # Command [TL=00:00:00]:[10202] (?=Help)? :
  2760. _, _, part = prompt.partition("]:[")
  2761. sector, _, _ = part.partition("]")
  2762. self.current_sector = int(sector)
  2763. # A better default is to ask which planet to upgrade.
  2764. tc = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  2765. c1 = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  2766. c2 = merge(Style.BRIGHT + Fore.CYAN + Back.BLUE)
  2767. box = Boxes(44, color=tc)
  2768. self.queue_game.put(box.top())
  2769. self.queue_game.put(
  2770. box.row(
  2771. tc
  2772. + "{0:3} {1:6} {2:20} {3} ".format(
  2773. " # ", "Sector", "Planet Name", "Citadel LVL"
  2774. )
  2775. )
  2776. )
  2777. self.queue_game.put(box.middle())
  2778. def planet_output(number, sector, name, citadel):
  2779. row = "{0}{1:^3} {2:6} {3}{4:29} {0}{5:2} ".format(
  2780. c1, number, sector, c2, name, citadel
  2781. )
  2782. self.queue_game.put(box.row(row))
  2783. # Manually add in Terra so a player knows about it,
  2784. # Since we now support Terra being TO or FROM.
  2785. terra = row = "{0}{1:^3} {2:6} {3}{4:29} {0}{5:2} ".format(
  2786. c1, 1, 1, c2, "Terra", " "
  2787. )
  2788. self.send2player(box.row(terra))
  2789. for s in sorted(self.planets.keys()):
  2790. planet_output(
  2791. s,
  2792. self.planets[s]["sector"],
  2793. self.planets[s]["name"],
  2794. self.planets[s]["citadel"],
  2795. )
  2796. self.queue_game.put(box.bottom())
  2797. ask = PlayerInput(self.game)
  2798. d = ask.prompt("To: ", 3, name="planet", digits=True)
  2799. d.addCallback(self.to_chosen)
  2800. elif self.state == 3:
  2801. # Initalize moving to sector 1, Terra
  2802. if prompt.startswith("Do you want to engage the TransWarp drive? "):
  2803. self.queue_player.put("N")
  2804. elif prompt.startswith(
  2805. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2806. ):
  2807. self.queue_player.put("E")
  2808. elif prompt.startswith(
  2809. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  2810. ):
  2811. self.queue_player.put("N")
  2812. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2813. self.state = 4
  2814. self.game.to_player = True
  2815. self.send2game("{0}\r".format(self.FROM))
  2816. # Move to planet FROM
  2817. elif self.state == 4:
  2818. # Are we there yet? (NNY)
  2819. if prompt.startswith("Do you want to engage the TransWarp drive? "):
  2820. self.queue_player.put("N")
  2821. elif prompt.startswith(
  2822. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2823. ):
  2824. self.queue_player.put("E")
  2825. elif prompt.startswith(
  2826. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  2827. ):
  2828. self.queue_player.put("N")
  2829. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2830. self.state = 5
  2831. self.send2game("L")
  2832. elif self.state == 5:
  2833. if self.FROM == 1: # Is our FROM planet Terra?
  2834. if prompt.startswith("Land on which planet <Q to abort> ?"):
  2835. self.send2game("1\r\r\r{0}\r".format(self.TO))
  2836. self.state = 6
  2837. # Planetary Scanner Detected, Move to sector with planet
  2838. elif prompt.startswith(
  2839. "Do you wish to (L)eave or (T)ake Colonists? [T] (Q to leave)"
  2840. ):
  2841. self.send2game("\r\r{0}\r".format(self.TO))
  2842. self.state = 6
  2843. # No Planetary Scanner Detected, Move to sector with planet
  2844. elif prompt.startswith(
  2845. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2846. ):
  2847. self.send2game("E")
  2848. self.state = 4
  2849. # We are not at terra, go back
  2850. else:
  2851. if prompt.startswith("Land on which planet <Q to abort> ?"):
  2852. self.send2game(
  2853. "{0}\rs\rt1\rq{1}\r".format(self.from_number, self.TO)
  2854. )
  2855. self.state = 6
  2856. # Planetary Scanner Detected, Move to sector with planet
  2857. elif prompt.startswith("Planet command (?=help) [D] "):
  2858. self.send2game("s\rt1\rq{0}\r".format(self.TO))
  2859. self.state = 6
  2860. elif prompt.startswith(
  2861. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2862. ):
  2863. self.send2game("E")
  2864. self.state = 4
  2865. # We are not at terra, go back
  2866. elif self.state == 6:
  2867. if prompt.startswith("Do you want to engage the TransWarp drive? "):
  2868. self.queue_player.put("N")
  2869. elif prompt.startswith(
  2870. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2871. ):
  2872. self.queue_player.put("E")
  2873. elif prompt.startswith(
  2874. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  2875. ):
  2876. self.queue_player.put("N")
  2877. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2878. self.state = 6
  2879. self.send2game("L")
  2880. if self.TO != 1:
  2881. if prompt.startswith("Land on which planet <Q to abort> ?"):
  2882. self.state = 7
  2883. self.send2game("{0}\r".format(self.to_number))
  2884. # Planetary Scanner Detected selecting planet number
  2885. elif prompt.startswith("Planet command (?=help) [D] "):
  2886. self.state = 7
  2887. self.send2game("D")
  2888. # No Planetary Scaner skip on
  2889. else:
  2890. if prompt.startswith("Land on which planet <Q to abort> ?"):
  2891. self.state = 7
  2892. self.send2game("1\r")
  2893. # Planetary Scanner Detected selecting planet number
  2894. elif prompt.startswith("Do you wish to (L)eave or (T)ake Colonists?"):
  2895. self.state = 7
  2896. self.send2game("L")
  2897. # No Planetary Scaner skip on
  2898. elif self.state == 7:
  2899. if prompt.startswith("Engage the Autopilot? (Y/N/Single step/Express) [Y]"):
  2900. self.state = 6
  2901. self.send2game("E")
  2902. # Missed moving jump back to state 6
  2903. if self.TO != 1:
  2904. if prompt.startswith("Land on which planet <Q to abort> ?"):
  2905. self.queue_player.put("{0}\r".format(self.to_number))
  2906. # Planetary Scanner Detected selecting planet number
  2907. if prompt.startswith("Planet command (?=help) [D] "):
  2908. # Unload people and process the loop
  2909. self.loops -= 1
  2910. if self.loops:
  2911. self.state = 3
  2912. self.send2game("S\r\r1\rQ")
  2913. # Jump to state 3 we are not done
  2914. else:
  2915. self.send2game("S\r\r1\rQ")
  2916. self.send2player(
  2917. "\r" + Boxes.alert("Completed ({0})".format(self.maxloops))
  2918. )
  2919. self.deactivate(True)
  2920. # Ok we are done
  2921. else:
  2922. if prompt.startswith("Land on which planet <Q to abort> ?"):
  2923. self.queue_player.put("1\r")
  2924. # Planetary Scanner Detected selecting planet number
  2925. if prompt.startswith("Do you wish to (L)eave or (T)ake Colonists?"):
  2926. # Unload people and process the loop
  2927. self.loops -= 1
  2928. if self.loops:
  2929. self.state = 3
  2930. self.send2game("L\r")
  2931. # Jump to state 3 we are not done
  2932. else:
  2933. self.send2game("L\r")
  2934. self.send2player(
  2935. "\r" + Boxes.alert("Completed ({0})".format(self.maxloops))
  2936. )
  2937. self.deactivate(True)
  2938. # Ok we are done
  2939. if prompt.startswith(
  2940. "How many groups of Colonists do you want to leave"
  2941. ):
  2942. self.loops -= 1
  2943. if self.loops:
  2944. self.state = 3
  2945. self.send2game("\r")
  2946. # Jump to state 3 we are not done
  2947. else:
  2948. self.send2game("\r")
  2949. self.send2player(
  2950. "\r" + Boxes.alert("Completed ({0})".format(self.maxloops))
  2951. )
  2952. self.deactivate(True)
  2953. # Ok we are done
  2954. def game_line(self, line: str):
  2955. log.debug("L {0} | {1}".format(self.state, line))
  2956. # IF at any state we see turns left lets grab it
  2957. if "turns left" in line:
  2958. work = line[19:].replace(" turns left.", "").strip()
  2959. self.turns = work
  2960. log.debug("TURNS LEFT: {0}".format(self.turns))
  2961. if int(self.turns) < 200:
  2962. self.send2player(
  2963. "\r" + Boxes.alert("Low Turns! ({0})".format(self.turns))
  2964. )
  2965. self.deactivate(True)
  2966. # IF at any state we see how many holds avalible let's get that
  2967. if "Total Holds" in line:
  2968. work = line[16:].replace("-", "").replace("=", " ").split()
  2969. self.total_holds = int(work[0])
  2970. count = 0
  2971. seen_empty = False
  2972. for w in work:
  2973. if w != "Empty":
  2974. count += 1
  2975. elif w == "Empty":
  2976. count += 1
  2977. self.holds = int(work[count])
  2978. log.debug("EMPTY HOLDS = {0}".format(self.holds))
  2979. self.holds_percent = int((self.holds / self.total_holds) * 100.0)
  2980. log.debug("HOLDS PERCENT = {0}%".format(self.holds_percent))
  2981. seen_empty = True
  2982. if self.holds < self.total_holds:
  2983. self.send2player(
  2984. "\r"
  2985. + Boxes.alert(
  2986. "You need {0} holds empty! ({1} Empty)".format(
  2987. self.total_holds, self.holds
  2988. )
  2989. )
  2990. )
  2991. self.deactivate(True)
  2992. if (
  2993. seen_empty != True
  2994. ): # Just incase we didn't see Empty... meaning we have 0 avalible holds
  2995. self.send2player(
  2996. "\r"
  2997. + Boxes.alert(
  2998. "You need {0} holds empty! (0 Empty)".format(self.total_holds)
  2999. )
  3000. )
  3001. self.deactivate(True)
  3002. if "There aren't that many on the planet!" in line:
  3003. self.send2player("\r" + Boxes.alert("We're missing people!"))
  3004. self.deactivate(True)
  3005. if "There isn't room on the planet for that many!" in line:
  3006. self.send2player("\r" + Boxes.alert("We have to many people!"))
  3007. self.deactivate(True)
  3008. if "There aren't that many on Terra!" in line:
  3009. self.send2player("\r" + Boxes.alert("No people on Terra to get!"))
  3010. self.deactivate(True)
  3011. # Now back to our scheduled program
  3012. if self.state == 1:
  3013. if "Personal Planet Scan" in line or "Corporate Planet Scan" in line:
  3014. self.state = 2
  3015. elif self.state == 2:
  3016. # Ok, we're in the planet scan part of this
  3017. # 10202 #3 Home of Bugz Class M, Earth Type No Citadel]
  3018. if "#" in line:
  3019. # Ok, we have a planet detail line.
  3020. # There's an extra T when the planet is maxed out.
  3021. # [ 986 #114 Trantor Class M, Earth Type No Citadel]
  3022. # [ 23 #17 gift Class O, Oceanic Level 1]
  3023. if line[7] == "T":
  3024. line = line[:7] + " " + line[8:]
  3025. details, _, citadel = line.partition("Class")
  3026. # log.info(details) # Is that what we are after?
  3027. # log.info(citadel)
  3028. sector, planet_number, name = re.split(r"\s+", details.strip(), 2)
  3029. sector = int(sector)
  3030. number = int(planet_number.replace("#", ""))
  3031. if "Level" in citadel:
  3032. cit = int(citadel[-1]) # Grab last item
  3033. else: # Oops, there looks like there is no citadel here.
  3034. cit = 0
  3035. self.last_seen = number
  3036. self.planets[number] = {"sector": sector, "name": name, "citadel": cit}
  3037. log.info(
  3038. "Planet # {0} in {1} called {2} with a lvl {3} citadel".format(
  3039. number, sector, name, cit
  3040. )
  3041. )
  3042. if "---" in line:
  3043. number = self.last_seen
  3044. # Ok, take the last_seen number, and use it for this line
  3045. # [ Sector Planet Name Ore Org Equ Ore Org Equ Fighters Citadel]
  3046. # [ Shields Population -=Productions=- -=-=-=-=-On Hands-=-=-=-=- Credits]
  3047. # [ 10202 #3 Home of Bugz Class M, Earth Type No Citadel]
  3048. # [ --- (1M) 144 49 26 145 75 12 10 0]
  3049. details = re.split(r"\s+", line.strip())
  3050. log.debug(details) # What are we getting?
  3051. # OK: Likely, I'm not going to use these numbers AT ALL.
  3052. self.planets[number]["population"] = (
  3053. details[1].replace("(", "").replace(")", "")
  3054. )
  3055. # Ok, there's going to have to be some sort of modifier (K, M, etc.)
  3056. # to these numbers. Beware!
  3057. self.planets[number]["ore"] = details[5]
  3058. self.planets[number]["org"] = details[6]
  3059. self.planets[number]["equ"] = details[7]
  3060. # self.planets[number]['cit'] = details[9] # This is if we wanted cit money... but that's not it
  3061. class MaxFighterMake(object):
  3062. """ Max Fighter Make
  3063. State of the Union:
  3064. 1 = Grab planets in current sector
  3065. 2 = Ask what planet to utilize, land
  3066. 3 = Grab Snapshot of planet (We will need to check population lvls too)
  3067. 4 = try cat 1 to cat 2 (Or perhaps this defaults to false if cat 2 is N/A)
  3068. 5 = if bad then try cat 1 to cat 3 (Or perhaps this defaults to false if cat 3 is N/A)
  3069. 6 = if bad then try cat 2 to cat 3 (Or perhaps this defaults to false if cat 3 is N/A)
  3070. 7 = loop back to state 3 until all result in bad (Yay best acheived)
  3071. """
  3072. def __init__(self, game):
  3073. self.game = game
  3074. self.queue_game = game.queue_game
  3075. self.queue_player = game.queue_player
  3076. self.observer = game.observer
  3077. self.r = Style.RESET_ALL
  3078. self.c = merge(Style.BRIGHT + Fore.YELLOW)
  3079. self.nl = "\n\r"
  3080. # My "stuff" in my pants!
  3081. self.state = 1
  3082. self.corp = True
  3083. self.target_sector = 0 # Sector Number of target
  3084. self.target_number = 0 # Planet Number of target
  3085. self.last_seen = {"Ore": False, "Org": False, "Equ": False, "Fig": False}
  3086. self.max_product = 0
  3087. self.trying = "Ore2Org"
  3088. self.trying_NEXT = False
  3089. self.movement = 1000
  3090. self.planets_list = [] # Will be a list of dicts, containing planet information
  3091. self.cap = False # Capture line for planet
  3092. # Activate
  3093. self.prompt = game.buffer
  3094. self.save = self.observer.save()
  3095. self.observer.connect("player", self.player)
  3096. self.observer.connect("prompt", self.game_prompt)
  3097. self.observer.connect("game-line", self.game_line)
  3098. self.ore = {}
  3099. self.org = {}
  3100. self.equ = {}
  3101. self.fig = {}
  3102. self.defer = None
  3103. self.to_player = self.game.to_player
  3104. self.game.to_player = False
  3105. self.send2game("D")
  3106. def whenDone(self):
  3107. self.defer = defer.Deferred()
  3108. return self.defer
  3109. def deactivate(self, andExit=False):
  3110. self.state = 0
  3111. log.debug("MaxFighterMake.deactivate()")
  3112. self.game.to_player = True
  3113. assert not self.save is None
  3114. self.observer.load(self.save)
  3115. self.save = None
  3116. if self.defer:
  3117. if andExit:
  3118. self.defer.callback({"exit": True})
  3119. else:
  3120. self.defer.callback("done")
  3121. self.defer = None
  3122. def player(self, chunk: bytes):
  3123. self.deactivate(True)
  3124. def send2game(self, txt):
  3125. # Removed debug info since I use this to also display Boxes.alert
  3126. self.queue_player.put(txt)
  3127. def send2player(self, txt):
  3128. # Removed debug since it really doesn't help with anything
  3129. self.queue_game.put(txt)
  3130. def target_chosen(self, choice: str):
  3131. if choice.strip() == "":
  3132. self.deactivate(True)
  3133. else:
  3134. self.target_number = int(choice)
  3135. if self.target_number > self.total:
  3136. self.deactivate(True)
  3137. else:
  3138. self.state = 3
  3139. self.send2game("L")
  3140. def check_resource(self, resource):
  3141. # Given a valid string that can be converted to int
  3142. if resource == "N/A":
  3143. resource = -1
  3144. else:
  3145. resource = int(resource.replace(",", ""))
  3146. return resource
  3147. def game_prompt(self, prompt: str):
  3148. log.debug("P {0} | {1}".format(self.state, prompt))
  3149. if self.state == 2:
  3150. self.game.to_player = True
  3151. if len(self.planets_list) == 0:
  3152. self.send2player(self.nl + Boxes.alert("No planets in this sector!"))
  3153. self.deactivate(True)
  3154. tc = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  3155. c1 = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  3156. c2 = merge(Style.BRIGHT + Fore.CYAN + Back.BLUE)
  3157. box = Boxes(44, color=tc)
  3158. self.queue_game.put(box.top())
  3159. self.queue_game.put(
  3160. box.row(
  3161. tc
  3162. + "{0:3} {1:20} {2:18} ".format(" # ", "Planet Name", "Planet Type")
  3163. )
  3164. )
  3165. self.queue_game.put(box.middle())
  3166. def planet_output(num, planet_name, planet_type):
  3167. row = "{0}{1:3} {2}{3:29} {4:9} ".format(
  3168. c1, num, c2, planet_name, planet_type
  3169. )
  3170. self.send2player(box.row(row))
  3171. self.total = 0
  3172. for p in self.planets_list:
  3173. planet_output(self.total, p["name"], p["type"])
  3174. self.total += 1
  3175. ask = PlayerInput(self.game)
  3176. d = ask.prompt("Choose a planet", 3, name="planet", digits=True)
  3177. d = d.addCallback(self.target_chosen)
  3178. elif self.state == 4:
  3179. if prompt.startswith("Planet command (?=help) [D]"):
  3180. self.send2game("?")
  3181. self.state = 6
  3182. elif self.state == 6:
  3183. if prompt.startswith("Planet command (?=help) [D]"):
  3184. self.send2game("P")
  3185. self.state = 7
  3186. elif self.state == 7:
  3187. if prompt.startswith("Display planet?"):
  3188. self.send2game("N")
  3189. self.state = 8
  3190. elif self.state == 8:
  3191. if prompt.startswith("(1)Ore, (2)Org or (3)Equipment?"):
  3192. if self.trying == "Ore2Org" or self.trying == "Ore2Equ":
  3193. self.send2game("1")
  3194. elif self.trying == "Org2Equ" or self.trying == "Org2Ore":
  3195. self.send2game("2")
  3196. elif self.trying == "Equ2Org" or self.trying == "Equ2Ore":
  3197. self.send2game("3")
  3198. self.state = 9
  3199. elif self.state == 9:
  3200. if prompt.startswith("How many groups of Colonists do you want to move?"):
  3201. self.send2game("{0}\r".format(self.movement))
  3202. self.state = 10
  3203. elif self.state == 10:
  3204. if prompt.startswith("(1)Ore, (2)Org or (3)Equipment?"):
  3205. if self.trying == "Org2Ore" or self.trying == "Equ2Ore":
  3206. self.send2game("1")
  3207. elif self.trying == "Ore2Org" or self.trying == "Equ2Org":
  3208. self.send2game("2")
  3209. elif self.trying == "Ore2Equ" or self.trying == "Org2Equ":
  3210. self.send2game("3")
  3211. self.state = 11
  3212. elif self.state == 11:
  3213. if prompt.startswith("Planet command (?=help) [D]"):
  3214. self.send2game("D")
  3215. self.trying_NEXT = False
  3216. self.last_seen["Ore"] = False
  3217. self.last_seen["Org"] = False
  3218. self.last_seen["Equ"] = False
  3219. self.last_seen["Fig"] = False
  3220. self.state = 12
  3221. elif self.state == 12:
  3222. if prompt.startswith("Planet command (?=help) [D]"):
  3223. self.send2game("?")
  3224. self.state = 6
  3225. # if(self.trying == 'Ore2Org'):
  3226. # self.send2game('P\r1{0}2D'.format(self.movement))
  3227. # self.state = 4
  3228. # # Back to looking at the planet
  3229. # elif(self.trying == 'Ore2Equ'):
  3230. # self.send2game('P\r1{0}3D'.format(self.movement))
  3231. # self.state = 4
  3232. # # Back to looking at the planet
  3233. # elif(self.trying == 'Org2Equ'):
  3234. # self.send2game('P\r2{0}3D'.format(self.movement))
  3235. # self.state = 4
  3236. # elif(self.trying == 'reverse'):
  3237. # if(self.trying_OLD == 'Ore2Org'):
  3238. # self.send2game('P\r2{0}1D'.format(self.movement))
  3239. # elif(self.trying_OLD == 'Ore2Equ'):
  3240. # self.send2game('P\r3{0}1D'.format(self.movement))
  3241. # elif(self.trying_OLD == 'Org2Equ'):
  3242. # self.send2game('P\r3{0}2D'.format(self.movement))
  3243. # self.state = 4
  3244. # self.trying = self.trying_NEXT
  3245. def game_line(self, line: str):
  3246. log.debug("L {0} | {1}".format(self.state, line))
  3247. # IF at any state we see turns left lets grab it
  3248. if "turns left" in line:
  3249. work = line[19:].replace(" turns left.", "").strip()
  3250. self.turns = work
  3251. log.debug("TURNS LEFT: {0}".format(self.turns))
  3252. if int(self.turns) < 200:
  3253. self.send2player(
  3254. "\r" + Boxes.alert("Low Turns! ({0})".format(self.turns))
  3255. )
  3256. self.deactivate(True)
  3257. # IF at any state we see how many holds avalible let's get that
  3258. if "Total Holds" in line:
  3259. work = line[16:].replace("-", "").replace("=", " ").split()
  3260. self.total_holds = int(work[0])
  3261. count = 0
  3262. for w in work:
  3263. if w != "Empty":
  3264. count += 1
  3265. elif w == "Empty":
  3266. count += 1
  3267. self.holds = int(work[count])
  3268. log.debug("EMPTY HOLDS = {0}".format(self.holds))
  3269. if self.holds < self.total_holds:
  3270. self.send2player(
  3271. "\r"
  3272. + Boxes.alert(
  3273. "You need {0} holds empty! ({1} Empty)".format(
  3274. self.total_holds, self.holds
  3275. )
  3276. )
  3277. )
  3278. self.deactivate(True)
  3279. if "There aren't that many on the planet!" in line:
  3280. self.send2player("\r" + Boxes.alert("We're missing people!"))
  3281. self.deactivate(True)
  3282. if "There isn't room on the planet for that many!" in line:
  3283. self.send2player("\r" + Boxes.alert("We have to many people!"))
  3284. self.deactivate(True)
  3285. # Now back to our scheduled program
  3286. if self.state == 1:
  3287. if line.startswith("Planets"):
  3288. self.cap = True
  3289. work = re.split(r"\s+", line)
  3290. # log.debug("'{0}'".format(work))
  3291. final = {"name": work[-1], "type": work[-2]}
  3292. self.planets_list.append(final)
  3293. log.debug("Planet {0} type {1}".format(final["name"], final["type"]))
  3294. elif line.startswith("Ships"): # Stop 1, so we don't capture everything
  3295. self.cap = False
  3296. elif line.startswith("Fighters"): # Stop 2, so we don't capture everything
  3297. self.cap = False
  3298. elif self.cap == True:
  3299. work = re.split(r"\s+", line)
  3300. # log.debug("'{0}'".format(work))
  3301. final = {"name": work[-1], "type": work[-2]}
  3302. self.planets_list.append(final)
  3303. log.debug("Planet {0} type {1}".format(final["name"], final["type"]))
  3304. elif self.cap == False and len(self.planets_list) != 0:
  3305. self.state = 2
  3306. elif self.state == 3:
  3307. if self.planets_list[self.target_number]["name"] in line:
  3308. work = re.split(r"\s+", line)
  3309. log.debug("'{0}'".format(work))
  3310. pnumber = work[2].replace(">", "")
  3311. self.planets_list[self.target_number][
  3312. "pnumber"
  3313. ] = pnumber # Add this to our dict of the planet
  3314. log.debug(
  3315. "Pnumber {0} is {1}".format(
  3316. pnumber, self.planets_list[self.target_number]["name"]
  3317. )
  3318. )
  3319. self.send2game("{0}\r".format(pnumber))
  3320. self.state = 4
  3321. elif self.state == 4:
  3322. # Item Colonists Colonists Daily Planet Ship Planet
  3323. # (1000s) 2 Build 1 Product Amount Amount Maximum
  3324. # ------- --------- --------- --------- --------- --------- ---------
  3325. # Fuel Ore 707 2 353 10,376 0 200,000
  3326. # Organics 651 5 130 4,304 0 200,000
  3327. # Equipment 1,641 20 82 2,618 0 100,000
  3328. # Fighters N/A 63 47 1,463 400 1,000,000
  3329. if line.startswith("Fuel Ore"):
  3330. work = re.split(r"\s+", line)
  3331. # log.debug("Ore - Pop: {0}, 2make1: {1} dailyproduct: {2} pamount: {3} saamount: {4} pmax: {5}".format(work[2], work[3], work[4], work[5], work[6], work[7]))
  3332. self.ore = {
  3333. "pop": self.check_resource(work[2]),
  3334. "make": self.check_resource(work[3]),
  3335. "daily": self.check_resource(work[4]),
  3336. "amount": self.check_resource(work[5]),
  3337. "ship": self.check_resource(work[6]),
  3338. "pmax": self.check_resource(work[7]),
  3339. }
  3340. self.last_seen["Ore"] = True
  3341. elif line.startswith("Organics"):
  3342. work = re.split(r"\s+", line)
  3343. # log.debug("Org - Pop: {0}, 2make1: {1} dailyproduct: {2} pamount: {3} saamount: {4} pmax: {5}".format(work[1], work[2], work[3], work[4], work[5], work[6]))
  3344. self.org = {
  3345. "pop": self.check_resource(work[1]),
  3346. "make": self.check_resource(work[2]),
  3347. "daily": self.check_resource(work[3]),
  3348. "amount": self.check_resource(work[4]),
  3349. "ship": self.check_resource(work[5]),
  3350. "pmax": self.check_resource(work[6]),
  3351. }
  3352. self.last_seen["Org"] = True
  3353. elif line.startswith("Equipment"):
  3354. work = re.split(r"\s+", line)
  3355. # log.debug("Equ - Pop: {0}, 2make1: {1} dailyproduct: {2} pamount: {3} saamount: {4} pmax: {5}".format(work[1], work[2], work[3], work[4], work[5], work[6]))
  3356. self.equ = {
  3357. "pop": self.check_resource(work[1]),
  3358. "make": self.check_resource(work[2]),
  3359. "daily": self.check_resource(work[3]),
  3360. "amount": self.check_resource(work[4]),
  3361. "ship": self.check_resource(work[5]),
  3362. "pmax": self.check_resource(work[6]),
  3363. }
  3364. self.last_seen["Equ"] = True
  3365. elif line.startswith("Fighters"):
  3366. work = re.split(r"\s+", line)
  3367. # log.debug("Fig - Pop: {0}, 2make1: {1} dailyproduct: {2} pamount: {3} saamount: {4} pmax: {5}".format(work[1], work[2], work[3], work[4], work[5], work[6]))
  3368. self.fig = {
  3369. "pop": self.check_resource(work[1]),
  3370. "make": self.check_resource(work[2]),
  3371. "daily": self.check_resource(work[3]),
  3372. "amount": self.check_resource(work[4]),
  3373. "ship": self.check_resource(work[5]),
  3374. "pmax": self.check_resource(work[6]),
  3375. }
  3376. self.last_seen["Fig"] = True
  3377. else:
  3378. if (
  3379. self.last_seen["Ore"] == True
  3380. and self.last_seen["Org"] == True
  3381. and self.last_seen["Equ"] == True
  3382. and self.last_seen["Fig"] == True
  3383. ):
  3384. if self.fig["daily"] > self.max_product:
  3385. self.max_product = self.fig["daily"]
  3386. self.planets_list[self.target_number]["Ore"] = self.ore
  3387. self.planets_list[self.target_number]["Org"] = self.org
  3388. self.planets_list[self.target_number]["Equ"] = self.equ
  3389. self.planets_list[self.target_number]["Fig"] = self.fig
  3390. log.debug("Max Production is {0}!".format(self.max_product))
  3391. self.state == 6
  3392. elif self.state == 12:
  3393. if line.startswith("Fuel Ore"):
  3394. work = re.split(r"\s+", line)
  3395. # log.debug("Ore - Pop: {0}, 2make1: {1} dailyproduct: {2} pamount: {3} saamount: {4} pmax: {5}".format(work[2], work[3], work[4], work[5], work[6], work[7]))
  3396. self.ore = {
  3397. "pop": self.check_resource(work[2]),
  3398. "make": self.check_resource(work[3]),
  3399. "daily": self.check_resource(work[4]),
  3400. "amount": self.check_resource(work[5]),
  3401. "ship": self.check_resource(work[6]),
  3402. "pmax": self.check_resource(work[7]),
  3403. }
  3404. self.last_seen["Ore"] = True
  3405. elif line.startswith("Organics"):
  3406. work = re.split(r"\s+", line)
  3407. # log.debug("Org - Pop: {0}, 2make1: {1} dailyproduct: {2} pamount: {3} saamount: {4} pmax: {5}".format(work[1], work[2], work[3], work[4], work[5], work[6]))
  3408. self.org = {
  3409. "pop": self.check_resource(work[1]),
  3410. "make": self.check_resource(work[2]),
  3411. "daily": self.check_resource(work[3]),
  3412. "amount": self.check_resource(work[4]),
  3413. "ship": self.check_resource(work[5]),
  3414. "pmax": self.check_resource(work[6]),
  3415. }
  3416. self.last_seen["Org"] = True
  3417. elif line.startswith("Equipment"):
  3418. work = re.split(r"\s+", line)
  3419. # log.debug("Equ - Pop: {0}, 2make1: {1} dailyproduct: {2} pamount: {3} saamount: {4} pmax: {5}".format(work[1], work[2], work[3], work[4], work[5], work[6]))
  3420. self.equ = {
  3421. "pop": self.check_resource(work[1]),
  3422. "make": self.check_resource(work[2]),
  3423. "daily": self.check_resource(work[3]),
  3424. "amount": self.check_resource(work[4]),
  3425. "ship": self.check_resource(work[5]),
  3426. "pmax": self.check_resource(work[6]),
  3427. }
  3428. self.last_seen["Equ"] = True
  3429. elif line.startswith("Fighters"):
  3430. work = re.split(r"\s+", line)
  3431. # log.debug("Fig - Pop: {0}, 2make1: {1} dailyproduct: {2} pamount: {3} saamount: {4} pmax: {5}".format(work[1], work[2], work[3], work[4], work[5], work[6]))
  3432. self.fig = {
  3433. "pop": self.check_resource(work[1]),
  3434. "make": self.check_resource(work[2]),
  3435. "daily": self.check_resource(work[3]),
  3436. "amount": self.check_resource(work[4]),
  3437. "ship": self.check_resource(work[5]),
  3438. "pmax": self.check_resource(work[6]),
  3439. }
  3440. self.last_seen["Fig"] = True
  3441. else:
  3442. if (
  3443. self.last_seen["Ore"] == True
  3444. and self.last_seen["Org"] == True
  3445. and self.last_seen["Equ"] == True
  3446. and self.last_seen["Fig"] == True
  3447. ):
  3448. if self.fig["daily"] > self.max_product:
  3449. self.max_product = self.fig["daily"]
  3450. self.planets_list[self.target_number]["Ore"] = self.ore
  3451. self.planets_list[self.target_number]["Org"] = self.org
  3452. self.planets_list[self.target_number]["Equ"] = self.equ
  3453. self.planets_list[self.target_number]["Fig"] = self.fig
  3454. log.debug("Max Production is now {0}!".format(self.max_product))
  3455. if self.fig["daily"] < self.max_product:
  3456. # Oh nose, our change actually made things worse... let's fix that and try a different way
  3457. if self.trying == "Ore2Org":
  3458. self.trying = "Org2Ore"
  3459. elif self.trying == "Ore2Equ":
  3460. self.trying = "Equ2Ore"
  3461. elif self.trying == "Org2Equ":
  3462. self.trying = "Equ2Org"
  3463. self.state = 6
  3464. if (
  3465. self.ore["pop"] < 1
  3466. or self.org["pop"] < 1
  3467. or self.equ["pop"] < 1
  3468. ):
  3469. self.send2game("Q")
  3470. self.send2player(
  3471. self.nl
  3472. + Boxes.alert(
  3473. "Peak Fighter Production: {0}".format(self.fig["daily"])
  3474. )
  3475. )
  3476. self.deactivate(True)
  3477. class evilTrade(object):
  3478. """
  3479. A little bit on playing evil,
  3480. Doing SSM, a bust will cause some holds and any cargo to be removed!
  3481. You must move to different ports to reduce the chance of a bust,
  3482. Bust's are reset after so many days... so might want to handle that.
  3483. SSM rewards you -10 Alignment and +5 Experiece if you are sucessful
  3484. in robbing back your cargo you just sold.
  3485. States:
  3486. 0 = Pre-State, Asks the user how many times to run
  3487. 1 = Gather user info
  3488. 2 = Verify Cargo is full of Equ, else jump to state 3.5
  3489. 3 = Find nearest "Evil Pair" of ports, move to first, jump to 4
  3490. 3.5 = User does not have Equ, lets buy it, then move on
  3491. (SSM: Sell-Steal-Move)
  3492. 4 = Port and Sell Equ
  3493. 5 = Port and Steal Equ
  3494. 6 = Move to 2nd "Evil Pair"
  3495. 7 = Port and Sell Equ
  3496. 8 = Port and Steal Equ
  3497. 9 = Move to 1st "Evil Pair"
  3498. 10 = Decide to loop, if so we jump back to state 4, else exit
  3499. """
  3500. def __init__(self, game):
  3501. self.game = game
  3502. self.queue_game = game.queue_game
  3503. self.queue_player = game.queue_player
  3504. self.observer = game.observer
  3505. self.r = Style.RESET_ALL
  3506. self.c = merge(Style.BRIGHT + Fore.YELLOW)
  3507. self.nl = "\n\r"
  3508. self.state = 0 # Pre-state
  3509. self.holds = 0 # Total holds empty, self.holds == self.cargo["Empty"]
  3510. self.cargo = {
  3511. "Ore": 0,
  3512. "Org": 0,
  3513. "Equ": 0,
  3514. "Colo": 0,
  3515. "Empty": 0,
  3516. } # What is in our holds?
  3517. self.maxHolds = 0 # Total holds
  3518. self.maxLoops = 0 # So when we display done show the total loops asked to do
  3519. self.loops = 0 # Current number of loops left to do
  3520. self.completeINFO = False # Collected all INFO needed
  3521. self.exp = 0 # Experience Points the player has
  3522. self.alignment = 0 # Alignment the player has
  3523. self.credits = 0 # Credits player has
  3524. self.turns = 0 # Turns the player has
  3525. self.sector = 0 # Current sector
  3526. self.sectors = False # Do we need to update sector1 and 2?
  3527. self.sector1 = None
  3528. self.sector2 = None
  3529. self.target_sector = 0 # Next port to trade with
  3530. self.name = "" # Player name to include into stats for logs
  3531. self.prompt = game.buffer
  3532. self.save = self.observer.save()
  3533. self.observer.connect("player", self.player)
  3534. self.observer.connect("prompt", self.game_prompt)
  3535. self.observer.connect("game-line", self.game_line)
  3536. self.defer = None
  3537. self.to_player = self.game.to_player
  3538. self.game.to_player = False
  3539. self.send2game("D")
  3540. def whenDone(self):
  3541. self.defer = defer.Deferred()
  3542. return self.defer
  3543. def deactivate(self, andExit=False):
  3544. self.state = 0
  3545. log.debug("EvilTrade.deactivate()")
  3546. self.game.to_player = True
  3547. assert not self.save is None
  3548. self.observer.load(self.save)
  3549. self.save = None
  3550. if self.defer:
  3551. if andExit:
  3552. self.defer.callback({"exit": True})
  3553. else:
  3554. self.defer.callback("done")
  3555. self.defer = None
  3556. def player(self, chunk: bytes):
  3557. self.deactivate(True)
  3558. def send2game(self, txt):
  3559. self.queue_player.put(txt)
  3560. def send2player(self, txt):
  3561. self.queue_game.put(txt)
  3562. def loops_chosen(self, choice: str):
  3563. if choice.strip() == "":
  3564. self.deactivate(True)
  3565. else:
  3566. self.loops = int(choice)
  3567. self.maxLoops = self.loops
  3568. self.state = 1
  3569. self.send2game("I")
  3570. def game_prompt(self, prompt: str):
  3571. log.debug("P {0} | {1}".format(self.state, prompt))
  3572. if self.state == 0:
  3573. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3574. ask = PlayerInput(self.game)
  3575. d = ask.prompt("How many times: ", 3, name="times", digits=True)
  3576. d.addCallback(self.loops_chosen)
  3577. elif self.state == 1:
  3578. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3579. if self.completeINFO: # We have all our info, lets display it into logs
  3580. log.debug("{0}'s Stats...".format(self.name))
  3581. log.debug(
  3582. "Experience: {0} Alignment: {1} Turns: {2} Credits: {3} Total Holds: {4} Avaible Holds: {5} Current Sector: {6}".format(
  3583. self.exp,
  3584. self.alignment,
  3585. self.turns,
  3586. self.credits,
  3587. self.maxHolds,
  3588. self.holds,
  3589. self.sector,
  3590. )
  3591. )
  3592. log.debug(
  3593. "Ore: {0} Org: {1} Equ: {2} Colo: {3} Empty: {4}".format(
  3594. self.cargo["Ore"],
  3595. self.cargo["Org"],
  3596. self.cargo["Equ"],
  3597. self.cargo["Colo"],
  3598. self.cargo["Empty"],
  3599. )
  3600. )
  3601. self.state = 2
  3602. self.send2game("D")
  3603. self.game.to_player = True
  3604. elif self.state == 2:
  3605. if self.cargo["Ore"] != 0: # Nada, we want Equ
  3606. self.send2player(
  3607. self.nl + Boxes.alert("Holds must contain Equ not Ore!")
  3608. )
  3609. self.deactivate(True)
  3610. elif self.cargo["Org"] != 0: # Oops, wrong, Give use Equ
  3611. self.send2player(
  3612. self.nl + Boxes.alert("Holds must contain Equ not Org!")
  3613. )
  3614. self.deactivate(True)
  3615. elif (
  3616. self.cargo["Colo"] != 0
  3617. ): # We don't want people, let the user handle this
  3618. self.send2player(
  3619. self.nl + Boxes.alert("Holds must contain Equ not Colonist!")
  3620. )
  3621. self.deactivate(True)
  3622. elif self.cargo["Equ"] != 0: # We do have Equ, but do we need more?
  3623. if self.cargo["Equ"] != self.maxHolds:
  3624. self.send2player(
  3625. self.nl
  3626. + Boxes.alert(
  3627. "You need {0} more Equ!".format(self.cargo["Empty"])
  3628. )
  3629. )
  3630. # Ok nope, we need more, let's find the nearest and "Mush!"
  3631. place = self.game.gamedata.find_nearest_selling(
  3632. self.sector, "E", 400
  3633. )
  3634. if place == 0:
  3635. self.queue_game.put(
  3636. self.nl + Boxes.alert("Find Nearest Failed!")
  3637. )
  3638. self.deactivate(True)
  3639. else:
  3640. self.send2game("{0}\rEPT".format(place))
  3641. # Code here to handle getting Equ
  3642. self.state = 3.5
  3643. else: # All OK, now to find_nearest_evilpairs
  3644. self.state = 3
  3645. self.game.to_player = False
  3646. self.send2game("D")
  3647. self.game.to_player = True
  3648. else: # Ok so we have Empty holds, lets fill it with Equ
  3649. place = self.game.gamedata.find_nearest_selling(self.sector, "E", 400)
  3650. if place == 0:
  3651. self.queue_game.put(self.nl + Boxes.alert("Find Nearest Failed!"))
  3652. self.deactivate(True)
  3653. else:
  3654. self.send2game("{0}\rEPT".format(place))
  3655. # Code here to handle getting Equ
  3656. self.state = 3.5
  3657. elif self.state == 3.5:
  3658. # Ok, we are getting Equ into holds then onto 3
  3659. if prompt.startswith("How many holds of Fuel Ore do you want to buy "):
  3660. self.send2game("0\r")
  3661. elif prompt.startswith("How many holds of Organics do you want to buy "):
  3662. self.send2game("0\r")
  3663. elif prompt.startswith("How many holds of Equipment do you want to buy "):
  3664. self.send2game("\r\r")
  3665. # Oops, we are expecting the user to have enough money to buy it!
  3666. self.state = 3
  3667. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3668. self.send2game("D")
  3669. self.state = 3
  3670. elif self.state == 3:
  3671. if prompt.startswith("Your offer"):
  3672. self.send2game("0\r")
  3673. self.deactivate(True)
  3674. else:
  3675. # Now to go to evil trade pair \o/
  3676. # Ok so if we go to line 2117 we can see how to use find_nearest_tradepairs()
  3677. # Which will give us a starting point for what needs to be done for us trading
  3678. log.info("find_nearest_evilpairs({0})".format(self.sector))
  3679. c = coiterate(
  3680. self.game.gamedata.find_nearest_evilpairs(self.sector, self)
  3681. )
  3682. c.addCallback(lambda unknown: self.evil())
  3683. self.state = 4
  3684. elif self.state == 4:
  3685. if prompt.startswith("Do you want to engage the TransWarp drive? "):
  3686. self.queue_player.put("N")
  3687. elif prompt.startswith(
  3688. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  3689. ):
  3690. self.queue_player.put("E")
  3691. elif prompt.startswith(
  3692. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  3693. ):
  3694. self.queue_player.put("N")
  3695. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3696. # We should be where we wanted to.
  3697. self.send2game("PT\r\r")
  3698. self.state = 5
  3699. elif self.state == 5:
  3700. if prompt.startswith("How many holds of Fuel Ore do you want to buy"):
  3701. self.send2game("0\r")
  3702. elif prompt.startswith("How many holds of Organics do you want to buy"):
  3703. self.send2game("0\r")
  3704. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3705. self.send2game("PR\rS3\r")
  3706. self.state = 6
  3707. elif self.state == 7:
  3708. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3709. c = coiterate(self.find_next_evilpair())
  3710. c.addCallback(lambda unknown: self.evil())
  3711. self.state = 8
  3712. elif self.state == 8:
  3713. if prompt.startswith("Do you want to engage the TransWarp drive? "):
  3714. self.queue_player.put("N")
  3715. elif prompt.startswith(
  3716. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  3717. ):
  3718. self.queue_player.put("E")
  3719. elif prompt.startswith(
  3720. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  3721. ):
  3722. self.queue_player.put("N")
  3723. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3724. # We should be where we wanted to.
  3725. self.send2game("PT\r\r")
  3726. self.state = 9
  3727. elif self.state == 9:
  3728. if prompt.startswith("How many holds of Fuel Ore do you want to buy"):
  3729. self.send2game("0\r")
  3730. elif prompt.startswith("How many holds of Organics do you want to buy"):
  3731. self.send2game("0\r")
  3732. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3733. self.send2game("PR\rS3\r")
  3734. self.state = 10
  3735. def evil(self):
  3736. if self.target_sector is None:
  3737. self.send2player(
  3738. self.nl + Boxes.alert("I don't see any ports to trade with.")
  3739. )
  3740. self.deactivate(True)
  3741. else:
  3742. self.send2game("{0}\r".format(self.target_sector))
  3743. if self.sectors == False:
  3744. self.sector1 = self.sector
  3745. self.sector2 = self.target_sector
  3746. self.sectors = True
  3747. self.sector = self.target_sector
  3748. def find_next_evilpair(self):
  3749. """ Find the next GOOD trade pair sector.
  3750. This is sequential (just like Trade report)
  3751. """
  3752. # This should be using the setting in the config, not a hard coded value!
  3753. # show_limit (galaxy.port_trade_show) is pct >= show_limit.
  3754. show_limit = self.game.gamedata.get_config("Display_Percent", "90")
  3755. try:
  3756. show_limit = int(show_limit)
  3757. except ValueError:
  3758. show_limit = 90
  3759. if show_limit < 15:
  3760. show_limit = 15
  3761. if show_limit > 90:
  3762. show_limit = 90
  3763. # Look for "GOOD" trades
  3764. for sector in sorted(self.game.gamedata.ports.keys()):
  3765. pd = self.game.gamedata.ports[sector]
  3766. if not GameData.port_burnt(pd):
  3767. # This happens when you trade with a StarDock
  3768. if "class" not in pd:
  3769. continue
  3770. pc = pd["class"]
  3771. # Ok, let's look into it.
  3772. if not sector in self.game.gamedata.warps:
  3773. continue
  3774. # Busted port
  3775. if not sector in self.game.gamedata.busts:
  3776. continue
  3777. warps = self.game.gamedata.warps[sector]
  3778. for w in warps:
  3779. # We can get there, and get back.
  3780. if (
  3781. w in self.game.gamedata.warps
  3782. and sector in self.game.gamedata.warps[w]
  3783. ):
  3784. # Ok, we can get there -- and get back!
  3785. if (
  3786. w > sector
  3787. and w in self.game.gamedata.ports
  3788. and not GameData.port_burnt(self.game.gamedata.ports[w])
  3789. ):
  3790. wd = self.game.gamedata.ports[w]
  3791. if "class" not in wd:
  3792. continue
  3793. wc = wd["class"]
  3794. if pc in (2, 3, 4, 8) and wc in (2, 3, 4, 8):
  3795. data = self.game.gamedata.port_trade_show(
  3796. sector, w, show_limit
  3797. )
  3798. if data:
  3799. self.target_sector = sector
  3800. return sector
  3801. yield
  3802. # Look for OK trades
  3803. for sector in sorted(self.game.gamedata.ports.keys()):
  3804. pd = self.game.gamedata.ports[sector]
  3805. if not GameData.port_burnt(pd):
  3806. if "class" not in pd:
  3807. continue
  3808. pc = pd["class"]
  3809. # Ok, let's look into it.
  3810. if not sector in self.game.gamedata.warps:
  3811. continue
  3812. # Busted port
  3813. if not sector in self.game.gamedata.busts:
  3814. continue
  3815. warps = self.game.gamedata.warps[sector]
  3816. for w in warps:
  3817. # We can get there, and get back.
  3818. if (
  3819. w in self.game.gamedata.warps
  3820. and sector in self.game.gamedata.warps[w]
  3821. ):
  3822. # Ok, we can get there -- and get back!
  3823. if (
  3824. w > sector
  3825. and w in self.game.gamedata.ports
  3826. and not GameData.port_burnt(self.game.gamedata.ports[w])
  3827. ):
  3828. wd = self.game.gamedata.ports[w]
  3829. if "class" not in wd:
  3830. continue
  3831. wc = wd["class"]
  3832. if GameData.port_trading(
  3833. pd["port"], self.game.gamedata.ports[w]["port"]
  3834. ):
  3835. data = self.game.gamedata.port_trade_show(
  3836. sector, w, show_limit
  3837. )
  3838. if data:
  3839. self.target_sector = sector
  3840. return sector
  3841. yield
  3842. self.target_sector = None
  3843. def game_line(self, line: str):
  3844. log.debug("L {0} | {1}".format(self.state, line))
  3845. if self.state == 1:
  3846. if line.startswith("Trader Name"):
  3847. work = line.replace("Trader Name :", "").split()
  3848. self.name = work[-1]
  3849. elif line.startswith("Current Sector"):
  3850. work = line.replace("Current Sector : ", "")
  3851. self.sector = int(work)
  3852. elif line.startswith("Rank and Exp"):
  3853. work = line.replace("Rank and Exp :", "").split()
  3854. # Rank and Exp : 110 points, Alignment=-116 Crass
  3855. self.exp = work[0]
  3856. self.alignment = work[2].replace("Alignment=", "")
  3857. elif line.startswith("Turns left"):
  3858. work = line.replace("Turns left : ", "")
  3859. self.turns = int(work)
  3860. elif line.startswith("Total Holds"):
  3861. work = (
  3862. line[16:]
  3863. .replace("-", "")
  3864. .replace("=", " ")
  3865. .replace("Fuel Ore", "Fuel")
  3866. .split()
  3867. )
  3868. self.maxHolds = int(work[0])
  3869. # Total Holds : 53 - Empty=53
  3870. # Total Holds : 53 - Fuel Ore=1 Organics=2 Equipment=3 Colonists=4 Empty=43
  3871. # log.debug(work)
  3872. # '53', 'Fuel', '1', 'Organics', '2', 'Equipment', '3', 'Colonists', '4', 'Empty', '43'
  3873. count = 0
  3874. for w in work:
  3875. if w == "Fuel":
  3876. try:
  3877. self.cargo["Ore"] = int(work[count + 1])
  3878. except ValueError: # The next value is not a number!
  3879. self.cargo["Ore"] = 0
  3880. elif w == "Organics":
  3881. try:
  3882. self.cargo["Org"] = int(work[count + 1])
  3883. except ValueError: # The next value is not a number!
  3884. self.cargo["Org"] = 0
  3885. elif w == "Equipment":
  3886. try:
  3887. self.cargo["Equ"] = int(work[count + 1])
  3888. except ValueError: # The next value is not a number!
  3889. self.cargo["Equ"] = 0
  3890. elif w == "Colonists":
  3891. try:
  3892. self.cargo["Colo"] = int(work[count + 1])
  3893. except ValueError: # The next value is not a number!
  3894. self.cargo["Colo"] = 0
  3895. elif w == "Empty":
  3896. try:
  3897. self.cargo["Empty"] = int(work[count + 1])
  3898. self.holds = self.cargo["Empty"]
  3899. except ValueError: # The next value is not a number!
  3900. self.cargo["Empty"] = 0
  3901. count += 1
  3902. elif line.startswith("Credits"):
  3903. work = line.replace("Credits : ", "").replace(",", "")
  3904. self.credits = int(work)
  3905. self.completeINFO = True
  3906. if self.state == 6:
  3907. if "Suddenly you're Busted!" in line:
  3908. # Oops! We got busted, let's stop.
  3909. self.deactivate(True)
  3910. elif "Success!" in line:
  3911. # Ok we passed that... now to move on.
  3912. self.state = 7
  3913. if self.state == 10:
  3914. if "Suddenly you're Busted!" in line:
  3915. # Oops! We got busted, let's stop.
  3916. self.deactivate(True)
  3917. elif "Success!" in line:
  3918. # Ok we passed that... now to move on.
  3919. self.loops -= 1
  3920. if self.loops >= 0:
  3921. self.send2player(
  3922. self.nl + Boxes.alert("Completed {0}".format(self.maxLoops))
  3923. )
  3924. self.deactivate(True)
  3925. else:
  3926. c = coiterate(self.find_next_evilpair())
  3927. c.addCallback(lambda unknown: self.evil())
  3928. self.state = 4
  3929. class bustViewer(object):
  3930. """ Display all busts
  3931. Perhaps also add it so we can manually reset/clear busts?
  3932. Or maybe...
  3933. We make galaxy's maint_busts() configurable so the check in days is in the config
  3934. States:
  3935. 0 = Perform convertion of self.game.gamedata.busts into a more understandable format.
  3936. 1 = Display/List all busts perferably just their sector numbers and when (what date) did that occur.
  3937. Optionals:
  3938. 1. Give numbering to state 0 so you can select a specific bust to be perhaps removed and/or add a remove all option.
  3939. (Dangerous, might not want to allow someone to manually reset all that)
  3940. 2. Add math that calculates the age in days for that particular bust. (Then add this to state 1 Display/List)
  3941. (Ok well this one should be really easy make a string/tuple storing month/day/year for both now and the bust then,)
  3942. (compare them one by one against eachother if 0 we know it's not that category) <- Should always be days since we are clearing them out automatically
  3943. """
  3944. def __init__(self, game):
  3945. self.game = game
  3946. self.queue_game = game.queue_game
  3947. self.queue_player = game.queue_player
  3948. self.observer = game.observer
  3949. self.r = Style.RESET_ALL
  3950. self.c = merge(Style.BRIGHT + Fore.YELLOW)
  3951. self.nl = "\n\r"
  3952. # Stuff
  3953. self.busted = {} # Make custom bust dict based on self.game.gamedata.busts dict
  3954. self.age = {}
  3955. self.state = 0 # Display/List
  3956. self.prompt = game.buffer
  3957. self.save = self.observer.save()
  3958. self.observer.connect("player", self.player)
  3959. self.observer.connect("prompt", self.game_prompt)
  3960. self.observer.connect("game-line", self.game_line)
  3961. self.defer = None
  3962. self.to_player = self.game.to_player
  3963. self.game.to_player = False
  3964. self.send2game("D") # Since we need to send at least 1 character
  3965. def whenDone(self):
  3966. self.defer = defer.Deferred()
  3967. return self.defer
  3968. def deactivate(self, andExit=False):
  3969. self.state = 0
  3970. log.debug("bustViewer.deactivate()")
  3971. self.game.to_player = True
  3972. assert not self.save is None
  3973. self.observer.load(self.save)
  3974. self.save = None
  3975. if self.defer:
  3976. if andExit:
  3977. self.defer.callback({"exit": True})
  3978. else:
  3979. self.defer.callback("done")
  3980. self.defer = None
  3981. def player(self, chunk: bytes):
  3982. self.deactivate(True)
  3983. def send2game(self, txt):
  3984. self.queue_player.put(txt)
  3985. def send2player(self, txt):
  3986. self.queue_game.put(txt)
  3987. def calcAge(self, dt):
  3988. rightNow = pendulum.now()
  3989. result = rightNow.diff(dt).in_days()
  3990. log.debug("calcAge('{0}') got {1} days".format(dt.to_datetime_string(), result))
  3991. return result
  3992. def game_prompt(self, prompt: str):
  3993. log.debug("P {0} | {1}".format(self.state, prompt))
  3994. if self.state == 0:
  3995. # Convert from YYYY-MM-DD to MM-DD-YYYY
  3996. for s in self.game.gamedata.busts:
  3997. d = self.game.gamedata.busts[s] # Keep as string
  3998. d1 = pendulum.parse(d) # Convert to dateTime obj
  3999. log.debug("{0} on {1}".format(s, d))
  4000. self.busted[s] = "{0:02d}-{1:02d}-{2:04d}".format(
  4001. d1.month, d1.day, d1.year
  4002. )
  4003. self.age[s] = self.calcAge(d1)
  4004. self.state += 1
  4005. self.send2game("D")
  4006. elif self.state == 1:
  4007. # Display it nicely to the user, then exit
  4008. tc = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  4009. c1 = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  4010. c2 = merge(Style.BRIGHT + Fore.CYAN + Back.BLUE)
  4011. if self.busted:
  4012. box = Boxes(42, color=tc)
  4013. self.queue_game.put(box.top())
  4014. self.queue_game.put(
  4015. box.row(
  4016. tc
  4017. + " {0:10} {1:<20} {2:8} ".format(
  4018. "Sector", "Date Busted On", "Days old"
  4019. )
  4020. )
  4021. )
  4022. self.queue_game.put(box.middle())
  4023. for s in self.busted:
  4024. if self.age[s]:
  4025. self.queue_game.put(
  4026. box.row(
  4027. c1
  4028. + " {0:<10} {1:<20} {2:8} ".format(
  4029. s, self.busted[s], self.age[s]
  4030. )
  4031. )
  4032. )
  4033. else:
  4034. self.queue_game.put(
  4035. box.row(
  4036. c1
  4037. + " {0:<10} {1:<20} ".format(s, self.busted[s])
  4038. )
  4039. )
  4040. self.queue_game.put(box.bottom())
  4041. else:
  4042. self.send2player(
  4043. self.nl
  4044. + Boxes.alert(
  4045. "You have no busts to view, perhaps you just aren't into trouble."
  4046. )
  4047. )
  4048. self.deactivate(True)
  4049. def game_line(self, line: str):
  4050. log.debug("L {0} | {1}".format(self.state, line))
  4051. class firstActivate(object):
  4052. """ Upon first time activation of the proxy what happens
  4053. States:
  4054. 0 = Send V and gather information on when busts were cleared
  4055. 1 = Calculate date from pendulum.now().subtract(days=#)
  4056. 2 = If pendulum.now() is greater than our date to clear then self.game.gamedata.reset_busts()
  4057. Well drat... while in a game you can't access when busts were cleared. :(
  4058. """
  4059. def __init__(self, game):
  4060. self.game = game
  4061. self.queue_game = game.queue_game
  4062. self.queue_player = game.queue_player
  4063. self.observer = game.observer
  4064. self.r = Style.RESET_ALL
  4065. self.c = merge(Style.BRIGHT + Fore.YELLOW)
  4066. self.nl = "\n\r"
  4067. # Stuffz
  4068. self.state = 0 # V and gather info
  4069. self.prompt = game.buffer
  4070. self.save = self.observer.save()
  4071. self.observer.connect("player", self.player)
  4072. self.observer.connect("prompt", self.game_prompt)
  4073. self.observer.connect("game-line", self.game_line)
  4074. self.defer = None
  4075. self.to_player = self.game.to_player
  4076. self.game.to_player = False
  4077. self.send2game("V") # Since we need to send at least 1 character
  4078. def whenDone(self):
  4079. self.defer = defer.Deferred()
  4080. return self.defer
  4081. def deactivate(self, andExit=False):
  4082. self.state = 0
  4083. log.debug("firstActivate.deactivate()")
  4084. self.game.to_player = True
  4085. assert not self.save is None
  4086. self.observer.load(self.save)
  4087. self.save = None
  4088. if self.defer:
  4089. if andExit:
  4090. self.defer.callback({"exit": True})
  4091. else:
  4092. self.defer.callback("done")
  4093. self.defer = None
  4094. def player(self, chunk: bytes):
  4095. self.deactivate(True)
  4096. def send2game(self, txt):
  4097. self.queue_player.put(txt)
  4098. def send2player(self, txt):
  4099. self.queue_game.put(txt)
  4100. def game_prompt(self, prompt: str):
  4101. log.debug("P {0} | {1}".format(self.state, prompt))
  4102. if self.state == 0:
  4103. # Enable sloppy-shit mode. This shows random parts
  4104. # of the command line because you don't wait for
  4105. # the entire commandline to be displayed.
  4106. # There's a darn good reason I worked on the regex to
  4107. # match the prompt...
  4108. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  4109. # if prompt.startswith("Command"):
  4110. self.deactivate()
  4111. def game_line(self, line: str):
  4112. log.debug("L {0} | {1}".format(self.state, line))
  4113. class ProxyMenu(object):
  4114. """ Display ProxyMenu
  4115. Example:
  4116. from flexible import ProxyMenu
  4117. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  4118. menu = ProxyMenu(self.game)
  4119. """
  4120. def __init__(self, game):
  4121. self.nl = "\n\r"
  4122. self.c = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  4123. self.r = Style.RESET_ALL
  4124. self.c1 = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  4125. self.c2 = merge(Style.NORMAL + Fore.CYAN + Back.BLUE)
  4126. # self.portdata = None
  4127. self.game = game
  4128. self.queue_game = game.queue_game
  4129. self.observer = game.observer
  4130. self.game.gamedata.get_config("Macro", "D^1N^D")
  4131. # Am I using self or game? (I think I want game, not self.)
  4132. # if hasattr(self.game, "portdata"):
  4133. # self.portdata = self.game.portdata
  4134. # else:
  4135. # self.portdata = {}
  4136. # if hasattr(self.game, 'warpdata'):
  4137. # self.warpdata = self.game.warpdata
  4138. # else:
  4139. # self.warpdata = {}
  4140. if hasattr(self.game, "trade_report"):
  4141. self.trade_report = self.game.trade_report
  4142. else:
  4143. self.trade_report = []
  4144. # Yes, at this point we would activate
  4145. self.prompt = game.buffer
  4146. self.save = self.observer.save()
  4147. self.observer.connect("player", self.player)
  4148. # If we want it, it's here.
  4149. self.defer = None
  4150. self.game.to_player = True
  4151. # Is it our first time activated? if so do a little extra stuff.
  4152. if self.game.gamedata.activated == False:
  4153. self.game.gamedata.activated = True
  4154. # Run V to get date of bust clear from game
  4155. # Decide to clear or not
  4156. # Clear or continue on
  4157. log.debug("First time activation dectected!")
  4158. first = firstActivate(self.game)
  4159. d = first.whenDone()
  4160. d.addCallback(self.pre_back)
  4161. d.addErrback(self.pre_back)
  4162. else:
  4163. # well that was all skipped because we already did that.
  4164. self.pre_back()
  4165. def __del__(self):
  4166. log.debug("ProxyMenu {0} RIP".format(self))
  4167. # When we exit, always make sure player echo is on.
  4168. self.game.to_player = True
  4169. def pre_back(self, stuffz=None):
  4170. self.keepalive = task.LoopingCall(self.awake)
  4171. self.keepalive.start(30)
  4172. self.menu()
  4173. def whenDone(self):
  4174. self.defer = defer.Deferred()
  4175. # Call this to chain something after we exit.
  4176. return self.defer
  4177. def menu(self):
  4178. box = Boxes(30, color=self.c)
  4179. self.queue_game.put(box.top())
  4180. text = self.c + "{0:^30}".format("TradeWars Proxy Active")
  4181. text = text.replace("Active", BLINK + "Active" + Style.RESET_ALL + self.c)
  4182. self.queue_game.put(box.row(text))
  4183. self.queue_game.put(box.bottom())
  4184. self.queue_game.put(" " + self.c + "-=>" + self.r + " ")
  4185. def fullmenu(self):
  4186. box = Boxes(30, color=self.c)
  4187. self.queue_game.put(box.top())
  4188. def menu_item(ch: str, desc: str):
  4189. row = self.c1 + " {0} {1}- {2}{3:25}".format(ch, self.c2, self.c1, desc)
  4190. self.queue_game.put(box.row(row))
  4191. # self.queue_game.put(
  4192. # " " + self.c1 + ch + self.c2 + " - " + self.c1 + desc + self.nl
  4193. # )
  4194. menu_item("C", "Configuration ({0})".format(len(self.game.gamedata.config)))
  4195. menu_item("D", "Display Report again")
  4196. menu_item("E", "Export Data (Save)")
  4197. # menu_item("Q", "Quest")
  4198. menu_item("M", "Macro")
  4199. menu_item("P", "Port CIM Report ({0})".format(len(self.game.gamedata.ports)))
  4200. menu_item("W", "Warp CIM Report ({0})".format(len(self.game.gamedata.warps)))
  4201. menu_item("R", "Restock Report")
  4202. menu_item("T", "Trading Report")
  4203. menu_item("B", "Display Busts ({0})".format(len(self.game.gamedata.busts)))
  4204. menu_item("S", "Scripts")
  4205. menu_item("X", "eXit")
  4206. bottom = box.bottom()
  4207. self.queue_game.put(bottom[:-2])
  4208. def awake(self):
  4209. log.info("ProxyMenu.awake()")
  4210. self.game.queue_player.put(" ")
  4211. def port_report(self, portdata: dict):
  4212. # Check to see if the old data is close to the new data.
  4213. # If so, don't toss out the special!
  4214. matches = 0
  4215. for k, v in self.old_ports.items():
  4216. if k in self.game.gamedata.ports:
  4217. # Ok, key exists. Is the class the same
  4218. if self.game.gamedata.ports[k]["class"] == v["class"]:
  4219. matches += 1
  4220. log.info("Got {0} matches old ports to new.".format(matches))
  4221. if matches > 12:
  4222. self.queue_game.put(
  4223. "Restoring (SPECIAL) class ports ({0}).".format(len(self.specials))
  4224. + self.nl
  4225. )
  4226. for p in self.specials.keys():
  4227. self.game.gamedata.ports[int(p)] = self.specials[p]
  4228. # self.portdata = portdata
  4229. # self.game.portdata = portdata
  4230. self.queue_game.put("Loaded {0} ports.".format(len(self.game.ports)) + self.nl)
  4231. self.welcome_back()
  4232. def warp_report(self, warpdata: dict):
  4233. # self.warpdata = warpdata
  4234. # self.game.warpdata = warpdata
  4235. self.queue_game.put("Loaded {0} sectors.".format(len(warpdata)) + self.nl)
  4236. self.welcome_back()
  4237. def make_trade_report(self):
  4238. log.debug("make_trade_report()")
  4239. ok_trades = []
  4240. best_trades = []
  4241. show_best = self.game.gamedata.get_config("Display_Best", "Y").upper()[0] == "Y"
  4242. show_ok = self.game.gamedata.get_config("Display_Ok", "N").upper()[0] == "Y"
  4243. show_limit = self.game.gamedata.get_config("Display_Percent", "90")
  4244. update_config = False
  4245. try:
  4246. show_limit = int(show_limit)
  4247. except ValueError:
  4248. show_limit = 90
  4249. update_config = True
  4250. if show_limit < 0:
  4251. show_limit = 0
  4252. update_config = True
  4253. elif show_limit > 100:
  4254. show_limit = 100
  4255. update_config = True
  4256. if update_config:
  4257. self.game.gamedata.set_config("Display_Percent", show_limit)
  4258. # for sector, pd in self.game.gamedata.ports.items():
  4259. for sector in sorted(self.game.gamedata.ports.keys()):
  4260. pd = self.game.gamedata.ports[sector]
  4261. if not GameData.port_burnt(pd):
  4262. # This happens if you trade with a StarDock. (It doesn't get the class set.)
  4263. if "class" not in pd:
  4264. continue
  4265. pc = pd["class"]
  4266. # Ok, let's look into it.
  4267. if not sector in self.game.gamedata.warps:
  4268. continue
  4269. warps = self.game.gamedata.warps[sector]
  4270. for w in warps:
  4271. # Verify that we have that warp's info, and that the sector is in it.
  4272. # (We can get back from it)
  4273. if (
  4274. w in self.game.gamedata.warps
  4275. and sector in self.game.gamedata.warps[w]
  4276. ):
  4277. # Ok, we can get there -- and get back!
  4278. if (
  4279. w > sector
  4280. and w in self.game.gamedata.ports
  4281. and not GameData.port_burnt(self.game.gamedata.ports[w])
  4282. ):
  4283. # it is > and has a port.
  4284. wd = self.game.gamedata.ports[w]
  4285. if "class" not in wd:
  4286. continue
  4287. wc = wd["class"]
  4288. # 1: "BBS",
  4289. # 2: "BSB",
  4290. # 3: "SBB",
  4291. # 4: "SSB",
  4292. # 5: "SBS",
  4293. # 6: "BSS",
  4294. # 7: "SSS",
  4295. # 8: "BBB",
  4296. if pc in (1, 5) and wc in (2, 4):
  4297. data = self.game.gamedata.port_trade_show(
  4298. sector, w, show_limit
  4299. )
  4300. if data:
  4301. best_trades.append(data)
  4302. # best_trades.append( "{0:5} -=- {1:5}".format(sector, w))
  4303. elif pc in (2, 4) and wc in (1, 5):
  4304. data = self.game.gamedata.port_trade_show(
  4305. sector, w, show_limit
  4306. )
  4307. if data:
  4308. best_trades.append(data)
  4309. # best_trades.append( "{0:5} -=- {1:5}".format(sector, w))
  4310. elif GameData.port_trading(
  4311. pd["port"], self.game.gamedata.ports[w]["port"]
  4312. ):
  4313. # ok_trades.append( "{0:5} -=- {1:5}".format(sector,w))
  4314. data = self.game.gamedata.port_trade_show(
  4315. sector, w, show_limit
  4316. )
  4317. if data:
  4318. ok_trades.append(data)
  4319. yield
  4320. if show_best:
  4321. self.trade_report.append("Best Trades: (org/equ)")
  4322. self.trade_report.extend(best_trades)
  4323. if show_ok:
  4324. self.trade_report.append("Ok Trades:")
  4325. self.trade_report.extend(ok_trades)
  4326. if not show_best and not show_ok:
  4327. self.queue_game.put(
  4328. Boxes.alert(
  4329. "You probably want to choose something to display in configuration!",
  4330. base="red",
  4331. )
  4332. )
  4333. # self.queue_game.put("BEST TRADES:" + self.nl + self.nl.join(best_trades) + self.nl)
  4334. # self.queue_game.put("OK TRADES:" + self.nl + self.nl.join(ok_trades) + self.nl)
  4335. def get_display_maxlines(self):
  4336. show_maxlines = self.game.gamedata.get_config("Display_Maxlines", "0")
  4337. try:
  4338. show_maxlines = int(show_maxlines)
  4339. except ValueError:
  4340. show_maxlines = 0
  4341. if show_maxlines <= 0:
  4342. show_maxlines = None
  4343. return show_maxlines
  4344. def show_trade_report(self, *_):
  4345. show_maxlines = self.get_display_maxlines()
  4346. self.game.trade_report = self.trade_report
  4347. for t in self.trade_report[:show_maxlines]:
  4348. self.queue_game.put(t + self.nl)
  4349. self.queue_game.put(self.nl + Boxes.alert("Proxy done.", base="green"))
  4350. self.observer.load(self.save)
  4351. self.save = None
  4352. self.keepalive = None
  4353. self.prompt = None
  4354. # self.welcome_back()
  4355. def player(self, chunk: bytes):
  4356. """ Data from player (in bytes). """
  4357. chunk = chunk.decode("latin-1", "ignore")
  4358. key = chunk.upper()
  4359. log.debug("ProxyMenu.player({0})".format(key))
  4360. # Stop the keepalive if we are activating something else
  4361. # or leaving...
  4362. self.keepalive.stop()
  4363. if key == "T":
  4364. self.queue_game.put(self.c + key + self.r + self.nl)
  4365. # Trade Report
  4366. # do we have enough information to do this?
  4367. # if not hasattr(self.game, 'portdata') and not hasattr(self.game, 'warpdata'):
  4368. # self.queue_game.put("Missing portdata and warpdata." + self.nl)
  4369. # elif not hasattr(self.game, 'portdata'):
  4370. # self.queue_game.put("Missing portdata." + self.nl)
  4371. # elif not hasattr(self.game, 'warpdata'):
  4372. # self.queue_game.put("Missing warpdata." + self.nl)
  4373. # else:
  4374. if True:
  4375. # Yes, so let's start!
  4376. self.trade_report = []
  4377. d = coiterate(self.make_trade_report())
  4378. d.addCallback(self.show_trade_report)
  4379. return
  4380. elif key == "P":
  4381. self.queue_game.put(self.c + key + self.r + self.nl)
  4382. # Save specials, save 10 ports
  4383. self.specials = self.game.gamedata.special_ports()
  4384. # Save 20 ports. https://stackoverflow.com/questions/7971618/python-return-first-n-keyvalue-pairs-from-dict#7971655
  4385. self.old_ports = {
  4386. k: self.game.gamedata.ports[k]
  4387. for k in list(self.game.gamedata.ports)[:20]
  4388. }
  4389. self.game.gamedata.reset_ports()
  4390. # Activate CIM Port Report
  4391. report = CIMPortReport(self.game)
  4392. d = report.whenDone()
  4393. d.addCallback(self.port_report)
  4394. d.addErrback(self.welcome_back)
  4395. return
  4396. elif key == "W":
  4397. self.queue_game.put(self.c + key + self.r + self.nl)
  4398. self.game.gamedata.reset_warps()
  4399. # Activate CIM Warp Report
  4400. report = CIMWarpReport(self.game)
  4401. d = report.whenDone()
  4402. d.addCallback(self.warp_report)
  4403. d.addErrback(self.welcome_back)
  4404. return
  4405. elif key == "M":
  4406. self.queue_game.put(self.c + key + self.r + self.nl)
  4407. self.activate_macro(1)
  4408. if False:
  4409. ask = PlayerInput(self.game)
  4410. d = ask.prompt(
  4411. "How many times?", 10, name="times", abort_blank=True, digits=True
  4412. )
  4413. d.addCallback(self.activate_macro)
  4414. d.addErrback(self.welcome_back)
  4415. return
  4416. elif key == "B":
  4417. self.queue_game.put(self.c + key + self.r + self.nl)
  4418. # Display Busts
  4419. busting = bustViewer(self.game)
  4420. d = busting.whenDone()
  4421. d.addCallback(self.welcome_back)
  4422. d.addErrback(self.welcome_back)
  4423. return
  4424. elif key == "S":
  4425. self.queue_game.put(self.c + key + self.r + self.nl)
  4426. # Scripts
  4427. self.activate_scripts_menu()
  4428. return
  4429. elif key == "R":
  4430. self.queue_game.put(self.c + key + self.r + self.nl)
  4431. s = self.game.gamedata.special_ports()
  4432. box = Boxes(14, color=self.c)
  4433. self.queue_game.put(box.top())
  4434. self.queue_game.put(box.row(self.c1 + " Sector Class "))
  4435. for sector, data in s.items():
  4436. self.queue_game.put(
  4437. box.row(
  4438. "{0} {1:5}{2} {3:^5} ".format(
  4439. self.c1, sector, self.c2, data["class"]
  4440. )
  4441. )
  4442. )
  4443. self.queue_game.put(box.bottom())
  4444. elif key == "D":
  4445. self.queue_game.put(self.c + key + self.r + self.nl)
  4446. # (Re) Display Trade Report
  4447. show_maxlines = self.get_display_maxlines()
  4448. if self.trade_report:
  4449. for t in self.trade_report[:show_maxlines]:
  4450. self.queue_game.put(t + self.nl)
  4451. self.queue_game.put(self.nl + Boxes.alert("Proxy done.", base="green"))
  4452. self.observer.load(self.save)
  4453. self.save = None
  4454. self.keepalive = None
  4455. self.prompt = None
  4456. return
  4457. else:
  4458. self.queue_game.put("Missing trade_report." + self.nl)
  4459. elif key == "E":
  4460. self.queue_game.put(self.c + key + self.r + self.nl)
  4461. self.queue_game.put(Boxes.alert("Saving..."))
  4462. then_do = coiterate(self.game.gamedata.save())
  4463. then_do.addCallback(self.welcome_back)
  4464. return
  4465. elif key == "C":
  4466. self.queue_game.put(self.c + key + self.r + self.nl)
  4467. self.activate_config_menu()
  4468. return
  4469. # self.queue_game.put(pformat(self.portdata).replace("\n", "\n\r") + self.nl)
  4470. # self.queue_game.put(pformat(self.warpdata).replace("\n", "\n\r") + self.nl)
  4471. # elif key == "Q":
  4472. # self.queue_game.put(self.c + key + self.r + self.nl)
  4473. #
  4474. # # This is an example of chaining PlayerInput prompt calls.
  4475. #
  4476. # ask = PlayerInput(self.game)
  4477. # d = ask.prompt("What is your quest?", 40, name="quest", abort_blank=True)
  4478. #
  4479. # # Display the user's input
  4480. # d.addCallback(ask.output)
  4481. #
  4482. # d.addCallback(
  4483. # lambda ignore: ask.prompt(
  4484. # "What is your favorite color?", 10, name="color"
  4485. # )
  4486. # )
  4487. # d.addCallback(ask.output)
  4488. #
  4489. # d.addCallback(
  4490. # lambda ignore: ask.prompt(
  4491. # "What is the meaning of the squirrel?",
  4492. # 12,
  4493. # name="squirrel",
  4494. # digits=True,
  4495. # )
  4496. # )
  4497. # d.addCallback(ask.output)
  4498. #
  4499. # def show_values(show):
  4500. # log.debug(show)
  4501. # self.queue_game.put(pformat(show).replace("\n", "\n\r") + self.nl)
  4502. #
  4503. # d.addCallback(lambda ignore: show_values(ask.keep))
  4504. # d.addCallback(self.welcome_back)
  4505. #
  4506. # # On error, just return back
  4507. # # This doesn't seem to be getting called.
  4508. # # d.addErrback(lambda ignore: self.welcome_back)
  4509. # d.addErrback(self.welcome_back)
  4510. # return
  4511. elif key == "X":
  4512. self.queue_game.put(self.c + key + self.r + self.nl)
  4513. self.queue_game.put(Boxes.alert("Proxy done.", base="green"))
  4514. self.observer.load(self.save)
  4515. self.save = None
  4516. # It isn't running (NOW), so don't try to stop it.
  4517. # self.keepalive.stop()
  4518. self.keepalive = None
  4519. # Ok, this is a HORRIBLE idea, because the prompt might be
  4520. # outdated.
  4521. # self.queue_game.put(self.prompt)
  4522. self.prompt = None
  4523. # Send '\r' to re-display the prompt
  4524. # instead of displaying the original one.
  4525. self.game.queue_player.put("d")
  4526. # Were we asked to do something when we were done here?
  4527. if self.defer:
  4528. reactor.CallLater(0, self.defer.callback)
  4529. # self.defer.callback()
  4530. self.defer = None
  4531. return
  4532. else:
  4533. self.fullmenu()
  4534. self.keepalive.start(30, True)
  4535. self.menu()
  4536. def activate_config_menu(self):
  4537. self.observer.disconnect("player", self.player)
  4538. self.observer.connect("player", self.config_player)
  4539. self.config_menu()
  4540. def deactivate_config_menu(self, *data):
  4541. log.warn("deactivate_config_menu ({0})".format(data))
  4542. self.observer.disconnect("player", self.config_player)
  4543. self.observer.connect("player", self.player)
  4544. self.welcome_back()
  4545. def activate_macro(self, *data):
  4546. log.warn("macro: ({0})".format(data))
  4547. macro = self.game.gamedata.get_config("Macro", "D")
  4548. # Macro processing would go in here ...
  4549. macro = macro.replace("^", "\r")
  4550. log.warn("macro: [{0}]".format(repr(macro)))
  4551. self.game.queue_player.put(macro)
  4552. log.warn("Restore ...")
  4553. self.observer.load(self.save)
  4554. self.save = None
  4555. self.keepalive = None
  4556. if self.defer:
  4557. reactor.CallLater(0, self.defer.callback)
  4558. self.defer = None
  4559. # self.welcome_back()
  4560. def activate_scripts_menu(self):
  4561. self.observer.disconnect("player", self.player)
  4562. self.observer.connect("player", self.scripts_player)
  4563. self.scripts_menu()
  4564. def option_entry(self, entry):
  4565. if len(entry) > 0:
  4566. # Ok, they gave us something
  4567. self.game.gamedata.set_config(self.option_select, entry.strip())
  4568. else:
  4569. self.queue_game.put("Edit aborted." + self.nl)
  4570. self.config_menu()
  4571. def option_input(self, option):
  4572. if len(option) > 0:
  4573. option = int(option)
  4574. if option in self.config_opt:
  4575. # Ok, it's a valid option!
  4576. self.option_select = self.config_opt[option]
  4577. ask = PlayerInput(self.game)
  4578. if self.option_select == "Macro":
  4579. d = ask.prompt("Change {0} to?".format(self.option_select), 48)
  4580. else:
  4581. d = ask.prompt("Change {0} to?".format(self.option_select), 18)
  4582. d.addCallback(self.option_entry)
  4583. # d.addErrback(self.config_menu)
  4584. else:
  4585. self.queue_game.put("Unknown option, sorry." + self.nl)
  4586. self.config_menu()
  4587. else:
  4588. # Aborted
  4589. self.config_menu()
  4590. def config_player(self, chunk: bytes):
  4591. """ Data from player (in bytes). """
  4592. chunk = chunk.decode("latin-1", "ignore")
  4593. key = chunk.upper()
  4594. if key == "C":
  4595. self.queue_game.put(self.c + key + self.r + self.nl)
  4596. self.game.gamedata.config = {}
  4597. elif key == "E":
  4598. self.queue_game.put(self.c + key + self.r + self.nl)
  4599. ask = PlayerInput(self.game)
  4600. d = ask.prompt(
  4601. "Which to edit?", 4, name="option", abort_blank=True, digits=True
  4602. )
  4603. d.addCallback(self.option_input)
  4604. d.addErrback(self.config_menu)
  4605. return
  4606. elif key in ("1", "2", "3", "4", "5", "6", "7", "8", "9"):
  4607. self.queue_game.put(self.c + key + self.r + self.nl)
  4608. option = int(key)
  4609. if option in self.config_opt:
  4610. # Ok, it's a valid option!
  4611. self.option_select = self.config_opt[option]
  4612. ask = PlayerInput(self.game)
  4613. if self.option_select == "Macro":
  4614. d = ask.prompt("Change {0} to?".format(self.option_select), 48)
  4615. else:
  4616. d = ask.prompt("Change {0} to?".format(self.option_select), 18)
  4617. d.addCallback(self.option_entry)
  4618. # d.addErrback(self.config_menu)
  4619. return
  4620. else:
  4621. self.queue_game.put("Unknown option, sorry." + self.nl)
  4622. elif key == "X":
  4623. self.queue_game.put(self.c + key + self.r + self.nl)
  4624. self.deactivate_config_menu()
  4625. return
  4626. else:
  4627. self.queue_game.put(self.c + "?" + self.r + self.nl)
  4628. self.config_menu()
  4629. def config_menu(self, *_):
  4630. titlecolor = merge(Style.BRIGHT + Fore.CYAN + Back.BLUE)
  4631. tc = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  4632. c1 = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  4633. c2 = merge(Style.BRIGHT + Fore.CYAN + Back.BLUE)
  4634. # box = Boxes(44, color=titlecolor)
  4635. box = Boxes(44, color=tc)
  4636. self.queue_game.put(box.top())
  4637. # self.queue_game.put(box.row(titlecolor + "{0:^44}".format("Configuration")))
  4638. self.queue_game.put(box.row(tc + "{0:^44}".format("Configuration")))
  4639. self.queue_game.put(box.middle())
  4640. def config_option(index, key, value):
  4641. # Really, python? Because
  4642. # builtins.ValueError: Precision not allowed in integer format specifier
  4643. if type(value) == int:
  4644. value = str(value)
  4645. row = "{0}{1:2} {2:19}{3}{4:<20.20}".format(c1, index, key, c2, value)
  4646. self.queue_game.put(box.row(row))
  4647. def menu_item(ch, desc):
  4648. row = "{0} {1} {2}-{3} {4:39}".format(c1, ch, c2, c1, desc)
  4649. # self.queue_game.put(
  4650. # " " + c1 + ch + c2 + " - " + c1 + desc + self.nl
  4651. # )
  4652. self.queue_game.put(box.row(row))
  4653. index = 1
  4654. self.config_opt = {}
  4655. for k in sorted(self.game.gamedata.config.keys()):
  4656. # for k, v in self.game.gamedata.config.items():
  4657. v = self.game.gamedata.config[k]
  4658. self.config_opt[index] = k
  4659. config_option(index, k, v)
  4660. index += 1
  4661. self.queue_game.put(box.middle())
  4662. menu_item("C", "Clear Config")
  4663. menu_item("E", "Edit Item")
  4664. menu_item("X", "eXit")
  4665. self.queue_game.put(box.bottom())
  4666. self.queue_game.put(" " + tc + "-=>" + self.r + " ")
  4667. def deactivate_scripts_menu(self, *data):
  4668. log.warn("deactivate_scripts_menu ({0})".format(data))
  4669. self.observer.disconnect("player", self.scripts_player)
  4670. self.observer.connect("player", self.player)
  4671. # Did they request exit?
  4672. if len(data) > 0 and type(data[0]) == dict:
  4673. info = data[0]
  4674. if "exit" in info and info["exit"]:
  4675. log.warn("exit proxy...")
  4676. # Exit Proxy Code
  4677. self.queue_game.put(
  4678. self.nl + Boxes.alert("Proxy done.", base="green", style=3)
  4679. )
  4680. self.observer.load(self.save)
  4681. self.save = None
  4682. # It isn't running (NOW), so don't try to stop it.
  4683. # self.keepalive.stop()
  4684. self.keepalive = None
  4685. # Ok, this is a HORRIBLE idea, because the prompt might be
  4686. # outdated.
  4687. # self.queue_game.put(self.prompt)
  4688. self.prompt = None
  4689. # I'm not sure where we are, we might not be at a prompt.
  4690. # let's check!
  4691. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", self.game.getPrompt()):
  4692. # Send '\r' to re-display the prompt
  4693. # instead of displaying the original one.
  4694. self.game.queue_player.put("d")
  4695. # Were we asked to do something when we were done here?
  4696. if self.defer:
  4697. reactor.CallLater(0, self.defer.callback)
  4698. # self.defer.callback()
  4699. self.defer = None
  4700. return
  4701. log.warn("calling welcome_back")
  4702. self.welcome_back()
  4703. def scripts_menu(self, *_):
  4704. c1 = merge(Style.BRIGHT + Fore.CYAN)
  4705. c2 = merge(Style.NORMAL + Fore.CYAN)
  4706. box = Boxes(40, color=c1)
  4707. self.queue_game.put(box.top())
  4708. self.queue_game.put(box.row(c1 + "{0:^40}".format("Scripts")))
  4709. self.queue_game.put(box.middle())
  4710. def menu_item(ch, desc):
  4711. row = " {0}{1} {2}-{3} {4:35}".format(c1, ch, c2, c1, desc)
  4712. # self.queue_game.put(
  4713. # " " + c1 + ch + c2 + " - " + c1 + desc + self.nl
  4714. # )
  4715. self.queue_game.put(box.row(row))
  4716. menu_item("1", "Ports (Trades between two sectors)")
  4717. menu_item("!", "Terrorize Ports/Trades")
  4718. menu_item("2", "Explore (Strange new sectors)")
  4719. menu_item("3", "Space... the broken script...")
  4720. menu_item("4", "Upgrade Planet")
  4721. # menu_item("5", "Colonize Planet")
  4722. menu_item("5", "Colonize Planet v2.0")
  4723. menu_item("%", "Maxumize Fighter Production")
  4724. menu_item("6", "Trade Evil (Does SSM)")
  4725. menu_item("X", "eXit")
  4726. self.queue_game.put(box.bottom())
  4727. self.queue_game.put(" " + c1 + "-=>" + self.r + " ")
  4728. def terror(self, *_):
  4729. log.debug("terror {0}".format(_))
  4730. loops = _[0]
  4731. if loops.strip() == "":
  4732. self.deactivate_scripts_menu()
  4733. else:
  4734. # Ok, we have something here, I think...
  4735. terror = ScriptTerror(self.game, self, int(loops))
  4736. d = terror.whenDone()
  4737. d.addCallback(self.deactivate_scripts_menu)
  4738. d.addErrback(self.deactivate_scripts_menu)
  4739. def scripts_player(self, chunk: bytes):
  4740. """ Data from player (in bytes). """
  4741. chunk = chunk.decode("latin-1", "ignore")
  4742. key = chunk.upper()
  4743. if key == "1":
  4744. self.queue_game.put(self.c + key + self.r + self.nl)
  4745. # Activate this magical event here
  4746. ports = ScriptPort(self.game)
  4747. d = ports.whenDone()
  4748. # d.addCallback(self.scripts_menu)
  4749. # d.addErrback(self.scripts_menu)
  4750. d.addCallback(self.deactivate_scripts_menu)
  4751. d.addErrback(self.deactivate_scripts_menu)
  4752. return
  4753. elif key == "!":
  4754. self.queue_game.put(self.c + key + self.r + self.nl)
  4755. ask = PlayerInput(self.game)
  4756. # This is TERROR, so do something!
  4757. ask.color(merge(Style.BRIGHT + Fore.WHITE + Back.RED))
  4758. ask.colorp(merge(Style.BRIGHT + Fore.YELLOW + Back.RED))
  4759. d = ask.prompt(
  4760. "How many loops of terror?",
  4761. 4,
  4762. name="loops",
  4763. digits=True,
  4764. abort_blank=True,
  4765. )
  4766. d.addCallback(self.terror, ask)
  4767. d.addErrback(self.deactivate_scripts_menu)
  4768. return
  4769. elif key == "2":
  4770. self.queue_game.put(self.c + key + self.r + self.nl)
  4771. explore = ScriptExplore(self.game)
  4772. d = explore.whenDone()
  4773. d.addCallback(self.deactivate_scripts_menu)
  4774. d.addErrback(self.deactivate_scripts_menu)
  4775. return
  4776. elif key == "3":
  4777. self.queue_game.put(self.c + key + self.r + self.nl)
  4778. space = ScriptSpace(self.game)
  4779. d = space.whenDone()
  4780. d.addCallback(self.deactivate_scripts_menu)
  4781. d.addErrback(self.deactivate_scripts_menu)
  4782. return
  4783. elif key == "4":
  4784. self.queue_game.put(self.c + key + self.r + self.nl)
  4785. upgrade = PlanetUpScript(self.game)
  4786. d = upgrade.whenDone()
  4787. d.addCallback(self.deactivate_scripts_menu)
  4788. d.addErrback(self.deactivate_scripts_menu)
  4789. return
  4790. elif key == "5":
  4791. self.queue_game.put(self.c + key + self.r + self.nl)
  4792. # colo = ColoScript(self.game)
  4793. colo = ColoScript2(self.game)
  4794. d = colo.whenDone()
  4795. d.addCallback(self.deactivate_scripts_menu)
  4796. d.addErrback(self.deactivate_scripts_menu)
  4797. return
  4798. elif key == "%":
  4799. self.queue_game.put(self.c + key + self.r + self.nl)
  4800. maxfigs = MaxFighterMake(self.game)
  4801. d = maxfigs.whenDone()
  4802. d.addCallback(self.deactivate_scripts_menu)
  4803. d.addErrback(self.deactivate_scripts_menu)
  4804. return
  4805. elif key == "6":
  4806. self.queue_game.put(self.c + key + self.r + self.nl)
  4807. evil = evilTrade(self.game)
  4808. d = evil.whenDone()
  4809. d.addCallback(self.deactivate_scripts_menu)
  4810. d.addErrback(self.deactivate_scripts_menu)
  4811. return
  4812. elif key == "X":
  4813. self.queue_game.put(self.c + key + self.r + self.nl)
  4814. self.deactivate_scripts_menu()
  4815. return
  4816. else:
  4817. self.queue_game.put(self.c + "?" + self.r + self.nl)
  4818. self.scripts_menu()
  4819. def welcome_back(self, *_):
  4820. log.debug("welcome_back")
  4821. self.keepalive.start(30, True)
  4822. self.menu()