flexible.py 200 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039
  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 game_prompt(self, prompt):
  2081. log.info("prompt {0} : {1}".format(self.state, prompt))
  2082. if self.state == 1 and re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2083. # Ok, you're not on a team. :P
  2084. self.queue_player.put("CYQ")
  2085. if self.state == 2 and re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2086. if self.corp:
  2087. self.corp = False
  2088. self.state = 1
  2089. self.queue_player.put("CYQ")
  2090. return
  2091. self.game.to_player = True
  2092. # For now we output the information, and exit
  2093. # self.queue_game.put("{0}\r\n".format(self.planets))
  2094. # self.queue_game.put(pformat(self.planets).replace("\n", self.nl) + self.nl)
  2095. if len(self.planets) == 0:
  2096. # Ok, this is easy.
  2097. self.queue_game.put(
  2098. self.nl
  2099. + Boxes.alert(
  2100. "You don't have any planets? You poor, poor dear.", base="red"
  2101. )
  2102. )
  2103. self.deactivate()
  2104. return
  2105. # I need this to know if I can just land, or need to move to the planet.
  2106. # Get current sector from the prompt
  2107. # Command [TL=00:00:00]:[10202] (?=Help)? :
  2108. _, _, part = prompt.partition("]:[")
  2109. sector, _, _ = part.partition("]")
  2110. self.current_sector = int(sector)
  2111. # A better default is to ask which planet to upgrade.
  2112. tc = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  2113. c1 = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  2114. c2 = merge(Style.BRIGHT + Fore.CYAN + Back.BLUE)
  2115. box = Boxes(44, color=tc)
  2116. self.queue_game.put(box.top())
  2117. self.queue_game.put(
  2118. box.row(
  2119. tc
  2120. + "{0:3} {1:6} {2:20} {3} ".format(
  2121. " # ", "Sector", "Planet Name", "Citadel LVL"
  2122. )
  2123. )
  2124. )
  2125. self.queue_game.put(box.middle())
  2126. def planet_output(number, sector, name, citadel):
  2127. row = "{0}{1:^3} {2:6} {3}{4:29} {0}{5:2} ".format(
  2128. c1, number, sector, c2, name, citadel
  2129. )
  2130. self.queue_game.put(box.row(row))
  2131. for s in sorted(self.planets.keys()):
  2132. planet_output(
  2133. s,
  2134. self.planets[s]["sector"],
  2135. self.planets[s]["name"],
  2136. self.planets[s]["citadel"],
  2137. )
  2138. self.queue_game.put(box.bottom())
  2139. ask = PlayerInput(self.game)
  2140. d = ask.prompt("Choose a planet", 3, name="planet", digits=True)
  2141. d.addCallback(self.planet_chosen)
  2142. elif self.state == 3:
  2143. if prompt.startswith("Do you want to engage the TransWarp drive? "):
  2144. self.queue_player.put("N")
  2145. elif prompt.startswith(
  2146. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2147. ):
  2148. self.queue_player.put("E")
  2149. elif prompt.startswith(
  2150. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  2151. ):
  2152. self.queue_player.put("N")
  2153. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2154. # We're here!
  2155. self.state = 4
  2156. self.queue_player.put("L")
  2157. elif self.state == 4:
  2158. # If you have a planet scanner, or if there's more then one planet.
  2159. if prompt.startswith("Land on which planet <Q to abort> ?"):
  2160. self.queue_player.put("{0}\r".format(self.planet_number))
  2161. if prompt.startswith("Planet command (?=help) [D] "):
  2162. # self.queue_game.put(self.nl + "{0} : {1}".format( self.colonists, self.cargo) + self.nl)
  2163. self.state = 5
  2164. self.queue_player.put("C")
  2165. elif self.state == 5:
  2166. if re.match(r"Do you wish to construct .+\?", prompt):
  2167. # 'Do you wish to construct a Combat Control Computer?'
  2168. # Have we met all the needs? If so, do it. ;)
  2169. # If not, xfer the cargo on the ship to the planet and get moving!
  2170. ready = True
  2171. for i in self.index_cargo: # ['F', 'O', 'E']:
  2172. if self.need[i] > self.cargo[i]:
  2173. ready = False
  2174. log.info("Need: {0}".format(i))
  2175. # break
  2176. if self.need["C"] > self.colonists:
  2177. log.info("Need: people")
  2178. ready = False
  2179. # self.queue_game.put(self.nl + "{0}".format(self.need))
  2180. if ready:
  2181. self.queue_game.put(self.nl + Boxes.alert("Party Planet Pants On!"))
  2182. self.queue_player.put("YQ")
  2183. if self.citadel:
  2184. # Need extra Quit to get out of citadel, then out of planet.
  2185. self.queue_player.put("Q")
  2186. self.deactivate()
  2187. return
  2188. if "construct one" in prompt:
  2189. # No, but start moving things around to build one.
  2190. self.queue_player.put("N")
  2191. else:
  2192. # No, and quit the Citadel menu.
  2193. self.queue_player.put("NQ")
  2194. # Xfer cargo, and get ready to travel...
  2195. elif prompt.startswith("Citadel command (?=help)"):
  2196. self.queue_player.put("U")
  2197. self.citadel = True
  2198. if prompt.startswith("Planet command (?=help) [D] "):
  2199. # self.queue_game.put(pformat(self.ship_cargo).replace("\n", self.nl) + self.nl)
  2200. # self.queue_game.put(pformat(self.cargo).replace("\n", self.nl) + self.nl)
  2201. for idx, c in enumerate(self.index_cargo): # ('F', 'O', 'E')):
  2202. if self.ship_cargo[c] > 0:
  2203. # Transfer Cargo, (No display), Leave [1,2, or 3], \r = All of it.
  2204. self.queue_player.put("TNL{0}\r".format(idx + 1))
  2205. self.cargo[c] += self.ship_cargo[c]
  2206. self.ship_cargo[c] = 0
  2207. return
  2208. break
  2209. self.queue_player.put("Q")
  2210. self.state = 6
  2211. # self.queue_game.put(pformat(self.ship_cargo).replace("\n", self.nl) + self.nl)
  2212. # self.queue_game.put(pformat(self.cargo).replace("\n", self.nl) + self.nl)
  2213. # self.deactivate()
  2214. elif self.state == 6:
  2215. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2216. # Ok, what do we need and where do we get it?
  2217. if self.need["C"] > self.colonists:
  2218. # NavPoint, T, Express
  2219. self.fetch = "C"
  2220. self.queue_player.put("NTE")
  2221. self.state = 7
  2222. self.send_land = False
  2223. else:
  2224. for i in ("F", "O", "E"):
  2225. if self.need[i] > self.cargo[i]:
  2226. self.fetch = i
  2227. # TODO: Make this a config setting.
  2228. place = self.game.gamedata.find_nearest_selling(
  2229. self.planet_sector, i, 400
  2230. )
  2231. if place == 0:
  2232. self.queue_game.put(
  2233. self.nl + Boxes.alert("Find Nearest Failed!")
  2234. )
  2235. self.deactivate()
  2236. return
  2237. self.queue_player.put("{0}\r".format(place))
  2238. # self.queue_player.put("{0}\rE".format(place))
  2239. self.state = 7
  2240. return
  2241. # Ok, upgrade time!
  2242. self.state = 4
  2243. self.queue_player.put("L")
  2244. # self.queue_game.put("No, not yet!" + self.nl)
  2245. # self.deactivate()
  2246. # for i in ['F', 'O', 'E']:
  2247. # if self.need[i] > self.cargo[i]:
  2248. # ready = False
  2249. # self.queue_game.put( "Need: {0}".format(i) + self.nl)
  2250. elif self.state == 7:
  2251. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2252. if self.fetch == "C":
  2253. # Colonist
  2254. # [How many groups of Colonists do you want to take ([125] empty holds) ? ]
  2255. if self.send_land == False:
  2256. self.send_land = True
  2257. self.queue_player.put("L") # "LT\r")
  2258. elif self.fetch in self.index_cargo: # ('F', 'O', 'E'):
  2259. # Port, Trade
  2260. self.queue_player.put("pt")
  2261. elif re.match(r"How many holds of .+ do you want to sell", prompt):
  2262. # This shouldn't occur...
  2263. self.queue_game.put("OH NOSE!" + self.nl)
  2264. self.deactivate()
  2265. return
  2266. elif prompt.startswith("Do you want to engage the TransWarp drive? "):
  2267. self.queue_player.put("N")
  2268. elif prompt.startswith(
  2269. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2270. ):
  2271. self.queue_player.put("E")
  2272. elif prompt.startswith(
  2273. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  2274. ):
  2275. self.queue_player.put("N")
  2276. elif re.match(
  2277. r"How many holds of .+ do you want to buy \[\d+\]\? ", prompt
  2278. ):
  2279. if prompt.startswith("How many holds of " + self.fetch):
  2280. _, _, holds = prompt.partition("[")
  2281. holds, _, _ = holds.partition("]")
  2282. self.fetch_amount = int(holds)
  2283. log.info("Buying {0} of {1}".format(holds, self.fetch))
  2284. self.queue_player.put("\r\r")
  2285. self.state = 8
  2286. else:
  2287. # We don't want to buy this one. Skip it!
  2288. self.queue_player.put("0\r")
  2289. elif prompt.startswith("Land on which planet <Q to abort> ?"):
  2290. if self.fetch == "C":
  2291. self.queue_player.put("1\r")
  2292. elif prompt.startswith(
  2293. "Do you wish to (L)eave or (T)ake Colonists? [T] (Q to leave)"
  2294. ):
  2295. if self.fetch == "C":
  2296. self.queue_player.put("T\r")
  2297. self.state = 8
  2298. elif self.state == 8:
  2299. if re.match(r"How many holds of .+ do you want to buy \[\d+\]\? ", prompt):
  2300. # No, no, we're done buying!
  2301. self.queue_player.put("0\r")
  2302. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2303. # Ok, return to the planet...
  2304. self.queue_player.put("{0}\rE".format(self.planet_sector))
  2305. self.state = 9
  2306. elif self.state == 9:
  2307. log.info("prompt9 {0} : {1}".format(self.state, prompt))
  2308. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2309. # land
  2310. self.queue_player.put("L")
  2311. elif prompt.startswith("Do you want to engage the TransWarp drive? "):
  2312. self.queue_player.put("N")
  2313. elif prompt.startswith(
  2314. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2315. ):
  2316. self.queue_player.put("E")
  2317. elif prompt.startswith("Engage Express mode? (Y/N) [N] "):
  2318. self.queue_player.put("Y")
  2319. elif prompt.startswith(
  2320. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  2321. ):
  2322. self.queue_player.put("N")
  2323. elif prompt.startswith("Land on which planet <Q to abort> ?"):
  2324. self.queue_player.put("{0}\r".format(self.planet_number))
  2325. elif prompt.startswith("Planet command (?=help) [D]"):
  2326. if self.fetch == "C":
  2327. # Colonist / No display Planet / Leave
  2328. self.queue_player.put("SNL")
  2329. elif self.fetch in self.index_cargo: # ('F', 'O', 'E'):
  2330. # Cargo, No display / Leave
  2331. self.queue_player.put("TNL")
  2332. elif prompt.startswith("(1)Ore, (2)Org or (3)Equipment ?"):
  2333. self.queue_player.put(
  2334. "{0}\r\rQ".format(self.cargo_index[self.fetch] + 1)
  2335. )
  2336. self.cargo[self.fetch] += self.fetch_amount
  2337. self.state = 6
  2338. elif prompt.startswith("(1)Ore, (2)Org or (3)Equipment Production?"):
  2339. log.info("place_people: {0}".format(self.place_people))
  2340. safe_places = [
  2341. k for k in self.place_people.keys() if self.place_people[k]
  2342. ]
  2343. if len(safe_places) == 0:
  2344. # Ok, (GREAT) Class "U" Vaporous/Gaseus >:(
  2345. safe_places = ["F", "O", "E"]
  2346. # TO FIX: Use self.place_people to decide.
  2347. # Ok, I'd choose, but for right now.
  2348. log.info("Safe {0} index {1}".format(safe_places, self.place_start))
  2349. put_people = safe_places[self.place_start]
  2350. log.info("Use: {0}".format(put_people))
  2351. self.place_start += 1
  2352. if self.place_start >= len(safe_places):
  2353. self.place_start = 0
  2354. self.queue_player.put(
  2355. "{0}\r\rQ".format(self.cargo_index[put_people] + 1)
  2356. )
  2357. self.colonists += self.fetch_amount
  2358. self.state = 6
  2359. def planet_chosen(self, choice: str):
  2360. if choice.strip() == "":
  2361. self.deactivate()
  2362. else:
  2363. self.planet_number = int(choice)
  2364. if self.planet_number in self.planets:
  2365. # Ok, this'll work
  2366. self.planet_sector = self.planets[self.planet_number]["sector"]
  2367. self.planet_name = self.planets[self.planet_number]["name"]
  2368. if self.current_sector == self.planet_sector:
  2369. # We're here. Land
  2370. self.state = 4
  2371. self.queue_player.put("L")
  2372. else:
  2373. # Get moving!
  2374. self.state = 3
  2375. self.queue_player.put("{0}\r".format(self.planet_sector))
  2376. else:
  2377. self.deactivate()
  2378. def game_line(self, line):
  2379. log.info("line {0} : {1}".format(self.state, line))
  2380. if self.state == 1:
  2381. if "Personal Planet Scan" in line or "Corporate Planet Scan" in line:
  2382. self.state = 2
  2383. elif self.state == 2:
  2384. # Ok, we're in the planet scan part of this
  2385. # 10202 #3 Home of Bugz Class M, Earth Type No Citadel]
  2386. if "#" in line:
  2387. # Ok, we have a planet detail line.
  2388. # There's an extra T when the planet is maxed out.
  2389. if line[7] == "T":
  2390. line = line[:7] + " " + line[8:]
  2391. details, _, citadel = line.partition("Class")
  2392. # log.info(details) # Is that what we are after?
  2393. # log.info(citadel)
  2394. sector, planet_number, name = re.split(r"\s+", details.strip(), 2)
  2395. sector = int(sector)
  2396. number = int(planet_number.replace("#", ""))
  2397. if "Level" in citadel:
  2398. cit = int(citadel[-1]) # Grab last item
  2399. else: # Oops, there looks like there is no citadel here.
  2400. cit = 0
  2401. self.last_seen = number
  2402. self.planets[number] = {"sector": sector, "name": name, "citadel": cit}
  2403. log.info(
  2404. "Planet # {0} in {1} called {2} with a lvl {3} citadel".format(
  2405. number, sector, name, cit
  2406. )
  2407. )
  2408. # detail, _, _ = line.partition('Class')
  2409. # detail = detail.strip() # Sector #X Name of planet
  2410. # sector, number, name = re.split(r'\s+', detail, 2)
  2411. # sector = int(sector)
  2412. # number = int(number[1:])
  2413. # self.last_seen = number
  2414. # self.planets[number] = {"sector": sector, "name": name}
  2415. # log.info("Planet # {0} in {1} called {2}".format( number, sector, name))
  2416. if "---" in line:
  2417. number = self.last_seen
  2418. # Ok, take the last_seen number, and use it for this line
  2419. # [ Sector Planet Name Ore Org Equ Ore Org Equ Fighters Citadel]
  2420. # [ Shields Population -=Productions=- -=-=-=-=-On Hands-=-=-=-=- Credits]
  2421. # [ 10202 #3 Home of Bugz Class M, Earth Type No Citadel]
  2422. # [ --- (1M) 144 49 26 145 75 12 10 0]
  2423. details = re.split(r"\s+", line.strip())
  2424. # OK: Likely, I'm not going to use these numbers AT ALL.
  2425. self.planets[number]["population"] = (
  2426. details[1].replace("(", "").replace(")", "")
  2427. )
  2428. # Ok, there's going to have to be some sort of modifier (K, M, etc.)
  2429. # to these numbers. Beware!
  2430. self.planets[number]["ore"] = details[5]
  2431. self.planets[number]["org"] = details[6]
  2432. self.planets[number]["equ"] = details[7]
  2433. elif self.state == 4:
  2434. # Combat Control Computer under construction, 4 day(s) till complete.
  2435. if "under construction, " in line and "day(s) till complete" in line:
  2436. # Ok, already building.
  2437. self.queue_game.put(self.nl + Boxes.alert("NO, NOT YET!") + self.nl)
  2438. self.queue_player.put("Q") # quit Planet menu.
  2439. self.deactivate()
  2440. return
  2441. # [ Item Colonists Colonists Daily Planet Ship Planet ]
  2442. # [Fuel Ore 0 1 0 0 0 1,000,000]
  2443. # [Organics 0 N/A 0 0 0 10,000]
  2444. # [Equipment 0 500 0 125 125 100,000]
  2445. # [Fighters N/A N/A 0 0 400 1,000,000]
  2446. items = ["Fuel Ore", "Organics", "Equipment"]
  2447. for i in items:
  2448. if line.startswith(i):
  2449. cargo = line[0].upper()
  2450. work = line.replace(",", "")
  2451. if i == "Fuel Ore":
  2452. work = work.replace(i, "Fuel")
  2453. self.colonists = 0
  2454. self.cargo = {}
  2455. self.need = {}
  2456. self.ship_cargo = {}
  2457. self.place_people = {}
  2458. parts = re.split(r"\s+", work)
  2459. log.info("parts: {0}".format(parts))
  2460. c = int(parts[1])
  2461. planet_has = int(parts[4])
  2462. self.colonists += c
  2463. self.cargo[cargo] = planet_has
  2464. self.ship_cargo[cargo] = int(parts[5])
  2465. # Boolean, can we place people here? If N/A, then don't!
  2466. self.place_people[cargo] = parts[2] != "N/A"
  2467. self.place_start = 0
  2468. elif self.state == 5:
  2469. # [Planet command (?=help) [D] C]
  2470. # [Be patient, your Citadel is not yet finished.]
  2471. if line.startswith("Be patient, your Citadel is not yet finished."):
  2472. # Ah HA!
  2473. self.queue_game.put(self.nl + Boxes.alert("NO, NOT YET!") + self.nl)
  2474. self.queue_player.put("Q") # quit Planet menu.
  2475. self.deactivate()
  2476. elif line.startswith("This Citadel cannot be upgraded further"):
  2477. self.queue_game.put(self.nl + Boxes.alert("NO MORE!") + self.nl)
  2478. self.queue_player.put("QQ") # quit Citadel, quit Planet menu.
  2479. self.deactivate()
  2480. else:
  2481. items = ["Colonists", "Fuel Ore", "Organics", "Equipment"]
  2482. work = line.replace(",", "").replace(" units of", "").strip()
  2483. # 800,000 Colonists to support the construction,
  2484. # 500 units of Fuel Ore,
  2485. # 300 units of Organics,
  2486. # 600 units of Equipment and
  2487. for i in items:
  2488. if i in line:
  2489. count = int(work.split()[0])
  2490. k = i[0].upper()
  2491. # keep colonists in same units.
  2492. if k == "C":
  2493. count //= 1000
  2494. self.need[k] = count
  2495. elif self.state == 8:
  2496. if re.match(
  2497. r"How many groups of Colonists do you want to take \(\[\d+\] empty holds\) \?",
  2498. line,
  2499. ):
  2500. # Ok, how many holds?
  2501. _, _, holds = line.partition("[")
  2502. holds, _, _ = holds.partition("]")
  2503. self.fetch_amount = int(holds)
  2504. if line.startswith("One turn deducted, "):
  2505. parts = line.split()
  2506. turns = int(parts[3])
  2507. if turns < 200:
  2508. self.queue_game.put(self.nl + Boxes.alert("LOW TURNS.") + self.nl)
  2509. self.deactivate()
  2510. elif self.state == 9:
  2511. if re.match(r"You have \d turns left.", line):
  2512. parts = line.split()
  2513. turns = int(parts[2])
  2514. log.debug("Turns: {0}".format(turns))
  2515. def __del__(self):
  2516. log.debug("PlanetUpScript {0} RIP".format(self))
  2517. def whenDone(self):
  2518. self.defer = defer.Deferred()
  2519. # Call this to chain something after we exit.
  2520. return self.defer
  2521. def deactivate(self):
  2522. self.state = 0
  2523. if not self.defer is None:
  2524. # We have something, so:
  2525. self.game.to_player = self.to_player
  2526. self.observer.load(self.save)
  2527. self.save = None
  2528. self.defer.callback(1)
  2529. self.defer = None
  2530. else:
  2531. # Still "exit" out.
  2532. self.game.to_player = self.to_player
  2533. self.observer.load(self.save)
  2534. def player(self, chunk):
  2535. """ Data from player (in bytes). """
  2536. chunk = chunk.decode("latin-1", "ignore")
  2537. key = chunk.upper()
  2538. log.warn(
  2539. "PlanetUpScript.player({0}) : I AM stopping...(user input)".format(key)
  2540. )
  2541. if not self.defer is None:
  2542. # We have something, so:
  2543. self.game.to_player = self.to_player
  2544. self.observer.load(self.save)
  2545. self.save = None
  2546. self.defer.errback(Exception("User Abort"))
  2547. self.defer = None
  2548. else:
  2549. # Still "exit" out.
  2550. self.game.to_player = self.to_player
  2551. self.observer.load(self.save)
  2552. class ColoScript2(object):
  2553. """ ColoScript 2.0
  2554. Goal:
  2555. * Allow a player to move people from anywhere to anywhere. (Acheived!)
  2556. States:
  2557. 1 = Computer talks with us giving corp and personal planet info
  2558. 2 = Grab's data and asks series of questions, TO, FROM, LOOPS
  2559. 3 = Move to FROM
  2560. 4 = Identify Population Categories / Is it terra?
  2561. 5 = Load People, then move to planet TO
  2562. 6 = Init Land on TO
  2563. 7 = Decide to loop (Jump back to 3), Unload People
  2564. """
  2565. def __init__(self, game):
  2566. self.game = game
  2567. self.queue_game = game.queue_game
  2568. self.queue_player = game.queue_player
  2569. self.observer = game.observer
  2570. self.r = Style.RESET_ALL
  2571. self.c = merge(Style.BRIGHT + Fore.YELLOW)
  2572. self.nl = "\n\r"
  2573. # My "stuff" in my pants!
  2574. self.state = 1
  2575. self.corp = True
  2576. self.planets = {}
  2577. self.loops = 0
  2578. self.maxloops = 0
  2579. self.last_seen = 0
  2580. # Sector Numbers of Planets TO and FROM
  2581. self.TO = 0
  2582. self.FROM = 0
  2583. # Planet Numbers of Planets TO and FROM
  2584. self.to_number = 0
  2585. self.from_number = 0
  2586. # Activate
  2587. self.prompt = game.buffer
  2588. self.save = self.observer.save()
  2589. self.observer.connect("player", self.player)
  2590. self.observer.connect("prompt", self.game_prompt)
  2591. self.observer.connect("game-line", self.game_line)
  2592. self.defer = None
  2593. self.to_player = self.game.to_player
  2594. self.game.to_player = False
  2595. self.send2game("TLQ")
  2596. def whenDone(self):
  2597. self.defer = defer.Deferred()
  2598. return self.defer
  2599. def deactivate(self, andExit=False):
  2600. self.state = 0
  2601. log.debug("ColoScript2.deactivate()")
  2602. self.game.to_player = True
  2603. assert not self.save is None
  2604. self.observer.load(self.save)
  2605. self.save = None
  2606. if self.defer:
  2607. if andExit:
  2608. self.defer.callback({"exit": True})
  2609. else:
  2610. self.defer.callback("done")
  2611. self.defer = None
  2612. def player(self, chunk: bytes):
  2613. self.deactivate(True)
  2614. def send2game(self, txt):
  2615. # Removed debug info since I use this to also display Boxes.alert
  2616. self.queue_player.put(txt)
  2617. def send2player(self, txt):
  2618. # Removed debug since it really doesn't help with anything
  2619. self.queue_game.put(txt)
  2620. def to_chosen(self, choice: str):
  2621. if choice.strip() == "":
  2622. self.deactivate(True)
  2623. else:
  2624. self.to_number = int(choice)
  2625. if self.to_number in self.planets:
  2626. # Ok, this'll work
  2627. self.TO = self.planets[self.to_number]["sector"]
  2628. self.planet_name = self.planets[self.to_number]["name"]
  2629. # Are we really getting this? Yup
  2630. # log.debug("TO Planet Number: {0} Sector: {1}".format(self.to_number, self.TO))
  2631. ask1 = PlayerInput(self.game)
  2632. d1 = ask1.prompt("From: (1 = Terra) ", 3, name="from", digits=True)
  2633. d1.addCallback(self.from_chosen)
  2634. else:
  2635. self.deactivate(True)
  2636. def from_chosen(self, choice: str):
  2637. if choice.strip() == "":
  2638. self.deactivate(True)
  2639. else:
  2640. self.from_number = int(choice)
  2641. if self.from_number in self.planets:
  2642. # Ok, this'll work
  2643. self.FROM = self.planets[self.from_number]["sector"]
  2644. self.planet_name = self.planets[self.from_number]["name"]
  2645. # Are we really getting this? Yup Yup
  2646. # log.debug("FROM Planet Number: {0} Sector: {1}".format(self.from_number, self.FROM))
  2647. ask1 = PlayerInput(self.game)
  2648. d1 = ask1.prompt("How many times ", 3, name="rolls", digits=True)
  2649. d1.addCallback(self.loop_chosen)
  2650. elif self.from_number == 1:
  2651. # Yup handle if the user picks to pull from Terra
  2652. self.FROM = 1
  2653. ask1 = PlayerInput(self.game)
  2654. d1 = ask1.prompt("How many times ", 3, name="rolls", digits=True)
  2655. d1.addCallback(self.loop_chosen)
  2656. else:
  2657. self.deactivate(True)
  2658. def loop_chosen(self, choice: str):
  2659. if choice.strip() == "":
  2660. self.deactivate(True)
  2661. else:
  2662. self.loops = abs(int(choice))
  2663. if self.loops == 0:
  2664. self.loops = 1
  2665. self.maxloops = self.loops
  2666. # ask2 = PlayerInput(self.game)
  2667. # d2 = ask2.prompt("From? ", 5, name="from", digits=True)
  2668. # d2.addCallback(self.from_chosen)
  2669. self.state = 3
  2670. self.game.to_player = False
  2671. self.send2game("I")
  2672. def game_prompt(self, prompt: str):
  2673. log.debug("P {0} | {1}".format(self.state, prompt))
  2674. if self.state == 1 and re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2675. # Ok, you're not on a team. :P
  2676. self.queue_player.put("CYQ")
  2677. if self.state == 2 and re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2678. if self.corp:
  2679. self.corp = False
  2680. self.state = 1
  2681. self.queue_player.put("CYQ")
  2682. return
  2683. self.game.to_player = True
  2684. # For now we output the information, and exit
  2685. # self.queue_game.put("{0}\r\n".format(self.planets))
  2686. # self.queue_game.put(pformat(self.planets).replace("\n", self.nl) + self.nl)
  2687. if len(self.planets) == 0:
  2688. # Ok, this is easy.
  2689. self.queue_game.put(
  2690. self.nl
  2691. + Boxes.alert(
  2692. "You don't have any planets? You poor, poor dear.", base="red"
  2693. )
  2694. )
  2695. self.deactivate(True)
  2696. return
  2697. # I need this to know if I can just land, or need to move to the planet.
  2698. # Get current sector from the prompt
  2699. # Command [TL=00:00:00]:[10202] (?=Help)? :
  2700. _, _, part = prompt.partition("]:[")
  2701. sector, _, _ = part.partition("]")
  2702. self.current_sector = int(sector)
  2703. # A better default is to ask which planet to upgrade.
  2704. tc = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  2705. c1 = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  2706. c2 = merge(Style.BRIGHT + Fore.CYAN + Back.BLUE)
  2707. box = Boxes(44, color=tc)
  2708. self.queue_game.put(box.top())
  2709. self.queue_game.put(
  2710. box.row(
  2711. tc
  2712. + "{0:3} {1:6} {2:20} {3} ".format(
  2713. " # ", "Sector", "Planet Name", "Citadel LVL"
  2714. )
  2715. )
  2716. )
  2717. self.queue_game.put(box.middle())
  2718. def planet_output(number, sector, name, citadel):
  2719. row = "{0}{1:^3} {2:6} {3}{4:29} {0}{5:2} ".format(
  2720. c1, number, sector, c2, name, citadel
  2721. )
  2722. self.queue_game.put(box.row(row))
  2723. for s in sorted(self.planets.keys()):
  2724. planet_output(
  2725. s,
  2726. self.planets[s]["sector"],
  2727. self.planets[s]["name"],
  2728. self.planets[s]["citadel"],
  2729. )
  2730. self.queue_game.put(box.bottom())
  2731. ask = PlayerInput(self.game)
  2732. d = ask.prompt("To: ", 3, name="planet", digits=True)
  2733. d.addCallback(self.to_chosen)
  2734. elif self.state == 3:
  2735. # Initalize moving to sector 1, Terra
  2736. if prompt.startswith("Do you want to engage the TransWarp drive? "):
  2737. self.queue_player.put("N")
  2738. elif prompt.startswith(
  2739. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2740. ):
  2741. self.queue_player.put("E")
  2742. elif prompt.startswith(
  2743. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  2744. ):
  2745. self.queue_player.put("N")
  2746. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2747. self.state = 4
  2748. self.game.to_player = True
  2749. self.send2game("{0}\r".format(self.FROM))
  2750. # Move to planet FROM
  2751. elif self.state == 4:
  2752. # Are we there yet? (NNY)
  2753. if prompt.startswith("Do you want to engage the TransWarp drive? "):
  2754. self.queue_player.put("N")
  2755. elif prompt.startswith(
  2756. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2757. ):
  2758. self.queue_player.put("E")
  2759. elif prompt.startswith(
  2760. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  2761. ):
  2762. self.queue_player.put("N")
  2763. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2764. self.state = 5
  2765. self.send2game("L")
  2766. elif self.state == 5:
  2767. if self.FROM == 1: # Is our FROM planet Terra?
  2768. if prompt.startswith("Land on which planet <Q to abort> ?"):
  2769. self.send2game("1\r\r\r{0}\r".format(self.TO))
  2770. self.state = 6
  2771. # Planetary Scanner Detected, Move to sector with planet
  2772. elif prompt.startswith(
  2773. "Do you wish to (L)eave or (T)ake Colonists? [T] (Q to leave)"
  2774. ):
  2775. self.send2game("\r\r{0}\r".format(self.TO))
  2776. self.state = 6
  2777. # No Planetary Scanner Detected, Move to sector with planet
  2778. elif prompt.startswith(
  2779. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2780. ):
  2781. self.send2game("E")
  2782. self.state = 4
  2783. # We are not at terra, go back
  2784. else:
  2785. if prompt.startswith("Land on which planet <Q to abort> ?"):
  2786. self.send2game(
  2787. "{0}\rs\rt1\rq{1}\r".format(self.from_number, self.TO)
  2788. )
  2789. self.state = 6
  2790. # Planetary Scanner Detected, Move to sector with planet
  2791. elif prompt.startswith("Planet command (?=help) [D] "):
  2792. self.send2game("s\rt1\rq{0}\r".format(self.TO))
  2793. self.state = 6
  2794. elif prompt.startswith(
  2795. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2796. ):
  2797. self.send2game("E")
  2798. self.state = 4
  2799. # We are not at terra, go back
  2800. elif self.state == 6:
  2801. if prompt.startswith("Do you want to engage the TransWarp drive? "):
  2802. self.queue_player.put("N")
  2803. elif prompt.startswith(
  2804. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  2805. ):
  2806. self.queue_player.put("E")
  2807. elif prompt.startswith(
  2808. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  2809. ):
  2810. self.queue_player.put("N")
  2811. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  2812. self.state = 6
  2813. self.send2game("L")
  2814. elif prompt.startswith("Land on which planet <Q to abort> ?"):
  2815. self.state = 7
  2816. self.send2game("{0}\r".format(self.to_number))
  2817. # Planetary Scanner Detected selecting planet number
  2818. elif prompt.startswith("Planet command (?=help) [D] "):
  2819. self.state = 7
  2820. self.send2game("D")
  2821. # No Planetary Scaner skip on
  2822. elif self.state == 7:
  2823. if prompt.startswith("Engage the Autopilot? (Y/N/Single step/Express) [Y]"):
  2824. self.state = 6
  2825. self.send2game("E")
  2826. # Missed moving jump back to state 6
  2827. if prompt.startswith("Land on which planet <Q to abort> ?"):
  2828. self.queue_player.put("{0}\r".format(self.to_number))
  2829. # Planetary Scanner Detected selecting planet number
  2830. if prompt.startswith("Planet command (?=help) [D] "):
  2831. # Unload people and process the loop
  2832. self.loops -= 1
  2833. if self.loops:
  2834. self.state = 3
  2835. self.send2game("S\r\r1\rQ")
  2836. # Jump to state 3 we are not done
  2837. else:
  2838. self.send2game("S\r\r1\rQ")
  2839. self.send2player(
  2840. "\r" + Boxes.alert("Completed ({0})".format(self.maxloops))
  2841. )
  2842. self.deactivate(True)
  2843. # Ok we are done
  2844. def game_line(self, line: str):
  2845. log.debug("L {0} | {1}".format(self.state, line))
  2846. # IF at any state we see turns left lets grab it
  2847. if "turns left" in line:
  2848. work = line[19:].replace(" turns left.", "").strip()
  2849. self.turns = work
  2850. log.debug("TURNS LEFT: {0}".format(self.turns))
  2851. if int(self.turns) < 200:
  2852. self.send2player(
  2853. "\r" + Boxes.alert("Low Turns! ({0})".format(self.turns))
  2854. )
  2855. self.deactivate(True)
  2856. # IF at any state we see how many holds avalible let's get that
  2857. if "Total Holds" in line:
  2858. work = line[16:].replace("-", "").replace("=", " ").split()
  2859. self.total_holds = int(work[0])
  2860. count = 0
  2861. seen_empty = False
  2862. for w in work:
  2863. if w != "Empty":
  2864. count += 1
  2865. elif w == "Empty":
  2866. count += 1
  2867. self.holds = int(work[count])
  2868. log.debug("EMPTY HOLDS = {0}".format(self.holds))
  2869. self.holds_percent = int((self.holds / self.total_holds) * 100.0)
  2870. log.debug("HOLDS PERCENT = {0}%".format(self.holds_percent))
  2871. seen_empty = True
  2872. if self.holds < self.total_holds:
  2873. self.send2player(
  2874. "\r"
  2875. + Boxes.alert(
  2876. "You need {0} holds empty! ({1} Empty)".format(
  2877. self.total_holds, self.holds
  2878. )
  2879. )
  2880. )
  2881. self.deactivate(True)
  2882. if (
  2883. seen_empty != True
  2884. ): # Just incase we didn't see Empty... meaning we have 0 avalible holds
  2885. self.send2player(
  2886. "\r"
  2887. + Boxes.alert(
  2888. "You need {0} holds empty! (0 Empty)".format(self.total_holds)
  2889. )
  2890. )
  2891. self.deactivate(True)
  2892. if "There aren't that many on the planet!" in line:
  2893. self.send2player("\r" + Boxes.alert("We're missing people!"))
  2894. self.deactivate(True)
  2895. if "There isn't room on the planet for that many!" in line:
  2896. self.send2player("\r" + Boxes.alert("We have to many people!"))
  2897. self.deactivate(True)
  2898. if "There aren't that many on Terra!" in line:
  2899. self.send2player("\r" + Boxes.alert("No people on Terra to get!"))
  2900. self.deactivate(True)
  2901. # Now back to our scheduled program
  2902. if self.state == 1:
  2903. if "Personal Planet Scan" in line or "Corporate Planet Scan" in line:
  2904. self.state = 2
  2905. elif self.state == 2:
  2906. # Ok, we're in the planet scan part of this
  2907. # 10202 #3 Home of Bugz Class M, Earth Type No Citadel]
  2908. if "#" in line:
  2909. # Ok, we have a planet detail line.
  2910. # There's an extra T when the planet is maxed out.
  2911. # [ 986 #114 Trantor Class M, Earth Type No Citadel]
  2912. # [ 23 #17 gift Class O, Oceanic Level 1]
  2913. if line[7] == "T":
  2914. line = line[:7] + " " + line[8:]
  2915. details, _, citadel = line.partition("Class")
  2916. # log.info(details) # Is that what we are after?
  2917. # log.info(citadel)
  2918. sector, planet_number, name = re.split(r"\s+", details.strip(), 2)
  2919. sector = int(sector)
  2920. number = int(planet_number.replace("#", ""))
  2921. if "Level" in citadel:
  2922. cit = int(citadel[-1]) # Grab last item
  2923. else: # Oops, there looks like there is no citadel here.
  2924. cit = 0
  2925. self.last_seen = number
  2926. self.planets[number] = {"sector": sector, "name": name, "citadel": cit}
  2927. log.info(
  2928. "Planet # {0} in {1} called {2} with a lvl {3} citadel".format(
  2929. number, sector, name, cit
  2930. )
  2931. )
  2932. if "---" in line:
  2933. number = self.last_seen
  2934. # Ok, take the last_seen number, and use it for this line
  2935. # [ Sector Planet Name Ore Org Equ Ore Org Equ Fighters Citadel]
  2936. # [ Shields Population -=Productions=- -=-=-=-=-On Hands-=-=-=-=- Credits]
  2937. # [ 10202 #3 Home of Bugz Class M, Earth Type No Citadel]
  2938. # [ --- (1M) 144 49 26 145 75 12 10 0]
  2939. details = re.split(r"\s+", line.strip())
  2940. log.debug(details) # What are we getting?
  2941. # OK: Likely, I'm not going to use these numbers AT ALL.
  2942. self.planets[number]["population"] = (
  2943. details[1].replace("(", "").replace(")", "")
  2944. )
  2945. # Ok, there's going to have to be some sort of modifier (K, M, etc.)
  2946. # to these numbers. Beware!
  2947. self.planets[number]["ore"] = details[5]
  2948. self.planets[number]["org"] = details[6]
  2949. self.planets[number]["equ"] = details[7]
  2950. # self.planets[number]['cit'] = details[9] # This is if we wanted cit money... but that's not it
  2951. class MaxFighterMake(object):
  2952. """ Max Fighter Make
  2953. State of the Union:
  2954. 1 = Grab planets in current sector
  2955. 2 = Ask what planet to utilize, land
  2956. 3 = Grab Snapshot of planet (We will need to check population lvls too)
  2957. 4 = try cat 1 to cat 2 (Or perhaps this defaults to false if cat 2 is N/A)
  2958. 5 = if bad then try cat 1 to cat 3 (Or perhaps this defaults to false if cat 3 is N/A)
  2959. 6 = if bad then try cat 2 to cat 3 (Or perhaps this defaults to false if cat 3 is N/A)
  2960. 7 = loop back to state 3 until all result in bad (Yay best acheived)
  2961. """
  2962. def __init__(self, game):
  2963. self.game = game
  2964. self.queue_game = game.queue_game
  2965. self.queue_player = game.queue_player
  2966. self.observer = game.observer
  2967. self.r = Style.RESET_ALL
  2968. self.c = merge(Style.BRIGHT + Fore.YELLOW)
  2969. self.nl = "\n\r"
  2970. # My "stuff" in my pants!
  2971. self.state = 1
  2972. self.corp = True
  2973. self.target_sector = 0 # Sector Number of target
  2974. self.target_number = 0 # Planet Number of target
  2975. self.last_seen = {"Ore": False, "Org": False, "Equ": False, "Fig": False}
  2976. self.max_product = 0
  2977. self.trying = "Ore2Org"
  2978. self.trying_NEXT = False
  2979. self.movement = 1000
  2980. self.planets_list = [] # Will be a list of dicts, containing planet information
  2981. self.cap = False # Capture line for planet
  2982. # Activate
  2983. self.prompt = game.buffer
  2984. self.save = self.observer.save()
  2985. self.observer.connect("player", self.player)
  2986. self.observer.connect("prompt", self.game_prompt)
  2987. self.observer.connect("game-line", self.game_line)
  2988. self.ore = {}
  2989. self.org = {}
  2990. self.equ = {}
  2991. self.fig = {}
  2992. self.defer = None
  2993. self.to_player = self.game.to_player
  2994. self.game.to_player = False
  2995. self.send2game("D")
  2996. def whenDone(self):
  2997. self.defer = defer.Deferred()
  2998. return self.defer
  2999. def deactivate(self, andExit=False):
  3000. self.state = 0
  3001. log.debug("ColoScript2.deactivate()")
  3002. self.game.to_player = True
  3003. assert not self.save is None
  3004. self.observer.load(self.save)
  3005. self.save = None
  3006. if self.defer:
  3007. if andExit:
  3008. self.defer.callback({"exit": True})
  3009. else:
  3010. self.defer.callback("done")
  3011. self.defer = None
  3012. def player(self, chunk: bytes):
  3013. self.deactivate(True)
  3014. def send2game(self, txt):
  3015. # Removed debug info since I use this to also display Boxes.alert
  3016. self.queue_player.put(txt)
  3017. def send2player(self, txt):
  3018. # Removed debug since it really doesn't help with anything
  3019. self.queue_game.put(txt)
  3020. def target_chosen(self, choice: str):
  3021. if choice.strip() == "":
  3022. self.deactivate(True)
  3023. else:
  3024. self.target_number = int(choice)
  3025. if self.target_number > self.total:
  3026. self.deactivate(True)
  3027. else:
  3028. self.state = 3
  3029. self.send2game("L")
  3030. def check_resource(self, resource):
  3031. # Given a valid string that can be converted to int
  3032. if resource == "N/A":
  3033. resource = -1
  3034. else:
  3035. resource = int(resource.replace(",", ""))
  3036. return resource
  3037. def game_prompt(self, prompt: str):
  3038. log.debug("P {0} | {1}".format(self.state, prompt))
  3039. if self.state == 2:
  3040. self.game.to_player = True
  3041. if len(self.planets_list) == 0:
  3042. self.send2player(self.nl + Boxes.alert("No planets in this sector!"))
  3043. self.deactivate(True)
  3044. tc = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  3045. c1 = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  3046. c2 = merge(Style.BRIGHT + Fore.CYAN + Back.BLUE)
  3047. box = Boxes(44, color=tc)
  3048. self.queue_game.put(box.top())
  3049. self.queue_game.put(
  3050. box.row(
  3051. tc
  3052. + "{0:3} {1:20} {2:18} ".format(" # ", "Planet Name", "Planet Type")
  3053. )
  3054. )
  3055. self.queue_game.put(box.middle())
  3056. def planet_output(num, planet_name, planet_type):
  3057. row = "{0}{1:3} {2}{3:29} {4:9} ".format(
  3058. c1, num, c2, planet_name, planet_type
  3059. )
  3060. self.send2player(box.row(row))
  3061. self.total = 0
  3062. for p in self.planets_list:
  3063. planet_output(self.total, p["name"], p["type"])
  3064. self.total += 1
  3065. ask = PlayerInput(self.game)
  3066. d = ask.prompt("Choose a planet", 3, name="planet", digits=True)
  3067. d = d.addCallback(self.target_chosen)
  3068. elif self.state == 4:
  3069. if prompt.startswith("Planet command (?=help) [D]"):
  3070. self.send2game("?")
  3071. self.state = 6
  3072. elif self.state == 6:
  3073. if prompt.startswith("Planet command (?=help) [D]"):
  3074. self.send2game("P")
  3075. self.state = 7
  3076. elif self.state == 7:
  3077. if prompt.startswith("Display planet?"):
  3078. self.send2game("N")
  3079. self.state = 8
  3080. elif self.state == 8:
  3081. if prompt.startswith("(1)Ore, (2)Org or (3)Equipment?"):
  3082. if self.trying == "Ore2Org" or self.trying == "Ore2Equ":
  3083. self.send2game("1")
  3084. elif self.trying == "Org2Equ" or self.trying == "Org2Ore":
  3085. self.send2game("2")
  3086. elif self.trying == "Equ2Org" or self.trying == "Equ2Ore":
  3087. self.send2game("3")
  3088. self.state = 9
  3089. elif self.state == 9:
  3090. if prompt.startswith("How many groups of Colonists do you want to move?"):
  3091. self.send2game("{0}\r".format(self.movement))
  3092. self.state = 10
  3093. elif self.state == 10:
  3094. if prompt.startswith("(1)Ore, (2)Org or (3)Equipment?"):
  3095. if self.trying == "Org2Ore" or self.trying == "Equ2Ore":
  3096. self.send2game("1")
  3097. elif self.trying == "Ore2Org" or self.trying == "Equ2Org":
  3098. self.send2game("2")
  3099. elif self.trying == "Ore2Equ" or self.trying == "Org2Equ":
  3100. self.send2game("3")
  3101. self.state = 11
  3102. elif self.state == 11:
  3103. if prompt.startswith("Planet command (?=help) [D]"):
  3104. self.send2game("D")
  3105. self.trying_NEXT = False
  3106. self.last_seen["Ore"] = False
  3107. self.last_seen["Org"] = False
  3108. self.last_seen["Equ"] = False
  3109. self.last_seen["Fig"] = False
  3110. self.state = 12
  3111. elif self.state == 12:
  3112. if prompt.startswith("Planet command (?=help) [D]"):
  3113. self.send2game("?")
  3114. self.state = 6
  3115. # if(self.trying == 'Ore2Org'):
  3116. # self.send2game('P\r1{0}2D'.format(self.movement))
  3117. # self.state = 4
  3118. # # Back to looking at the planet
  3119. # elif(self.trying == 'Ore2Equ'):
  3120. # self.send2game('P\r1{0}3D'.format(self.movement))
  3121. # self.state = 4
  3122. # # Back to looking at the planet
  3123. # elif(self.trying == 'Org2Equ'):
  3124. # self.send2game('P\r2{0}3D'.format(self.movement))
  3125. # self.state = 4
  3126. # elif(self.trying == 'reverse'):
  3127. # if(self.trying_OLD == 'Ore2Org'):
  3128. # self.send2game('P\r2{0}1D'.format(self.movement))
  3129. # elif(self.trying_OLD == 'Ore2Equ'):
  3130. # self.send2game('P\r3{0}1D'.format(self.movement))
  3131. # elif(self.trying_OLD == 'Org2Equ'):
  3132. # self.send2game('P\r3{0}2D'.format(self.movement))
  3133. # self.state = 4
  3134. # self.trying = self.trying_NEXT
  3135. def game_line(self, line: str):
  3136. log.debug("L {0} | {1}".format(self.state, line))
  3137. # IF at any state we see turns left lets grab it
  3138. if "turns left" in line:
  3139. work = line[19:].replace(" turns left.", "").strip()
  3140. self.turns = work
  3141. log.debug("TURNS LEFT: {0}".format(self.turns))
  3142. if int(self.turns) < 200:
  3143. self.send2player(
  3144. "\r" + Boxes.alert("Low Turns! ({0})".format(self.turns))
  3145. )
  3146. self.deactivate(True)
  3147. # IF at any state we see how many holds avalible let's get that
  3148. if "Total Holds" in line:
  3149. work = line[16:].replace("-", "").replace("=", " ").split()
  3150. self.total_holds = int(work[0])
  3151. count = 0
  3152. for w in work:
  3153. if w != "Empty":
  3154. count += 1
  3155. elif w == "Empty":
  3156. count += 1
  3157. self.holds = int(work[count])
  3158. log.debug("EMPTY HOLDS = {0}".format(self.holds))
  3159. if self.holds < self.total_holds:
  3160. self.send2player(
  3161. "\r"
  3162. + Boxes.alert(
  3163. "You need {0} holds empty! ({1} Empty)".format(
  3164. self.total_holds, self.holds
  3165. )
  3166. )
  3167. )
  3168. self.deactivate(True)
  3169. if "There aren't that many on the planet!" in line:
  3170. self.send2player("\r" + Boxes.alert("We're missing people!"))
  3171. self.deactivate(True)
  3172. if "There isn't room on the planet for that many!" in line:
  3173. self.send2player("\r" + Boxes.alert("We have to many people!"))
  3174. self.deactivate(True)
  3175. # Now back to our scheduled program
  3176. if self.state == 1:
  3177. if line.startswith("Planets"):
  3178. self.cap = True
  3179. work = re.split(r"\s+", line)
  3180. # log.debug("'{0}'".format(work))
  3181. final = {"name": work[-1], "type": work[-2]}
  3182. self.planets_list.append(final)
  3183. log.debug("Planet {0} type {1}".format(final["name"], final["type"]))
  3184. elif line.startswith("Ships"): # Stop 1, so we don't capture everything
  3185. self.cap = False
  3186. elif line.startswith("Fighters"): # Stop 2, so we don't capture everything
  3187. self.cap = False
  3188. elif self.cap == True:
  3189. work = re.split(r"\s+", line)
  3190. # log.debug("'{0}'".format(work))
  3191. final = {"name": work[-1], "type": work[-2]}
  3192. self.planets_list.append(final)
  3193. log.debug("Planet {0} type {1}".format(final["name"], final["type"]))
  3194. elif self.cap == False and len(self.planets_list) != 0:
  3195. self.state = 2
  3196. elif self.state == 3:
  3197. if self.planets_list[self.target_number]["name"] in line:
  3198. work = re.split(r"\s+", line)
  3199. log.debug("'{0}'".format(work))
  3200. pnumber = work[2].replace(">", "")
  3201. self.planets_list[self.target_number][
  3202. "pnumber"
  3203. ] = pnumber # Add this to our dict of the planet
  3204. log.debug(
  3205. "Pnumber {0} is {1}".format(
  3206. pnumber, self.planets_list[self.target_number]["name"]
  3207. )
  3208. )
  3209. self.send2game("{0}\r".format(pnumber))
  3210. self.state = 4
  3211. elif self.state == 4:
  3212. # Item Colonists Colonists Daily Planet Ship Planet
  3213. # (1000s) 2 Build 1 Product Amount Amount Maximum
  3214. # ------- --------- --------- --------- --------- --------- ---------
  3215. # Fuel Ore 707 2 353 10,376 0 200,000
  3216. # Organics 651 5 130 4,304 0 200,000
  3217. # Equipment 1,641 20 82 2,618 0 100,000
  3218. # Fighters N/A 63 47 1,463 400 1,000,000
  3219. if line.startswith("Fuel Ore"):
  3220. work = re.split(r"\s+", line)
  3221. # 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]))
  3222. self.ore = {
  3223. "pop": self.check_resource(work[2]),
  3224. "make": self.check_resource(work[3]),
  3225. "daily": self.check_resource(work[4]),
  3226. "amount": self.check_resource(work[5]),
  3227. "ship": self.check_resource(work[6]),
  3228. "pmax": self.check_resource(work[7]),
  3229. }
  3230. self.last_seen["Ore"] = True
  3231. elif line.startswith("Organics"):
  3232. work = re.split(r"\s+", line)
  3233. # 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]))
  3234. self.org = {
  3235. "pop": self.check_resource(work[1]),
  3236. "make": self.check_resource(work[2]),
  3237. "daily": self.check_resource(work[3]),
  3238. "amount": self.check_resource(work[4]),
  3239. "ship": self.check_resource(work[5]),
  3240. "pmax": self.check_resource(work[6]),
  3241. }
  3242. self.last_seen["Org"] = True
  3243. elif line.startswith("Equipment"):
  3244. work = re.split(r"\s+", line)
  3245. # 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]))
  3246. self.equ = {
  3247. "pop": self.check_resource(work[1]),
  3248. "make": self.check_resource(work[2]),
  3249. "daily": self.check_resource(work[3]),
  3250. "amount": self.check_resource(work[4]),
  3251. "ship": self.check_resource(work[5]),
  3252. "pmax": self.check_resource(work[6]),
  3253. }
  3254. self.last_seen["Equ"] = True
  3255. elif line.startswith("Fighters"):
  3256. work = re.split(r"\s+", line)
  3257. # 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]))
  3258. self.fig = {
  3259. "pop": self.check_resource(work[1]),
  3260. "make": self.check_resource(work[2]),
  3261. "daily": self.check_resource(work[3]),
  3262. "amount": self.check_resource(work[4]),
  3263. "ship": self.check_resource(work[5]),
  3264. "pmax": self.check_resource(work[6]),
  3265. }
  3266. self.last_seen["Fig"] = True
  3267. else:
  3268. if (
  3269. self.last_seen["Ore"] == True
  3270. and self.last_seen["Org"] == True
  3271. and self.last_seen["Equ"] == True
  3272. and self.last_seen["Fig"] == True
  3273. ):
  3274. if self.fig["daily"] > self.max_product:
  3275. self.max_product = self.fig["daily"]
  3276. self.planets_list[self.target_number]["Ore"] = self.ore
  3277. self.planets_list[self.target_number]["Org"] = self.org
  3278. self.planets_list[self.target_number]["Equ"] = self.equ
  3279. self.planets_list[self.target_number]["Fig"] = self.fig
  3280. log.debug("Max Production is {0}!".format(self.max_product))
  3281. self.state == 6
  3282. elif self.state == 12:
  3283. if line.startswith("Fuel Ore"):
  3284. work = re.split(r"\s+", line)
  3285. # 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]))
  3286. self.ore = {
  3287. "pop": self.check_resource(work[2]),
  3288. "make": self.check_resource(work[3]),
  3289. "daily": self.check_resource(work[4]),
  3290. "amount": self.check_resource(work[5]),
  3291. "ship": self.check_resource(work[6]),
  3292. "pmax": self.check_resource(work[7]),
  3293. }
  3294. self.last_seen["Ore"] = True
  3295. elif line.startswith("Organics"):
  3296. work = re.split(r"\s+", line)
  3297. # 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]))
  3298. self.org = {
  3299. "pop": self.check_resource(work[1]),
  3300. "make": self.check_resource(work[2]),
  3301. "daily": self.check_resource(work[3]),
  3302. "amount": self.check_resource(work[4]),
  3303. "ship": self.check_resource(work[5]),
  3304. "pmax": self.check_resource(work[6]),
  3305. }
  3306. self.last_seen["Org"] = True
  3307. elif line.startswith("Equipment"):
  3308. work = re.split(r"\s+", line)
  3309. # 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]))
  3310. self.equ = {
  3311. "pop": self.check_resource(work[1]),
  3312. "make": self.check_resource(work[2]),
  3313. "daily": self.check_resource(work[3]),
  3314. "amount": self.check_resource(work[4]),
  3315. "ship": self.check_resource(work[5]),
  3316. "pmax": self.check_resource(work[6]),
  3317. }
  3318. self.last_seen["Equ"] = True
  3319. elif line.startswith("Fighters"):
  3320. work = re.split(r"\s+", line)
  3321. # 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]))
  3322. self.fig = {
  3323. "pop": self.check_resource(work[1]),
  3324. "make": self.check_resource(work[2]),
  3325. "daily": self.check_resource(work[3]),
  3326. "amount": self.check_resource(work[4]),
  3327. "ship": self.check_resource(work[5]),
  3328. "pmax": self.check_resource(work[6]),
  3329. }
  3330. self.last_seen["Fig"] = True
  3331. else:
  3332. if (
  3333. self.last_seen["Ore"] == True
  3334. and self.last_seen["Org"] == True
  3335. and self.last_seen["Equ"] == True
  3336. and self.last_seen["Fig"] == True
  3337. ):
  3338. if self.fig["daily"] > self.max_product:
  3339. self.max_product = self.fig["daily"]
  3340. self.planets_list[self.target_number]["Ore"] = self.ore
  3341. self.planets_list[self.target_number]["Org"] = self.org
  3342. self.planets_list[self.target_number]["Equ"] = self.equ
  3343. self.planets_list[self.target_number]["Fig"] = self.fig
  3344. log.debug("Max Production is now {0}!".format(self.max_product))
  3345. if self.fig["daily"] < self.max_product:
  3346. # Oh nose, our change actually made things worse... let's fix that and try a different way
  3347. if self.trying == "Ore2Org":
  3348. self.trying = "Org2Ore"
  3349. elif self.trying == "Ore2Equ":
  3350. self.trying = "Equ2Ore"
  3351. elif self.trying == "Org2Equ":
  3352. self.trying = "Equ2Org"
  3353. self.state = 6
  3354. if (
  3355. self.ore["pop"] < 1
  3356. or self.org["pop"] < 1
  3357. or self.equ["pop"] < 1
  3358. ):
  3359. self.send2game("Q")
  3360. self.send2player(
  3361. self.nl
  3362. + Boxes.alert(
  3363. "Peak Fighter Production: {0}".format(self.fig["daily"])
  3364. )
  3365. )
  3366. self.deactivate(True)
  3367. class evilTrade(object):
  3368. """
  3369. A little bit on playing evil,
  3370. Doing SSM, a bust will cause some holds and any cargo to be removed!
  3371. You must move to different ports to reduce the chance of a bust,
  3372. Bust's are reset after so many days... so might want to handle that.
  3373. SSM rewards you -10 Alignment and +5 Experiece if you are sucessful
  3374. in robbing back your cargo you just sold.
  3375. States:
  3376. 0 = Pre-State, Asks the user how many times to run
  3377. 1 = Gather user info
  3378. 2 = Verify Cargo is full of Equ, else jump to state 3.5
  3379. 3 = Find nearest "Evil Pair" of ports, move to first, jump to 4
  3380. 3.5 = User does not have Equ, lets buy it, then move on
  3381. (SSM: Sell-Steal-Move)
  3382. 4 = Port and Sell Equ
  3383. 5 = Port and Steal Equ
  3384. 6 = Move to 2nd "Evil Pair"
  3385. 7 = Port and Sell Equ
  3386. 8 = Port and Steal Equ
  3387. 9 = Move to 1st "Evil Pair"
  3388. 10 = Decide to loop, if so we jump back to state 4, else exit
  3389. """
  3390. def __init__(self, game):
  3391. self.game = game
  3392. self.queue_game = game.queue_game
  3393. self.queue_player = game.queue_player
  3394. self.observer = game.observer
  3395. self.r = Style.RESET_ALL
  3396. self.c = merge(Style.BRIGHT + Fore.YELLOW)
  3397. self.nl = "\n\r"
  3398. self.state = 0 # Pre-state
  3399. self.holds = 0 # Total holds empty, self.holds == self.cargo["Empty"]
  3400. self.cargo = {
  3401. "Ore": 0,
  3402. "Org": 0,
  3403. "Equ": 0,
  3404. "Colo": 0,
  3405. "Empty": 0,
  3406. } # What is in our holds?
  3407. self.maxHolds = 0 # Total holds
  3408. self.maxLoops = 0 # So when we display done show the total loops asked to do
  3409. self.loops = 0 # Current number of loops left to do
  3410. self.completeINFO = False # Collected all INFO needed
  3411. self.exp = 0 # Experience Points the player has
  3412. self.alignment = 0 # Alignment the player has
  3413. self.credits = 0 # Credits player has
  3414. self.turns = 0 # Turns the player has
  3415. self.sector = 0 # Current sector
  3416. self.sectors = False # Do we need to update sector1 and 2?
  3417. self.sector1 = None
  3418. self.sector2 = None
  3419. self.target_sector = 0 # Next port to trade with
  3420. self.name = "" # Player name to include into stats for logs
  3421. self.prompt = game.buffer
  3422. self.save = self.observer.save()
  3423. self.observer.connect("player", self.player)
  3424. self.observer.connect("prompt", self.game_prompt)
  3425. self.observer.connect("game-line", self.game_line)
  3426. self.defer = None
  3427. self.to_player = self.game.to_player
  3428. self.game.to_player = False
  3429. self.send2game("D")
  3430. def whenDone(self):
  3431. self.defer = defer.Deferred()
  3432. return self.defer
  3433. def deactivate(self, andExit=False):
  3434. self.state = 0
  3435. log.debug("EvilTrade.deactivate()")
  3436. self.game.to_player = True
  3437. assert not self.save is None
  3438. self.observer.load(self.save)
  3439. self.save = None
  3440. if self.defer:
  3441. if andExit:
  3442. self.defer.callback({"exit": True})
  3443. else:
  3444. self.defer.callback("done")
  3445. self.defer = None
  3446. def player(self, chunk: bytes):
  3447. self.deactivate(True)
  3448. def send2game(self, txt):
  3449. self.queue_player.put(txt)
  3450. def send2player(self, txt):
  3451. self.queue_game.put(txt)
  3452. def loops_chosen(self, choice: str):
  3453. if choice.strip() == "":
  3454. self.deactivate(True)
  3455. else:
  3456. self.loops = int(choice)
  3457. self.maxLoops = self.loops
  3458. self.state = 1
  3459. self.send2game("I")
  3460. def game_prompt(self, prompt: str):
  3461. log.debug("P {0} | {1}".format(self.state, prompt))
  3462. if self.state == 0:
  3463. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3464. ask = PlayerInput(self.game)
  3465. d = ask.prompt("How many times: ", 3, name="times", digits=True)
  3466. d.addCallback(self.loops_chosen)
  3467. elif self.state == 1:
  3468. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3469. if self.completeINFO: # We have all our info, lets display it into logs
  3470. log.debug("{0}'s Stats...".format(self.name))
  3471. log.debug(
  3472. "Experience: {0} Alignment: {1} Turns: {2} Credits: {3} Total Holds: {4} Avaible Holds: {5} Current Sector: {6}".format(
  3473. self.exp,
  3474. self.alignment,
  3475. self.turns,
  3476. self.credits,
  3477. self.maxHolds,
  3478. self.holds,
  3479. self.sector,
  3480. )
  3481. )
  3482. log.debug(
  3483. "Ore: {0} Org: {1} Equ: {2} Colo: {3} Empty: {4}".format(
  3484. self.cargo["Ore"],
  3485. self.cargo["Org"],
  3486. self.cargo["Equ"],
  3487. self.cargo["Colo"],
  3488. self.cargo["Empty"],
  3489. )
  3490. )
  3491. self.state = 2
  3492. self.send2game("D")
  3493. self.game.to_player = True
  3494. elif self.state == 2:
  3495. if self.cargo["Ore"] != 0: # Nada, we want Equ
  3496. self.send2player(
  3497. self.nl + Boxes.alert("Holds must contain Equ not Ore!")
  3498. )
  3499. self.deactivate(True)
  3500. elif self.cargo["Org"] != 0: # Oops, wrong, Give use Equ
  3501. self.send2player(
  3502. self.nl + Boxes.alert("Holds must contain Equ not Org!")
  3503. )
  3504. self.deactivate(True)
  3505. elif (
  3506. self.cargo["Colo"] != 0
  3507. ): # We don't want people, let the user handle this
  3508. self.send2player(
  3509. self.nl + Boxes.alert("Holds must contain Equ not Colonist!")
  3510. )
  3511. self.deactivate(True)
  3512. elif self.cargo["Equ"] != 0: # We do have Equ, but do we need more?
  3513. if self.cargo["Equ"] != self.maxHolds:
  3514. self.send2player(
  3515. self.nl
  3516. + Boxes.alert(
  3517. "You need {0} more Equ!".format(self.cargo["Empty"])
  3518. )
  3519. )
  3520. # Ok nope, we need more, let's find the nearest and "Mush!"
  3521. place = self.game.gamedata.find_nearest_selling(
  3522. self.sector, "E", 400
  3523. )
  3524. if place == 0:
  3525. self.queue_game.put(
  3526. self.nl + Boxes.alert("Find Nearest Failed!")
  3527. )
  3528. self.deactivate(True)
  3529. else:
  3530. self.send2game("{0}\rEPT".format(place))
  3531. # Code here to handle getting Equ
  3532. self.state = 3.5
  3533. else: # All OK, now to find_nearest_evilpairs
  3534. self.state = 3
  3535. self.game.to_player = False
  3536. self.send2game("D")
  3537. self.game.to_player = True
  3538. else: # Ok so we have Empty holds, lets fill it with Equ
  3539. place = self.game.gamedata.find_nearest_selling(self.sector, "E", 400)
  3540. if place == 0:
  3541. self.queue_game.put(self.nl + Boxes.alert("Find Nearest Failed!"))
  3542. self.deactivate(True)
  3543. else:
  3544. self.send2game("{0}\rEPT".format(place))
  3545. # Code here to handle getting Equ
  3546. self.state = 3.5
  3547. elif self.state == 3.5:
  3548. # Ok, we are getting Equ into holds then onto 3
  3549. if prompt.startswith("How many holds of Fuel Ore do you want to buy "):
  3550. self.send2game("0\r")
  3551. elif prompt.startswith("How many holds of Organics do you want to buy "):
  3552. self.send2game("0\r")
  3553. elif prompt.startswith("How many holds of Equipment do you want to buy "):
  3554. self.send2game("\r\r")
  3555. # Oops, we are expecting the user to have enough money to buy it!
  3556. self.state = 3
  3557. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3558. self.send2game("D")
  3559. self.state = 3
  3560. elif self.state == 3:
  3561. if prompt.startswith("Your offer"):
  3562. self.send2game("0\r")
  3563. self.deactivate(True)
  3564. else:
  3565. # Now to go to evil trade pair \o/
  3566. # Ok so if we go to line 2117 we can see how to use find_nearest_tradepairs()
  3567. # Which will give us a starting point for what needs to be done for us trading
  3568. log.info("find_nearest_evilpairs({0})".format(self.sector))
  3569. c = coiterate(
  3570. self.game.gamedata.find_nearest_evilpairs(self.sector, self)
  3571. )
  3572. c.addCallback(lambda unknown: self.evil())
  3573. self.state = 4
  3574. elif self.state == 4:
  3575. if prompt.startswith("Do you want to engage the TransWarp drive? "):
  3576. self.queue_player.put("N")
  3577. elif prompt.startswith(
  3578. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  3579. ):
  3580. self.queue_player.put("E")
  3581. elif prompt.startswith(
  3582. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  3583. ):
  3584. self.queue_player.put("N")
  3585. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3586. # We should be where we wanted to.
  3587. self.send2game("PT\r\r")
  3588. self.state = 5
  3589. elif self.state == 5:
  3590. if prompt.startswith("How many holds of Fuel Ore do you want to buy"):
  3591. self.send2game("0\r")
  3592. elif prompt.startswith("How many holds of Organics do you want to buy"):
  3593. self.send2game("0\r")
  3594. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3595. self.send2game("PR\rS3\r")
  3596. self.state = 6
  3597. elif self.state == 7:
  3598. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3599. c = coiterate(self.find_next_evilpair())
  3600. c.addCallback(lambda unknown: self.evil())
  3601. self.state = 8
  3602. elif self.state == 8:
  3603. if prompt.startswith("Do you want to engage the TransWarp drive? "):
  3604. self.queue_player.put("N")
  3605. elif prompt.startswith(
  3606. "Engage the Autopilot? (Y/N/Single step/Express) [Y]"
  3607. ):
  3608. self.queue_player.put("E")
  3609. elif prompt.startswith(
  3610. "Stop in this sector (Y,N,E,I,R,S,D,P,?) (?=Help) [N] ?"
  3611. ):
  3612. self.queue_player.put("N")
  3613. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3614. # We should be where we wanted to.
  3615. self.send2game("PT\r\r")
  3616. self.state = 9
  3617. elif self.state == 9:
  3618. if prompt.startswith("How many holds of Fuel Ore do you want to buy"):
  3619. self.send2game("0\r")
  3620. elif prompt.startswith("How many holds of Organics do you want to buy"):
  3621. self.send2game("0\r")
  3622. elif re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3623. self.send2game("PR\rS3\r")
  3624. self.state = 10
  3625. def evil(self):
  3626. if self.target_sector is None:
  3627. self.send2player(
  3628. self.nl + Boxes.alert("I don't see any ports to trade with.")
  3629. )
  3630. self.deactivate(True)
  3631. else:
  3632. self.send2game("{0}\r".format(self.target_sector))
  3633. if self.sectors == False:
  3634. self.sector1 = self.sector
  3635. self.sector2 = self.target_sector
  3636. self.sectors = True
  3637. self.sector = self.target_sector
  3638. def find_next_evilpair(self):
  3639. """ Find the next GOOD trade pair sector.
  3640. This is sequential (just like Trade report)
  3641. """
  3642. # This should be using the setting in the config, not a hard coded value!
  3643. # show_limit (galaxy.port_trade_show) is pct >= show_limit.
  3644. show_limit = self.game.gamedata.get_config("Display_Percent", "90")
  3645. try:
  3646. show_limit = int(show_limit)
  3647. except ValueError:
  3648. show_limit = 90
  3649. if show_limit < 15:
  3650. show_limit = 15
  3651. if show_limit > 90:
  3652. show_limit = 90
  3653. # Look for "GOOD" trades
  3654. for sector in sorted(self.game.gamedata.ports.keys()):
  3655. pd = self.game.gamedata.ports[sector]
  3656. if not GameData.port_burnt(pd):
  3657. # This happens when you trade with a StarDock
  3658. if "class" not in pd:
  3659. continue
  3660. pc = pd["class"]
  3661. # Ok, let's look into it.
  3662. if not sector in self.game.gamedata.warps:
  3663. continue
  3664. # Busted port
  3665. if not sector in self.game.gamedata.busts:
  3666. continue
  3667. warps = self.game.gamedata.warps[sector]
  3668. for w in warps:
  3669. # We can get there, and get back.
  3670. if (
  3671. w in self.game.gamedata.warps
  3672. and sector in self.game.gamedata.warps[w]
  3673. ):
  3674. # Ok, we can get there -- and get back!
  3675. if (
  3676. w > sector
  3677. and w in self.game.gamedata.ports
  3678. and not GameData.port_burnt(self.game.gamedata.ports[w])
  3679. ):
  3680. wd = self.game.gamedata.ports[w]
  3681. if "class" not in wd:
  3682. continue
  3683. wc = wd["class"]
  3684. if pc in (2, 3, 4, 8) and wc in (2, 3, 4, 8):
  3685. data = self.game.gamedata.port_trade_show(
  3686. sector, w, show_limit
  3687. )
  3688. if data:
  3689. self.target_sector = sector
  3690. return sector
  3691. yield
  3692. # Look for OK trades
  3693. for sector in sorted(self.game.gamedata.ports.keys()):
  3694. pd = self.game.gamedata.ports[sector]
  3695. if not GameData.port_burnt(pd):
  3696. if "class" not in pd:
  3697. continue
  3698. pc = pd["class"]
  3699. # Ok, let's look into it.
  3700. if not sector in self.game.gamedata.warps:
  3701. continue
  3702. # Busted port
  3703. if not sector in self.game.gamedata.busts:
  3704. continue
  3705. warps = self.game.gamedata.warps[sector]
  3706. for w in warps:
  3707. # We can get there, and get back.
  3708. if (
  3709. w in self.game.gamedata.warps
  3710. and sector in self.game.gamedata.warps[w]
  3711. ):
  3712. # Ok, we can get there -- and get back!
  3713. if (
  3714. w > sector
  3715. and w in self.game.gamedata.ports
  3716. and not GameData.port_burnt(self.game.gamedata.ports[w])
  3717. ):
  3718. wd = self.game.gamedata.ports[w]
  3719. if "class" not in wd:
  3720. continue
  3721. wc = wd["class"]
  3722. if GameData.port_trading(
  3723. pd["port"], self.game.gamedata.ports[w]["port"]
  3724. ):
  3725. data = self.game.gamedata.port_trade_show(
  3726. sector, w, show_limit
  3727. )
  3728. if data:
  3729. self.target_sector = sector
  3730. return sector
  3731. yield
  3732. self.target_sector = None
  3733. def game_line(self, line: str):
  3734. log.debug("L {0} | {1}".format(self.state, line))
  3735. if self.state == 1:
  3736. if line.startswith("Trader Name"):
  3737. work = line.replace("Trader Name :", "").split()
  3738. self.name = work[-1]
  3739. elif line.startswith("Current Sector"):
  3740. work = line.replace("Current Sector : ", "")
  3741. self.sector = int(work)
  3742. elif line.startswith("Rank and Exp"):
  3743. work = line.replace("Rank and Exp :", "").split()
  3744. # Rank and Exp : 110 points, Alignment=-116 Crass
  3745. self.exp = work[0]
  3746. self.alignment = work[2].replace("Alignment=", "")
  3747. elif line.startswith("Turns left"):
  3748. work = line.replace("Turns left : ", "")
  3749. self.turns = int(work)
  3750. elif line.startswith("Total Holds"):
  3751. work = (
  3752. line[16:]
  3753. .replace("-", "")
  3754. .replace("=", " ")
  3755. .replace("Fuel Ore", "Fuel")
  3756. .split()
  3757. )
  3758. self.maxHolds = int(work[0])
  3759. # Total Holds : 53 - Empty=53
  3760. # Total Holds : 53 - Fuel Ore=1 Organics=2 Equipment=3 Colonists=4 Empty=43
  3761. # log.debug(work)
  3762. # '53', 'Fuel', '1', 'Organics', '2', 'Equipment', '3', 'Colonists', '4', 'Empty', '43'
  3763. count = 0
  3764. for w in work:
  3765. if w == "Fuel":
  3766. try:
  3767. self.cargo["Ore"] = int(work[count + 1])
  3768. except ValueError: # The next value is not a number!
  3769. self.cargo["Ore"] = 0
  3770. elif w == "Organics":
  3771. try:
  3772. self.cargo["Org"] = int(work[count + 1])
  3773. except ValueError: # The next value is not a number!
  3774. self.cargo["Org"] = 0
  3775. elif w == "Equipment":
  3776. try:
  3777. self.cargo["Equ"] = int(work[count + 1])
  3778. except ValueError: # The next value is not a number!
  3779. self.cargo["Equ"] = 0
  3780. elif w == "Colonists":
  3781. try:
  3782. self.cargo["Colo"] = int(work[count + 1])
  3783. except ValueError: # The next value is not a number!
  3784. self.cargo["Colo"] = 0
  3785. elif w == "Empty":
  3786. try:
  3787. self.cargo["Empty"] = int(work[count + 1])
  3788. self.holds = self.cargo["Empty"]
  3789. except ValueError: # The next value is not a number!
  3790. self.cargo["Empty"] = 0
  3791. count += 1
  3792. elif line.startswith("Credits"):
  3793. work = line.replace("Credits : ", "").replace(",", "")
  3794. self.credits = int(work)
  3795. self.completeINFO = True
  3796. if self.state == 6:
  3797. if "Suddenly you're Busted!" in line:
  3798. # Oops! We got busted, let's stop.
  3799. self.deactivate(True)
  3800. elif "Success!" in line:
  3801. # Ok we passed that... now to move on.
  3802. self.state = 7
  3803. if self.state == 10:
  3804. if "Suddenly you're Busted!" in line:
  3805. # Oops! We got busted, let's stop.
  3806. self.deactivate(True)
  3807. elif "Success!" in line:
  3808. # Ok we passed that... now to move on.
  3809. self.loops -= 1
  3810. if self.loops >= 0:
  3811. self.send2player(
  3812. self.nl + Boxes.alert("Completed {0}".format(self.maxLoops))
  3813. )
  3814. self.deactivate(True)
  3815. else:
  3816. c = coiterate(self.find_next_evilpair())
  3817. c.addCallback(lambda unknown: self.evil())
  3818. self.state = 4
  3819. class ProxyMenu(object):
  3820. """ Display ProxyMenu
  3821. Example:
  3822. from flexible import ProxyMenu
  3823. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", prompt):
  3824. menu = ProxyMenu(self.game)
  3825. """
  3826. def __init__(self, game):
  3827. self.nl = "\n\r"
  3828. self.c = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  3829. self.r = Style.RESET_ALL
  3830. self.c1 = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  3831. self.c2 = merge(Style.NORMAL + Fore.CYAN + Back.BLUE)
  3832. # self.portdata = None
  3833. self.game = game
  3834. self.queue_game = game.queue_game
  3835. self.observer = game.observer
  3836. self.game.gamedata.get_config("Macro", "D^1N^D")
  3837. # Am I using self or game? (I think I want game, not self.)
  3838. # if hasattr(self.game, "portdata"):
  3839. # self.portdata = self.game.portdata
  3840. # else:
  3841. # self.portdata = {}
  3842. # if hasattr(self.game, 'warpdata'):
  3843. # self.warpdata = self.game.warpdata
  3844. # else:
  3845. # self.warpdata = {}
  3846. if hasattr(self.game, "trade_report"):
  3847. self.trade_report = self.game.trade_report
  3848. else:
  3849. self.trade_report = []
  3850. # Yes, at this point we would activate
  3851. self.prompt = game.buffer
  3852. self.save = self.observer.save()
  3853. self.observer.connect("player", self.player)
  3854. # If we want it, it's here.
  3855. self.defer = None
  3856. self.game.to_player = True
  3857. self.keepalive = task.LoopingCall(self.awake)
  3858. self.keepalive.start(30)
  3859. self.menu()
  3860. def __del__(self):
  3861. log.debug("ProxyMenu {0} RIP".format(self))
  3862. # When we exit, always make sure player echo is on.
  3863. self.game.to_player = True
  3864. def whenDone(self):
  3865. self.defer = defer.Deferred()
  3866. # Call this to chain something after we exit.
  3867. return self.defer
  3868. def menu(self):
  3869. box = Boxes(30, color=self.c)
  3870. self.queue_game.put(box.top())
  3871. text = self.c + "{0:^30}".format("TradeWars Proxy Active")
  3872. text = text.replace("Active", BLINK + "Active" + Style.RESET_ALL + self.c)
  3873. self.queue_game.put(box.row(text))
  3874. self.queue_game.put(box.bottom())
  3875. self.queue_game.put(" " + self.c + "-=>" + self.r + " ")
  3876. def fullmenu(self):
  3877. box = Boxes(30, color=self.c)
  3878. self.queue_game.put(box.top())
  3879. def menu_item(ch: str, desc: str):
  3880. row = self.c1 + " {0} {1}- {2}{3:25}".format(ch, self.c2, self.c1, desc)
  3881. self.queue_game.put(box.row(row))
  3882. # self.queue_game.put(
  3883. # " " + self.c1 + ch + self.c2 + " - " + self.c1 + desc + self.nl
  3884. # )
  3885. menu_item("C", "Configuration ({0})".format(len(self.game.gamedata.config)))
  3886. menu_item("D", "Display Report again")
  3887. menu_item("E", "Export Data (Save)")
  3888. # menu_item("Q", "Quest")
  3889. menu_item("M", "Macro")
  3890. menu_item("P", "Port CIM Report ({0})".format(len(self.game.gamedata.ports)))
  3891. menu_item("W", "Warp CIM Report ({0})".format(len(self.game.gamedata.warps)))
  3892. menu_item("R", "Restock Report")
  3893. menu_item("T", "Trading Report")
  3894. menu_item("S", "Scripts")
  3895. menu_item("X", "eXit")
  3896. bottom = box.bottom()
  3897. self.queue_game.put(bottom[:-2])
  3898. def awake(self):
  3899. log.info("ProxyMenu.awake()")
  3900. self.game.queue_player.put(" ")
  3901. def port_report(self, portdata: dict):
  3902. # Check to see if the old data is close to the new data.
  3903. # If so, don't toss out the special!
  3904. matches = 0
  3905. for k, v in self.old_ports.items():
  3906. if k in self.game.gamedata.ports:
  3907. # Ok, key exists. Is the class the same
  3908. if self.game.gamedata.ports[k]["class"] == v["class"]:
  3909. matches += 1
  3910. log.info("Got {0} matches old ports to new.".format(matches))
  3911. if matches > 12:
  3912. self.queue_game.put(
  3913. "Restoring (SPECIAL) class ports ({0}).".format(len(self.specials))
  3914. + self.nl
  3915. )
  3916. for p in self.specials.keys():
  3917. self.game.gamedata.ports[int(p)] = self.specials[p]
  3918. # self.portdata = portdata
  3919. # self.game.portdata = portdata
  3920. self.queue_game.put("Loaded {0} ports.".format(len(self.game.ports)) + self.nl)
  3921. self.welcome_back()
  3922. def warp_report(self, warpdata: dict):
  3923. # self.warpdata = warpdata
  3924. # self.game.warpdata = warpdata
  3925. self.queue_game.put("Loaded {0} sectors.".format(len(warpdata)) + self.nl)
  3926. self.welcome_back()
  3927. def make_trade_report(self):
  3928. log.debug("make_trade_report()")
  3929. ok_trades = []
  3930. best_trades = []
  3931. show_best = self.game.gamedata.get_config("Display_Best", "Y").upper()[0] == "Y"
  3932. show_ok = self.game.gamedata.get_config("Display_Ok", "N").upper()[0] == "Y"
  3933. show_limit = self.game.gamedata.get_config("Display_Percent", "90")
  3934. update_config = False
  3935. try:
  3936. show_limit = int(show_limit)
  3937. except ValueError:
  3938. show_limit = 90
  3939. update_config = True
  3940. if show_limit < 0:
  3941. show_limit = 0
  3942. update_config = True
  3943. elif show_limit > 100:
  3944. show_limit = 100
  3945. update_config = True
  3946. if update_config:
  3947. self.game.gamedata.set_config("Display_Percent", show_limit)
  3948. # for sector, pd in self.game.gamedata.ports.items():
  3949. for sector in sorted(self.game.gamedata.ports.keys()):
  3950. pd = self.game.gamedata.ports[sector]
  3951. if not GameData.port_burnt(pd):
  3952. # This happens if you trade with a StarDock. (It doesn't get the class set.)
  3953. if "class" not in pd:
  3954. continue
  3955. pc = pd["class"]
  3956. # Ok, let's look into it.
  3957. if not sector in self.game.gamedata.warps:
  3958. continue
  3959. warps = self.game.gamedata.warps[sector]
  3960. for w in warps:
  3961. # Verify that we have that warp's info, and that the sector is in it.
  3962. # (We can get back from it)
  3963. if (
  3964. w in self.game.gamedata.warps
  3965. and sector in self.game.gamedata.warps[w]
  3966. ):
  3967. # Ok, we can get there -- and get back!
  3968. if (
  3969. w > sector
  3970. and w in self.game.gamedata.ports
  3971. and not GameData.port_burnt(self.game.gamedata.ports[w])
  3972. ):
  3973. # it is > and has a port.
  3974. wd = self.game.gamedata.ports[w]
  3975. if "class" not in wd:
  3976. continue
  3977. wc = wd["class"]
  3978. # 1: "BBS",
  3979. # 2: "BSB",
  3980. # 3: "SBB",
  3981. # 4: "SSB",
  3982. # 5: "SBS",
  3983. # 6: "BSS",
  3984. # 7: "SSS",
  3985. # 8: "BBB",
  3986. if pc in (1, 5) and wc in (2, 4):
  3987. data = self.game.gamedata.port_trade_show(
  3988. sector, w, show_limit
  3989. )
  3990. if data:
  3991. best_trades.append(data)
  3992. # best_trades.append( "{0:5} -=- {1:5}".format(sector, w))
  3993. elif pc in (2, 4) and wc in (1, 5):
  3994. data = self.game.gamedata.port_trade_show(
  3995. sector, w, show_limit
  3996. )
  3997. if data:
  3998. best_trades.append(data)
  3999. # best_trades.append( "{0:5} -=- {1:5}".format(sector, w))
  4000. elif GameData.port_trading(
  4001. pd["port"], self.game.gamedata.ports[w]["port"]
  4002. ):
  4003. # ok_trades.append( "{0:5} -=- {1:5}".format(sector,w))
  4004. data = self.game.gamedata.port_trade_show(
  4005. sector, w, show_limit
  4006. )
  4007. if data:
  4008. ok_trades.append(data)
  4009. yield
  4010. if show_best:
  4011. self.trade_report.append("Best Trades: (org/equ)")
  4012. self.trade_report.extend(best_trades)
  4013. if show_ok:
  4014. self.trade_report.append("Ok Trades:")
  4015. self.trade_report.extend(ok_trades)
  4016. if not show_best and not show_ok:
  4017. self.queue_game.put(
  4018. Boxes.alert(
  4019. "You probably want to choose something to display in configuration!",
  4020. base="red",
  4021. )
  4022. )
  4023. # self.queue_game.put("BEST TRADES:" + self.nl + self.nl.join(best_trades) + self.nl)
  4024. # self.queue_game.put("OK TRADES:" + self.nl + self.nl.join(ok_trades) + self.nl)
  4025. def get_display_maxlines(self):
  4026. show_maxlines = self.game.gamedata.get_config("Display_Maxlines", "0")
  4027. try:
  4028. show_maxlines = int(show_maxlines)
  4029. except ValueError:
  4030. show_maxlines = 0
  4031. if show_maxlines <= 0:
  4032. show_maxlines = None
  4033. return show_maxlines
  4034. def show_trade_report(self, *_):
  4035. show_maxlines = self.get_display_maxlines()
  4036. self.game.trade_report = self.trade_report
  4037. for t in self.trade_report[:show_maxlines]:
  4038. self.queue_game.put(t + self.nl)
  4039. self.queue_game.put(self.nl + Boxes.alert("Proxy done.", base="green"))
  4040. self.observer.load(self.save)
  4041. self.save = None
  4042. self.keepalive = None
  4043. self.prompt = None
  4044. # self.welcome_back()
  4045. def player(self, chunk: bytes):
  4046. """ Data from player (in bytes). """
  4047. chunk = chunk.decode("latin-1", "ignore")
  4048. key = chunk.upper()
  4049. log.debug("ProxyMenu.player({0})".format(key))
  4050. # Stop the keepalive if we are activating something else
  4051. # or leaving...
  4052. self.keepalive.stop()
  4053. if key == "T":
  4054. self.queue_game.put(self.c + key + self.r + self.nl)
  4055. # Trade Report
  4056. # do we have enough information to do this?
  4057. # if not hasattr(self.game, 'portdata') and not hasattr(self.game, 'warpdata'):
  4058. # self.queue_game.put("Missing portdata and warpdata." + self.nl)
  4059. # elif not hasattr(self.game, 'portdata'):
  4060. # self.queue_game.put("Missing portdata." + self.nl)
  4061. # elif not hasattr(self.game, 'warpdata'):
  4062. # self.queue_game.put("Missing warpdata." + self.nl)
  4063. # else:
  4064. if True:
  4065. # Yes, so let's start!
  4066. self.trade_report = []
  4067. d = coiterate(self.make_trade_report())
  4068. d.addCallback(self.show_trade_report)
  4069. return
  4070. elif key == "P":
  4071. self.queue_game.put(self.c + key + self.r + self.nl)
  4072. # Save specials, save 10 ports
  4073. self.specials = self.game.gamedata.special_ports()
  4074. # Save 20 ports. https://stackoverflow.com/questions/7971618/python-return-first-n-keyvalue-pairs-from-dict#7971655
  4075. self.old_ports = {
  4076. k: self.game.gamedata.ports[k]
  4077. for k in list(self.game.gamedata.ports)[:20]
  4078. }
  4079. self.game.gamedata.reset_ports()
  4080. # Activate CIM Port Report
  4081. report = CIMPortReport(self.game)
  4082. d = report.whenDone()
  4083. d.addCallback(self.port_report)
  4084. d.addErrback(self.welcome_back)
  4085. return
  4086. elif key == "W":
  4087. self.queue_game.put(self.c + key + self.r + self.nl)
  4088. self.game.gamedata.reset_warps()
  4089. # Activate CIM Warp Report
  4090. report = CIMWarpReport(self.game)
  4091. d = report.whenDone()
  4092. d.addCallback(self.warp_report)
  4093. d.addErrback(self.welcome_back)
  4094. return
  4095. elif key == "M":
  4096. self.queue_game.put(self.c + key + self.r + self.nl)
  4097. self.activate_macro(1)
  4098. if False:
  4099. ask = PlayerInput(self.game)
  4100. d = ask.prompt(
  4101. "How many times?", 10, name="times", abort_blank=True, digits=True
  4102. )
  4103. d.addCallback(self.activate_macro)
  4104. d.addErrback(self.welcome_back)
  4105. return
  4106. elif key == "S":
  4107. self.queue_game.put(self.c + key + self.r + self.nl)
  4108. # Scripts
  4109. self.activate_scripts_menu()
  4110. return
  4111. elif key == "R":
  4112. self.queue_game.put(self.c + key + self.r + self.nl)
  4113. s = self.game.gamedata.special_ports()
  4114. box = Boxes(14, color=self.c)
  4115. self.queue_game.put(box.top())
  4116. self.queue_game.put(box.row(self.c1 + " Sector Class "))
  4117. for sector, data in s.items():
  4118. self.queue_game.put(
  4119. box.row(
  4120. "{0} {1:5}{2} {3:^5} ".format(
  4121. self.c1, sector, self.c2, data["class"]
  4122. )
  4123. )
  4124. )
  4125. self.queue_game.put(box.bottom())
  4126. elif key == "D":
  4127. self.queue_game.put(self.c + key + self.r + self.nl)
  4128. # (Re) Display Trade Report
  4129. show_maxlines = self.get_display_maxlines()
  4130. if self.trade_report:
  4131. for t in self.trade_report[:show_maxlines]:
  4132. self.queue_game.put(t + self.nl)
  4133. self.queue_game.put(self.nl + Boxes.alert("Proxy done.", base="green"))
  4134. self.observer.load(self.save)
  4135. self.save = None
  4136. self.keepalive = None
  4137. self.prompt = None
  4138. return
  4139. else:
  4140. self.queue_game.put("Missing trade_report." + self.nl)
  4141. elif key == "E":
  4142. self.queue_game.put(self.c + key + self.r + self.nl)
  4143. self.queue_game.put(Boxes.alert("Saving..."))
  4144. then_do = coiterate(self.game.gamedata.save())
  4145. then_do.addCallback(self.welcome_back)
  4146. return
  4147. elif key == "C":
  4148. self.queue_game.put(self.c + key + self.r + self.nl)
  4149. self.activate_config_menu()
  4150. return
  4151. # self.queue_game.put(pformat(self.portdata).replace("\n", "\n\r") + self.nl)
  4152. # self.queue_game.put(pformat(self.warpdata).replace("\n", "\n\r") + self.nl)
  4153. # elif key == "Q":
  4154. # self.queue_game.put(self.c + key + self.r + self.nl)
  4155. #
  4156. # # This is an example of chaining PlayerInput prompt calls.
  4157. #
  4158. # ask = PlayerInput(self.game)
  4159. # d = ask.prompt("What is your quest?", 40, name="quest", abort_blank=True)
  4160. #
  4161. # # Display the user's input
  4162. # d.addCallback(ask.output)
  4163. #
  4164. # d.addCallback(
  4165. # lambda ignore: ask.prompt(
  4166. # "What is your favorite color?", 10, name="color"
  4167. # )
  4168. # )
  4169. # d.addCallback(ask.output)
  4170. #
  4171. # d.addCallback(
  4172. # lambda ignore: ask.prompt(
  4173. # "What is the meaning of the squirrel?",
  4174. # 12,
  4175. # name="squirrel",
  4176. # digits=True,
  4177. # )
  4178. # )
  4179. # d.addCallback(ask.output)
  4180. #
  4181. # def show_values(show):
  4182. # log.debug(show)
  4183. # self.queue_game.put(pformat(show).replace("\n", "\n\r") + self.nl)
  4184. #
  4185. # d.addCallback(lambda ignore: show_values(ask.keep))
  4186. # d.addCallback(self.welcome_back)
  4187. #
  4188. # # On error, just return back
  4189. # # This doesn't seem to be getting called.
  4190. # # d.addErrback(lambda ignore: self.welcome_back)
  4191. # d.addErrback(self.welcome_back)
  4192. # return
  4193. elif key == "X":
  4194. self.queue_game.put(self.c + key + self.r + self.nl)
  4195. self.queue_game.put(Boxes.alert("Proxy done.", base="green"))
  4196. self.observer.load(self.save)
  4197. self.save = None
  4198. # It isn't running (NOW), so don't try to stop it.
  4199. # self.keepalive.stop()
  4200. self.keepalive = None
  4201. # Ok, this is a HORRIBLE idea, because the prompt might be
  4202. # outdated.
  4203. # self.queue_game.put(self.prompt)
  4204. self.prompt = None
  4205. # Send '\r' to re-display the prompt
  4206. # instead of displaying the original one.
  4207. self.game.queue_player.put("d")
  4208. # Were we asked to do something when we were done here?
  4209. if self.defer:
  4210. reactor.CallLater(0, self.defer.callback)
  4211. # self.defer.callback()
  4212. self.defer = None
  4213. return
  4214. else:
  4215. self.fullmenu()
  4216. self.keepalive.start(30, True)
  4217. self.menu()
  4218. def activate_config_menu(self):
  4219. self.observer.disconnect("player", self.player)
  4220. self.observer.connect("player", self.config_player)
  4221. self.config_menu()
  4222. def deactivate_config_menu(self, *data):
  4223. log.warn("deactivate_config_menu ({0})".format(data))
  4224. self.observer.disconnect("player", self.config_player)
  4225. self.observer.connect("player", self.player)
  4226. self.welcome_back()
  4227. def activate_macro(self, *data):
  4228. log.warn("macro: ({0})".format(data))
  4229. macro = self.game.gamedata.get_config("Macro", "D")
  4230. # Macro processing would go in here ...
  4231. macro = macro.replace("^", "\r")
  4232. log.warn("macro: [{0}]".format(repr(macro)))
  4233. self.game.queue_player.put(macro)
  4234. log.warn("Restore ...")
  4235. self.observer.load(self.save)
  4236. self.save = None
  4237. self.keepalive = None
  4238. if self.defer:
  4239. reactor.CallLater(0, self.defer.callback)
  4240. self.defer = None
  4241. # self.welcome_back()
  4242. def activate_scripts_menu(self):
  4243. self.observer.disconnect("player", self.player)
  4244. self.observer.connect("player", self.scripts_player)
  4245. self.scripts_menu()
  4246. def option_entry(self, entry):
  4247. if len(entry) > 0:
  4248. # Ok, they gave us something
  4249. self.game.gamedata.set_config(self.option_select, entry.strip())
  4250. else:
  4251. self.queue_game.put("Edit aborted." + self.nl)
  4252. self.config_menu()
  4253. def option_input(self, option):
  4254. if len(option) > 0:
  4255. option = int(option)
  4256. if option in self.config_opt:
  4257. # Ok, it's a valid option!
  4258. self.option_select = self.config_opt[option]
  4259. ask = PlayerInput(self.game)
  4260. if self.option_select == "Macro":
  4261. d = ask.prompt("Change {0} to?".format(self.option_select), 48)
  4262. else:
  4263. d = ask.prompt("Change {0} to?".format(self.option_select), 18)
  4264. d.addCallback(self.option_entry)
  4265. # d.addErrback(self.config_menu)
  4266. else:
  4267. self.queue_game.put("Unknown option, sorry." + self.nl)
  4268. self.config_menu()
  4269. else:
  4270. # Aborted
  4271. self.config_menu()
  4272. def config_player(self, chunk: bytes):
  4273. """ Data from player (in bytes). """
  4274. chunk = chunk.decode("latin-1", "ignore")
  4275. key = chunk.upper()
  4276. if key == "C":
  4277. self.queue_game.put(self.c + key + self.r + self.nl)
  4278. self.game.gamedata.config = {}
  4279. elif key == "E":
  4280. self.queue_game.put(self.c + key + self.r + self.nl)
  4281. ask = PlayerInput(self.game)
  4282. d = ask.prompt(
  4283. "Which to edit?", 4, name="option", abort_blank=True, digits=True
  4284. )
  4285. d.addCallback(self.option_input)
  4286. d.addErrback(self.config_menu)
  4287. return
  4288. elif key in ("1", "2", "3", "4", "5", "6", "7", "8", "9"):
  4289. self.queue_game.put(self.c + key + self.r + self.nl)
  4290. option = int(key)
  4291. if option in self.config_opt:
  4292. # Ok, it's a valid option!
  4293. self.option_select = self.config_opt[option]
  4294. ask = PlayerInput(self.game)
  4295. if self.option_select == "Macro":
  4296. d = ask.prompt("Change {0} to?".format(self.option_select), 48)
  4297. else:
  4298. d = ask.prompt("Change {0} to?".format(self.option_select), 18)
  4299. d.addCallback(self.option_entry)
  4300. # d.addErrback(self.config_menu)
  4301. return
  4302. else:
  4303. self.queue_game.put("Unknown option, sorry." + self.nl)
  4304. elif key == "X":
  4305. self.queue_game.put(self.c + key + self.r + self.nl)
  4306. self.deactivate_config_menu()
  4307. return
  4308. else:
  4309. self.queue_game.put(self.c + "?" + self.r + self.nl)
  4310. self.config_menu()
  4311. def config_menu(self, *_):
  4312. titlecolor = merge(Style.BRIGHT + Fore.CYAN + Back.BLUE)
  4313. tc = merge(Style.BRIGHT + Fore.YELLOW + Back.BLUE)
  4314. c1 = merge(Style.BRIGHT + Fore.WHITE + Back.BLUE)
  4315. c2 = merge(Style.BRIGHT + Fore.CYAN + Back.BLUE)
  4316. # box = Boxes(44, color=titlecolor)
  4317. box = Boxes(44, color=tc)
  4318. self.queue_game.put(box.top())
  4319. # self.queue_game.put(box.row(titlecolor + "{0:^44}".format("Configuration")))
  4320. self.queue_game.put(box.row(tc + "{0:^44}".format("Configuration")))
  4321. self.queue_game.put(box.middle())
  4322. def config_option(index, key, value):
  4323. # Really, python? Because
  4324. # builtins.ValueError: Precision not allowed in integer format specifier
  4325. if type(value) == int:
  4326. value = str(value)
  4327. row = "{0}{1:2} {2:19}{3}{4:<20.20}".format(c1, index, key, c2, value)
  4328. self.queue_game.put(box.row(row))
  4329. def menu_item(ch, desc):
  4330. row = "{0} {1} {2}-{3} {4:39}".format(c1, ch, c2, c1, desc)
  4331. # self.queue_game.put(
  4332. # " " + c1 + ch + c2 + " - " + c1 + desc + self.nl
  4333. # )
  4334. self.queue_game.put(box.row(row))
  4335. index = 1
  4336. self.config_opt = {}
  4337. for k in sorted(self.game.gamedata.config.keys()):
  4338. # for k, v in self.game.gamedata.config.items():
  4339. v = self.game.gamedata.config[k]
  4340. self.config_opt[index] = k
  4341. config_option(index, k, v)
  4342. index += 1
  4343. self.queue_game.put(box.middle())
  4344. menu_item("C", "Clear Config")
  4345. menu_item("E", "Edit Item")
  4346. menu_item("X", "eXit")
  4347. self.queue_game.put(box.bottom())
  4348. self.queue_game.put(" " + tc + "-=>" + self.r + " ")
  4349. def deactivate_scripts_menu(self, *data):
  4350. log.warn("deactivate_scripts_menu ({0})".format(data))
  4351. self.observer.disconnect("player", self.scripts_player)
  4352. self.observer.connect("player", self.player)
  4353. # Did they request exit?
  4354. if len(data) > 0 and type(data[0]) == dict:
  4355. info = data[0]
  4356. if "exit" in info and info["exit"]:
  4357. log.warn("exit proxy...")
  4358. # Exit Proxy Code
  4359. self.queue_game.put(
  4360. self.nl + Boxes.alert("Proxy done.", base="green", style=3)
  4361. )
  4362. self.observer.load(self.save)
  4363. self.save = None
  4364. # It isn't running (NOW), so don't try to stop it.
  4365. # self.keepalive.stop()
  4366. self.keepalive = None
  4367. # Ok, this is a HORRIBLE idea, because the prompt might be
  4368. # outdated.
  4369. # self.queue_game.put(self.prompt)
  4370. self.prompt = None
  4371. # I'm not sure where we are, we might not be at a prompt.
  4372. # let's check!
  4373. if re.match(r"Command \[TL=.* \(\?=Help\)\? :", self.game.getPrompt()):
  4374. # Send '\r' to re-display the prompt
  4375. # instead of displaying the original one.
  4376. self.game.queue_player.put("d")
  4377. # Were we asked to do something when we were done here?
  4378. if self.defer:
  4379. reactor.CallLater(0, self.defer.callback)
  4380. # self.defer.callback()
  4381. self.defer = None
  4382. return
  4383. log.warn("calling welcome_back")
  4384. self.welcome_back()
  4385. def scripts_menu(self, *_):
  4386. c1 = merge(Style.BRIGHT + Fore.CYAN)
  4387. c2 = merge(Style.NORMAL + Fore.CYAN)
  4388. box = Boxes(40, color=c1)
  4389. self.queue_game.put(box.top())
  4390. self.queue_game.put(box.row(c1 + "{0:^40}".format("Scripts")))
  4391. self.queue_game.put(box.middle())
  4392. def menu_item(ch, desc):
  4393. row = " {0}{1} {2}-{3} {4:35}".format(c1, ch, c2, c1, desc)
  4394. # self.queue_game.put(
  4395. # " " + c1 + ch + c2 + " - " + c1 + desc + self.nl
  4396. # )
  4397. self.queue_game.put(box.row(row))
  4398. menu_item("1", "Ports (Trades between two sectors)")
  4399. menu_item("!", "Terrorize Ports/Trades")
  4400. menu_item("2", "Explore (Strange new sectors)")
  4401. menu_item("3", "Space... the broken script...")
  4402. menu_item("4", "Upgrade Planet")
  4403. # menu_item("5", "Colonize Planet")
  4404. menu_item("5", "Colonize Planet v2.0")
  4405. menu_item("%", "Maxumize Fighter Production")
  4406. menu_item("6", "Trade Evil (Does SSM)")
  4407. menu_item("X", "eXit")
  4408. self.queue_game.put(box.bottom())
  4409. self.queue_game.put(" " + c1 + "-=>" + self.r + " ")
  4410. def terror(self, *_):
  4411. log.debug("terror {0}".format(_))
  4412. loops = _[0]
  4413. if loops.strip() == "":
  4414. self.deactivate_scripts_menu()
  4415. else:
  4416. # Ok, we have something here, I think...
  4417. terror = ScriptTerror(self.game, self, int(loops))
  4418. d = terror.whenDone()
  4419. d.addCallback(self.deactivate_scripts_menu)
  4420. d.addErrback(self.deactivate_scripts_menu)
  4421. def scripts_player(self, chunk: bytes):
  4422. """ Data from player (in bytes). """
  4423. chunk = chunk.decode("latin-1", "ignore")
  4424. key = chunk.upper()
  4425. if key == "1":
  4426. self.queue_game.put(self.c + key + self.r + self.nl)
  4427. # Activate this magical event here
  4428. ports = ScriptPort(self.game)
  4429. d = ports.whenDone()
  4430. # d.addCallback(self.scripts_menu)
  4431. # d.addErrback(self.scripts_menu)
  4432. d.addCallback(self.deactivate_scripts_menu)
  4433. d.addErrback(self.deactivate_scripts_menu)
  4434. return
  4435. elif key == "!":
  4436. self.queue_game.put(self.c + key + self.r + self.nl)
  4437. ask = PlayerInput(self.game)
  4438. # This is TERROR, so do something!
  4439. ask.color(merge(Style.BRIGHT + Fore.WHITE + Back.RED))
  4440. ask.colorp(merge(Style.BRIGHT + Fore.YELLOW + Back.RED))
  4441. d = ask.prompt(
  4442. "How many loops of terror?",
  4443. 4,
  4444. name="loops",
  4445. digits=True,
  4446. abort_blank=True,
  4447. )
  4448. d.addCallback(self.terror, ask)
  4449. d.addErrback(self.deactivate_scripts_menu)
  4450. return
  4451. elif key == "2":
  4452. self.queue_game.put(self.c + key + self.r + self.nl)
  4453. explore = ScriptExplore(self.game)
  4454. d = explore.whenDone()
  4455. d.addCallback(self.deactivate_scripts_menu)
  4456. d.addErrback(self.deactivate_scripts_menu)
  4457. return
  4458. elif key == "3":
  4459. self.queue_game.put(self.c + key + self.r + self.nl)
  4460. space = ScriptSpace(self.game)
  4461. d = space.whenDone()
  4462. d.addCallback(self.deactivate_scripts_menu)
  4463. d.addErrback(self.deactivate_scripts_menu)
  4464. return
  4465. elif key == "4":
  4466. self.queue_game.put(self.c + key + self.r + self.nl)
  4467. upgrade = PlanetUpScript(self.game)
  4468. d = upgrade.whenDone()
  4469. d.addCallback(self.deactivate_scripts_menu)
  4470. d.addErrback(self.deactivate_scripts_menu)
  4471. return
  4472. elif key == "5":
  4473. self.queue_game.put(self.c + key + self.r + self.nl)
  4474. # colo = ColoScript(self.game)
  4475. colo = ColoScript2(self.game)
  4476. d = colo.whenDone()
  4477. d.addCallback(self.deactivate_scripts_menu)
  4478. d.addErrback(self.deactivate_scripts_menu)
  4479. return
  4480. elif key == "%":
  4481. self.queue_game.put(self.c + key + self.r + self.nl)
  4482. maxfigs = MaxFighterMake(self.game)
  4483. d = maxfigs.whenDone()
  4484. d.addCallback(self.deactivate_scripts_menu)
  4485. d.addErrback(self.deactivate_scripts_menu)
  4486. return
  4487. elif key == "6":
  4488. self.queue_game.put(self.c + key + self.r + self.nl)
  4489. evil = evilTrade(self.game)
  4490. d = evil.whenDone()
  4491. d.addCallback(self.deactivate_scripts_menu)
  4492. d.addErrback(self.deactivate_scripts_menu)
  4493. return
  4494. elif key == "X":
  4495. self.queue_game.put(self.c + key + self.r + self.nl)
  4496. self.deactivate_scripts_menu()
  4497. return
  4498. else:
  4499. self.queue_game.put(self.c + "?" + self.r + self.nl)
  4500. self.scripts_menu()
  4501. def welcome_back(self, *_):
  4502. log.debug("welcome_back")
  4503. self.keepalive.start(30, True)
  4504. self.menu()