devel.but 252 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099
  1. \cfg{text-indent}{0}
  2. \cfg{text-width}{72}
  3. \cfg{text-title-align}{left}
  4. \cfg{text-chapter-align}{left}
  5. \cfg{text-chapter-numeric}{true}
  6. \cfg{text-chapter-suffix}{. }
  7. \cfg{text-chapter-underline}{-}
  8. \cfg{text-section-align}{0}{left}
  9. \cfg{text-section-numeric}{0}{true}
  10. \cfg{text-section-suffix}{0}{. }
  11. \cfg{text-section-underline}{0}{-}
  12. \cfg{text-section-align}{1}{left}
  13. \cfg{text-section-numeric}{1}{true}
  14. \cfg{text-section-suffix}{1}{. }
  15. \cfg{text-section-underline}{1}{-}
  16. \cfg{text-versionid}{0}
  17. \cfg{html-contents-filename}{index.html}
  18. \cfg{html-template-filename}{%k.html}
  19. \cfg{html-index-filename}{docindex.html}
  20. \cfg{html-leaf-level}{1}
  21. \cfg{html-contents-depth-0}{1}
  22. \cfg{html-contents-depth-1}{3}
  23. \cfg{html-leaf-contains-contents}{true}
  24. \define{dash} \u2013{-}
  25. \title Developer documentation for Simon Tatham's puzzle collection
  26. This is a guide to the internal structure of Simon Tatham's Portable
  27. Puzzle Collection (henceforth referred to simply as \q{Puzzles}),
  28. for use by anyone attempting to implement a new puzzle or port to a
  29. new platform.
  30. This guide is believed correct as of \cw{git} commit
  31. \cw{a2212e82aa2f4b9a4ee22783d6fed2761c213432}. Hopefully it will be
  32. updated along with the code in future, but if not, I've at least left
  33. this version number in here so you can figure out what's changed by
  34. tracking commit comments from there onwards.
  35. \C{intro} Introduction
  36. The Puzzles code base is divided into four parts: a set of
  37. interchangeable front ends, a set of interchangeable back ends, a
  38. universal \q{middle end} which acts as a buffer between the two, and
  39. a bunch of miscellaneous utility functions. In the following
  40. sections I give some general discussion of each of these parts.
  41. \H{intro-frontend} Front end
  42. The front end is the non-portable part of the code: it's the bit
  43. that you replace completely when you port to a different platform.
  44. So it's responsible for all system calls, all GUI interaction, and
  45. anything else platform-specific.
  46. The front end contains \cw{main()} or the local platform's
  47. equivalent. Top-level control over the application's execution flow
  48. belongs to the front end (it isn't, for example, a set of functions
  49. called by a universal \cw{main()} somewhere else).
  50. The front end has complete freedom to design the GUI for any given
  51. port of Puzzles. There is no centralised mechanism for maintaining the
  52. menu layout, for example. This has a cost in consistency (when I
  53. \e{do} want the same menu layout on more than one platform, I have to
  54. edit N pieces of code in parallel every time I make a change), but the
  55. advantage is that local GUI conventions can be conformed to and local
  56. constraints adapted to. For example, MacOS has strict human interface
  57. guidelines which specify a different menu layout from the one I've
  58. used on Windows and GTK; there's nothing stopping the MacOS front end
  59. from providing a menu layout consistent with those guidelines.
  60. Although the front end is mostly caller rather than the callee in
  61. its interactions with other parts of the code, it is required to
  62. implement a small API for other modules to call, mostly of drawing
  63. functions for games to use when drawing their graphics. The drawing
  64. API is documented in \k{drawing}; the other miscellaneous front end
  65. API functions are documented in \k{frontend-api}.
  66. \H{intro-backend} Back end
  67. A \q{back end}, in this collection, is synonymous with a \q{puzzle}.
  68. Each back end implements a different game.
  69. At the top level, a back end is simply a data structure, containing
  70. a few constants (flag words, preferred pixel size) and a large
  71. number of function pointers. Back ends are almost invariably callee
  72. rather than caller, which means there's a limitation on what a back
  73. end can do on its own initiative.
  74. The persistent state in a back end is divided into a number of data
  75. structures, which are used for different purposes and therefore
  76. likely to be switched around, changed without notice, and otherwise
  77. updated by the rest of the code. It is important when designing a
  78. back end to put the right pieces of data into the right structures,
  79. or standard midend-provided features (such as Undo) may fail to
  80. work.
  81. The functions and variables provided in the back end data structure
  82. are documented in \k{backend}.
  83. \H{intro-midend} Middle end
  84. Puzzles has a single and universal \q{middle end}. This code is
  85. common to all platforms and all games; it sits in between the front
  86. end and the back end and provides standard functionality everywhere.
  87. People adding new back ends or new front ends should generally not
  88. need to edit the middle end. On rare occasions there might be a
  89. change that can be made to the middle end to permit a new game to do
  90. something not currently anticipated by the middle end's present
  91. design; however, this is terribly easy to get wrong and should
  92. probably not be undertaken without consulting the primary maintainer
  93. (me). Patch submissions containing unannounced mid-end changes will
  94. be treated on their merits like any other patch; this is just a
  95. friendly warning that mid-end changes will need quite a lot of
  96. merits to make them acceptable.
  97. Functionality provided by the mid-end includes:
  98. \b Maintaining a list of game state structures and moving back and
  99. forth along that list to provide Undo and Redo.
  100. \b Handling timers (for move animations, flashes on completion, and
  101. in some cases actually timing the game).
  102. \b Handling the container format of game IDs: receiving them,
  103. picking them apart into parameters, description and/or random seed,
  104. and so on. The game back end need only handle the individual parts
  105. of a game ID (encoded parameters and encoded game description);
  106. everything else is handled centrally by the mid-end.
  107. \b Handling standard keystrokes and menu commands, such as \q{New
  108. Game}, \q{Restart Game} and \q{Quit}.
  109. \b Pre-processing mouse events so that the game back ends can rely
  110. on them arriving in a sensible order (no missing button-release
  111. events, no sudden changes of which button is currently pressed,
  112. etc).
  113. \b Handling the dialog boxes which ask the user for a game ID.
  114. \b Handling serialisation of entire games (for loading and saving a
  115. half-finished game to a disk file; for handling application shutdown
  116. and restart on platforms such as PalmOS where state is expected to be
  117. saved; for storing the previous game in order to undo and redo across
  118. a New Game event).
  119. Thus, there's a lot of work done once by the mid-end so that
  120. individual back ends don't have to worry about it. All the back end
  121. has to do is cooperate in ensuring the mid-end can do its work
  122. properly.
  123. The API of functions provided by the mid-end to be called by the
  124. front end is documented in \k{midend}.
  125. \H{intro-utils} Miscellaneous utilities
  126. In addition to these three major structural components, the Puzzles
  127. code also contains a variety of utility modules usable by all of the
  128. above components. There is a set of functions to provide
  129. platform-independent random number generation; functions to make
  130. memory allocation easier; functions which implement a balanced tree
  131. structure to be used as necessary in complex algorithms; and a few
  132. other miscellaneous functions. All of these are documented in
  133. \k{utils}.
  134. \H{intro-structure} Structure of this guide
  135. There are a number of function call interfaces within Puzzles, and
  136. this guide will discuss each one in a chapter of its own. After
  137. that, \k{writing} discusses how to design new games, with some
  138. general design thoughts and tips.
  139. \C{backend} Interface to the back end
  140. This chapter gives a detailed discussion of the interface that each
  141. back end must implement.
  142. At the top level, each back end source file exports a single global
  143. symbol, which is a \c{const struct game} containing a large number
  144. of function pointers and a small amount of constant data. This
  145. structure is called by different names depending on what kind of
  146. platform the puzzle set is being compiled on:
  147. \b On platforms such as Windows and GTK, which build a separate
  148. binary for each puzzle, the game structure in every back end has the
  149. same name, \cq{thegame}; the front end refers directly to this name,
  150. so that compiling the same front end module against a different back
  151. end module builds a different puzzle.
  152. \b On platforms such as MacOS X and PalmOS, which build all the
  153. puzzles into a single monolithic binary, the game structure in each
  154. back end must have a different name, and there's a helper module
  155. \c{list.c} which constructs a complete list of those game structures
  156. from a header file generated by CMake.
  157. On the latter type of platform, source files may assume that the
  158. preprocessor symbol \c{COMBINED} has been defined. Thus, the usual
  159. code to declare the game structure looks something like this:
  160. \c #ifdef COMBINED
  161. \c #define thegame net /* or whatever this game is called */
  162. \e iii iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
  163. \c #endif
  164. \c
  165. \c const struct game thegame = {
  166. \c /* lots of structure initialisation in here */
  167. \e iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
  168. \c };
  169. Game back ends must also internally define a number of data
  170. structures, for storing their various persistent state. This chapter
  171. will first discuss the nature and use of those structures, and then
  172. go on to give details of every element of the game structure.
  173. \H{backend-structs} Data structures
  174. Each game is required to define four separate data structures. This
  175. section discusses each one and suggests what sorts of things need to
  176. be put in it.
  177. \S{backend-game-params} \c{game_params}
  178. The \c{game_params} structure contains anything which affects the
  179. automatic generation of new puzzles. So if puzzle generation is
  180. parametrised in any way, those parameters need to be stored in
  181. \c{game_params}.
  182. Most puzzles currently in this collection are played on a grid of
  183. squares, meaning that the most obvious parameter is the grid size.
  184. Many puzzles have additional parameters; for example, Mines allows
  185. you to control the number of mines in the grid independently of its
  186. size, Net can be wrapping or non-wrapping, Solo has difficulty
  187. levels and symmetry settings, and so on.
  188. A simple rule for deciding whether a data item needs to go in
  189. \c{game_params} is: would the user expect to be able to control this
  190. data item from either the preset-game-types menu or the \q{Custom}
  191. game type configuration? If so, it's part of \c{game_params}.
  192. \c{game_params} structures are permitted to contain pointers to
  193. subsidiary data if they need to. The back end is required to provide
  194. functions to create and destroy \c{game_params}, and those functions
  195. can allocate and free additional memory if necessary. (It has not
  196. yet been necessary to do this in any puzzle so far, but the
  197. capability is there just in case.)
  198. \c{game_params} is also the only structure which the game's
  199. \cw{compute_size()} function may refer to; this means that any aspect
  200. of the game which affects the size of the window it needs to be drawn
  201. in (other than the magnification level) must be stored in
  202. \c{game_params}. In particular, this imposes the fundamental
  203. limitation that random game generation may not have a random effect on
  204. the window size: game generation algorithms are constrained to work by
  205. starting from the grid size rather than generating it as an emergent
  206. phenomenon. (Although this is a restriction in theory, it has not yet
  207. seemed to be a problem.)
  208. \S{backend-game-state} \c{game_state}
  209. While the user is actually playing a puzzle, the \c{game_state}
  210. structure stores all the data corresponding to the current state of
  211. play.
  212. The mid-end keeps \c{game_state}s in a list, and adds to the list
  213. every time the player makes a move; the Undo and Redo functions step
  214. back and forth through that list.
  215. Therefore, a good means of deciding whether a data item needs to go in
  216. \c{game_state} is: would a player expect that data item to be restored
  217. on undo? If so, put it in \c{game_state}, and this will automatically
  218. happen without you having to lift a finger. If not, then you might
  219. have found a data item that needs to go in \c{game_ui} instead.
  220. Two quite different examples of this:
  221. \b if the game provides an interface for making moves by moving a
  222. cursor around the grid with the keyboard and pressing some other key
  223. when you get to a square you want to change, then the location of that
  224. cursor belongs in \c{game_ui}, because the player will want to undo
  225. one \e{square change} at a time, not one \e{cursor movement} at a
  226. time.
  227. \b Mines tracks the number of times you opened a mine square and died.
  228. Every time you do that, you can only continue the game by pressing
  229. Undo. So the deaths counter belongs in \c{game_ui}, because otherwise,
  230. it would revert to 0 every time you undid your mistaken move.
  231. During play, \c{game_state}s are often passed around without an
  232. accompanying \c{game_params} structure. Therefore, any information
  233. in \c{game_params} which is important during play (such as the grid
  234. size) must be duplicated within the \c{game_state}. One simple
  235. method of doing this is to have the \c{game_state} structure
  236. \e{contain} a \c{game_params} structure as one of its members,
  237. although this isn't obligatory if you prefer to do it another way.
  238. \S{backend-game-drawstate} \c{game_drawstate}
  239. \c{game_drawstate} carries persistent state relating to the current
  240. graphical contents of the puzzle window. The same \c{game_drawstate}
  241. is passed to every call to the game redraw function, so that it can
  242. remember what it has already drawn and what needs redrawing.
  243. A typical use for a \c{game_drawstate} is to have an array mirroring
  244. the array of grid squares in the \c{game_state}, but describing what
  245. was drawn in the window on the most recent redraw. This is used to
  246. identify the squares that need redrawing next time, by deciding what
  247. the new value in that array should be, and comparing it to what was
  248. drawn last time. See \k{writing-howto-redraw} for more on this
  249. subject.
  250. \c{game_drawstate} is occasionally completely torn down and
  251. reconstructed by the mid-end, if the user somehow forces a full
  252. redraw. Therefore, no data should be stored in \c{game_drawstate}
  253. which is \e{not} related to the state of the puzzle window, because
  254. it might be unexpectedly destroyed.
  255. The back end provides functions to create and destroy
  256. \c{game_drawstate}, which means it can contain pointers to
  257. subsidiary allocated data if it needs to. A common thing to want to
  258. allocate in a \c{game_drawstate} is a \c{blitter}; see
  259. \k{drawing-blitter} for more on this subject.
  260. \S{backend-game-ui} \c{game_ui}
  261. \c{game_ui} contains whatever doesn't fit into the above three
  262. structures!
  263. A new \c{game_ui} is created when the user begins playing a new
  264. instance of a puzzle (i.e. during \q{New Game} or after entering a
  265. game ID etc). It persists until the user finishes playing that game
  266. and begins another one (or closes the window); in particular,
  267. \q{Restart Game} does \e{not} destroy the \c{game_ui}.
  268. There are various things that you might store in \c{game_ui}, which
  269. are conceptually different from each other, but I haven't yet found a
  270. need to split them out into smaller sub-structures for different
  271. purposes:
  272. \dt Transient UI state:
  273. \dd Storing a piece of UI state in \c{game_state} means that you can
  274. only update it by appending a move to the undo chain. Some UI state
  275. shouldn't really be treated this way. For example, if your puzzle has
  276. a keyboard-controlled cursor, you probably don't want every cursor
  277. movement to be an undoable action, because the history of where the
  278. cursor went just isn't interesting. More likely the cursor should just
  279. move freely, and the only undoable actions are the ones where you
  280. modify the element under the cursor. So you'd store the cursor
  281. position in \c{game_ui} rather than \c{game_state}. See
  282. \k{writing-keyboard-cursor} for more details.
  283. \lcont{ Another example of this is the state of an ongoing mouse drag.
  284. If there's an undoable action involved, it will probably occur when
  285. the drag is released. In between, you still need to store state that
  286. the redraw function will use to update the display \dash and that can
  287. live in \c{game_ui}. See \k{writing-howto-dragging} for more details
  288. of this. }
  289. \dt Persistent UI state:
  290. \dd An example of this is the counter of deaths in Mines or Inertia.
  291. This shouldn't be reverted by pressing Undo, for the opposite reason
  292. to the cursor position: the cursor position is too boring to store the
  293. history of, but the deaths counter is too \e{important}!
  294. \dt Information about recent changes to the game state:
  295. \dd This is used in Mines, for example, to indicate whether a
  296. requested \q{flash} should be a white flash for victory or a red flash
  297. for defeat; see \k{writing-flash-types}.
  298. \dt User preferences:
  299. \dd Any user preference about display or UI handled by
  300. \cw{get_prefs()} and \cw{set_prefs()} will need to live in
  301. \c{game_ui}, because that's the structure that those functions access.
  302. \H{backend-simple} Simple data in the back end
  303. In this section I begin to discuss each individual element in the
  304. back end structure. To begin with, here are some simple
  305. self-contained data elements.
  306. \S{backend-name} \c{name}
  307. \c const char *name;
  308. This is a simple ASCII string giving the name of the puzzle. This
  309. name will be used in window titles, in game selection menus on
  310. monolithic platforms, and anywhere else that the front end needs to
  311. know the name of a game.
  312. \S{backend-winhelp} \c{winhelp_topic} and \c{htmlhelp_topic}
  313. \c const char *winhelp_topic, *htmlhelp_topic;
  314. These members are used on Windows only, to provide online help.
  315. Although the Windows front end provides a separate binary for each
  316. puzzle, it has a single monolithic help file; so when a user selects
  317. \q{Help} from the menu, the program needs to open the help file and
  318. jump to the chapter describing that particular puzzle.
  319. This code base still supports the legacy \cw{.HLP} Windows Help format
  320. as well as the less old \cw{.CHM} HTML Help format. The two use
  321. different methods of identifying topics, so you have to specify both.
  322. Each chapter about a puzzle in \c{puzzles.but} is labelled with a
  323. \e{help topic} name for Windows Help, which typically appears just
  324. after the \cw{\\C} chapter title paragraph, similar to this:
  325. \c \C{net} \i{Net}
  326. \c
  327. \c \cfg{winhelp-topic}{games.net}
  328. But HTML Help is able to use the Halibut identifier for the chapter
  329. itself, i.e. the keyword that appears in braces immediatey after the
  330. \cw{\\C}.
  331. So the corresponding game back end encodes the \c{winhelp-topic}
  332. string (here \cq{games.net}) in the \c{winhelp_topic} element of the
  333. game structure, and puts the chapter identifier (here \cq{net}) in the
  334. \c{htmlhelp_topic} element. For example:
  335. \c const struct game thegame = {
  336. \c "Net", "games.net", "net",
  337. \c // ...
  338. \c };
  339. \H{backend-params} Handling game parameter sets
  340. In this section I present the various functions which handle the
  341. \c{game_params} structure.
  342. \S{backend-default-params} \cw{default_params()}
  343. \c game_params *(*default_params)(void);
  344. This function allocates a new \c{game_params} structure, fills it
  345. with the default values, and returns a pointer to it.
  346. \S{backend-fetch-preset} \cw{fetch_preset()}
  347. \c bool (*fetch_preset)(int i, char **name, game_params **params);
  348. This function is one of the two APIs a back end can provide to
  349. populate the \q{Type} menu, which provides a list of conveniently
  350. accessible preset parameters for most games.
  351. The function is called with \c{i} equal to the index of the preset
  352. required (numbering from zero). It returns \cw{false} if that preset
  353. does not exist (if \c{i} is less than zero or greater than the
  354. largest preset index). Otherwise, it sets \c{*params} to point at a
  355. newly allocated \c{game_params} structure containing the preset
  356. information, sets \c{*name} to point at a newly allocated C string
  357. containing the preset title (to go on the \q{Type} menu), and
  358. returns \cw{true}.
  359. If the game does not wish to support any presets at all, this
  360. function is permitted to return \cw{false} always.
  361. If the game wants to return presets in the form of a hierarchical menu
  362. instead of a flat list (and, indeed, even if it doesn't), then it may
  363. set this function pointer to \cw{NULL}, and instead fill in the
  364. alternative function pointer \cw{preset_menu}
  365. (\k{backend-preset-menu}).
  366. \S{backend-preset-menu} \cw{preset_menu()}
  367. \c struct preset_menu *(*preset_menu)(void);
  368. This function is the more flexible of the two APIs by which a back end
  369. can define a collection of preset game parameters.
  370. This function simply returns a complete menu hierarchy, in the form of
  371. a \c{struct preset_menu} (see \k{midend-get-presets}) and further
  372. submenus (if it wishes) dangling off it. There are utility functions
  373. described in \k{utils-presets} to make it easy for the back end to
  374. construct this menu.
  375. If the game has no need to return a hierarchy of menus, it may instead
  376. opt to implement the \cw{fetch_preset()} function (see
  377. \k{backend-fetch-preset}).
  378. The game need not fill in the \c{id} fields in the preset menu
  379. structures. The mid-end will do that after it receives the structure
  380. from the game, and before passing it on to the front end.
  381. \S{backend-encode-params} \cw{encode_params()}
  382. \c char *(*encode_params)(const game_params *params, bool full);
  383. The job of this function is to take a \c{game_params}, and encode it
  384. in a printable ASCII string form for use in game IDs. The return value must
  385. be a newly allocated C string, and \e{must} not contain a colon or a hash
  386. (since those characters are used to mark the end of the parameter
  387. section in a game ID).
  388. Ideally, it should also not contain any other potentially
  389. controversial punctuation; bear in mind when designing a string
  390. parameter format that it will probably be used on both Windows and
  391. Unix command lines under a variety of exciting shell quoting and
  392. metacharacter rules. Sticking entirely to alphanumerics is the
  393. safest thing; if you really need punctuation, you can probably get
  394. away with commas, periods or underscores without causing anybody any
  395. major inconvenience. If you venture far beyond that, you're likely
  396. to irritate \e{somebody}.
  397. (At the time of writing this, most existing games have purely
  398. alphanumeric string parameter formats. Usually these involve a
  399. letter denoting a parameter, followed optionally by a number giving
  400. the value of that parameter, with a few mandatory parts at the
  401. beginning such as numeric width and height separated by \cq{x}.)
  402. If the \c{full} parameter is \cw{true}, this function should encode
  403. absolutely everything in the \c{game_params}, such that a subsequent
  404. call to \cw{decode_params()} (\k{backend-decode-params}) will yield
  405. an identical structure. If \c{full} is \cw{false}, however, you
  406. should leave out anything which is not necessary to describe a
  407. \e{specific puzzle instance}, i.e. anything which only takes effect
  408. when a new puzzle is \e{generated}.
  409. For example, the Solo \c{game_params} includes a difficulty rating
  410. used when constructing new puzzles; but a Solo game ID need not
  411. explicitly include the difficulty, since to describe a puzzle once
  412. generated it's sufficient to give the grid dimensions and the location
  413. and contents of the clue squares. (Indeed, one might very easily type
  414. in a puzzle out of a newspaper without \e{knowing} what its difficulty
  415. level is in Solo's terminology.) Therefore, Solo's
  416. \cw{encode_params()} only encodes the difficulty level if \c{full} is
  417. set.
  418. \S{backend-decode-params} \cw{decode_params()}
  419. \c void (*decode_params)(game_params *params, char const *string);
  420. This function is the inverse of \cw{encode_params()}
  421. (\k{backend-encode-params}). It parses the supplied string and fills
  422. in the supplied \c{game_params} structure. Note that the structure
  423. will \e{already} have been allocated: this function is not expected
  424. to create a \e{new} \c{game_params}, but to modify an existing one.
  425. This function can receive a string which only encodes a subset of
  426. the parameters. The most obvious way in which this can happen is if
  427. the string was constructed by \cw{encode_params()} with its \c{full}
  428. parameter set to \cw{false}; however, it could also happen if the
  429. user typed in a parameter set manually and missed something out. Be
  430. prepared to deal with a wide range of possibilities.
  431. When dealing with a parameter which is not specified in the input
  432. string, what to do requires a judgment call on the part of the
  433. programmer. Sometimes it makes sense to adjust other parameters to
  434. bring them into line with the new ones. In Mines, for example, you
  435. would probably not want to keep the same mine count if the user
  436. dropped the grid size and didn't specify one, since you might easily
  437. end up with more mines than would actually fit in the grid! On the
  438. other hand, sometimes it makes sense to leave the parameter alone: a
  439. Solo player might reasonably expect to be able to configure size and
  440. difficulty independently of one another.
  441. This function currently has no direct means of returning an error if
  442. the string cannot be parsed at all. However, the returned
  443. \c{game_params} is almost always subsequently passed to
  444. \cw{validate_params()} (\k{backend-validate-params}), so if you
  445. really want to signal parse errors, you could always have a \c{char
  446. *} in your parameters structure which stored an error message, and
  447. have \cw{validate_params()} return it if it is non-\cw{NULL}.
  448. \S{backend-free-params} \cw{free_params()}
  449. \c void (*free_params)(game_params *params);
  450. This function frees a \c{game_params} structure, and any subsidiary
  451. allocations contained within it.
  452. \S{backend-dup-params} \cw{dup_params()}
  453. \c game_params *(*dup_params)(const game_params *params);
  454. This function allocates a new \c{game_params} structure and
  455. initialises it with an exact copy of the information in the one
  456. provided as input. It returns a pointer to the new duplicate.
  457. \S{backend-can-configure} \c{can_configure}
  458. \c bool can_configure;
  459. This data element is set to \cw{true} if the back end supports custom
  460. parameter configuration via a dialog box. If it is \cw{true}, then the
  461. functions \cw{configure()} and \cw{custom_params()} are expected to
  462. work. See \k{backend-configure} and \k{backend-custom-params} for more
  463. details.
  464. \S{backend-configure} \cw{configure()}
  465. \c config_item *(*configure)(const game_params *params);
  466. This function is called when the user requests a dialog box for
  467. custom parameter configuration. It returns a newly allocated array
  468. of \cw{config_item} structures, describing the GUI elements required
  469. in the dialog box. The array should have one more element than the
  470. number of controls, since it is terminated with a \cw{C_END} marker
  471. (see below). Each array element describes the control together with
  472. its initial value; the front end will modify the value fields and
  473. return the updated array to \cw{custom_params()} (see
  474. \k{backend-custom-params}).
  475. The \cw{config_item} structure contains the following elements used by
  476. this function:
  477. \c const char *name;
  478. \c int type;
  479. \c union { /* type-specific fields */ } u;
  480. \e iiiiiiiiiiiiiiiiiiiiiiiiii
  481. \c{name} is an ASCII string giving the textual label for a GUI
  482. control. It is \e{not} expected to be dynamically allocated.
  483. \c{type} contains one of a small number of \c{enum} values defining
  484. what type of control is being described. The usable member of the
  485. union field \c{u} depends on \c{type}. The valid type values are:
  486. \dt \c{C_STRING}
  487. \dd Describes a text input box. (This is also used for numeric
  488. input. The back end does not bother informing the front end that the
  489. box is numeric rather than textual; some front ends do have the
  490. capacity to take this into account, but I decided it wasn't worth
  491. the extra complexity in the interface.)
  492. \lcont{
  493. For controls of this type, \c{u.string} contains a single field
  494. \c char *sval;
  495. which stores a dynamically allocated string representing the contents
  496. of the input box.
  497. }
  498. \dt \c{C_BOOLEAN}
  499. \dd Describes a simple checkbox.
  500. \lcont{
  501. For controls of this type, \c{u.boolean} contains a single field
  502. \c bool bval;
  503. }
  504. \dt \c{C_CHOICES}
  505. \dd Describes a drop-down list presenting one of a small number of
  506. fixed choices.
  507. \lcont{
  508. For controls of this type, \c{u.choices} contains two fields:
  509. \c const char *choicenames;
  510. \c int selected;
  511. \c{choicenames} contains a list of strings describing the choices. The
  512. very first character of \c{sval} is used as a delimiter when
  513. processing the rest (so that the strings \cq{:zero:one:two},
  514. \cq{!zero!one!two} and \cq{xzeroxonextwo} all define a three-element
  515. list containing \cq{zero}, \cq{one} and \cq{two}).
  516. \c{selected} contains the index of the currently selected element,
  517. numbering from zero (so that in the above example, 0 would mean
  518. \cq{zero} and 2 would mean \cq{two}).
  519. Note that \c{u.choices.choicenames} is \e{not} dynamically allocated,
  520. unlike \c{u.string.sval}.
  521. }
  522. \dt \c{C_END}
  523. \dd Marks the end of the array of \c{config_item}s. There is no
  524. associated member of the union field \c{u} for this type.
  525. The array returned from this function is expected to have filled in
  526. the initial values of all the controls according to the input
  527. \c{game_params} structure.
  528. If the game's \c{can_configure} flag is set to \cw{false}, this
  529. function is never called and can be \cw{NULL}.
  530. \S{backend-custom-params} \cw{custom_params()}
  531. \c game_params *(*custom_params)(const config_item *cfg);
  532. This function is the counterpart to \cw{configure()}
  533. (\k{backend-configure}). It receives as input an array of
  534. \c{config_item}s which was originally created by \cw{configure()},
  535. but in which the control values have since been changed in
  536. accordance with user input. Its function is to read the new values
  537. out of the controls and return a newly allocated \c{game_params}
  538. structure representing the user's chosen parameter set.
  539. (The front end will have modified the controls' \e{values}, but
  540. there will still always be the same set of controls, in the same
  541. order, as provided by \cw{configure()}. It is not necessary to check
  542. the \c{name} and \c{type} fields, although you could use
  543. \cw{assert()} if you were feeling energetic.)
  544. This function is not expected to (and indeed \e{must not}) free the
  545. input \c{config_item} array. (If the parameters fail to validate,
  546. the dialog box will stay open.)
  547. If the game's \c{can_configure} flag is set to \cw{false}, this
  548. function is never called and can be \cw{NULL}.
  549. \S{backend-get-prefs} \cw{get_prefs()}
  550. \c config_item *(*get_prefs)(game_ui *ui);
  551. This function works very like \cw{configure()}, but instead of
  552. receiving a \c{game_params} and returning GUI elements describing the
  553. data in it, this function receives a \c{game_ui} and returns GUI
  554. elements describing any user preferences stored in that.
  555. This function should only deal with fields of \c{game_ui} that are
  556. user-settable preferences. In-game state like cursor position and
  557. mouse drags, or per-game state like death counters, are nothing to do
  558. with this function.
  559. If there are no user preferences, you can set both this function
  560. pointer and \c{set_prefs} to \cw{NULL}.
  561. If you implement these functions, you must also ensure that your
  562. game's \cw{new_ui()} function can be called with a null \c{game_state}
  563. pointer. (See \k{backend-new-ui}.)
  564. In every \c{config_item} returned from this function, you must set an
  565. additional field beyond the ones described in \k{backend-configure}:
  566. \c const char *kw;
  567. This should be an identifying keyword for the user preference in
  568. question, suitable for use in configuration files. That means it
  569. should remain stable, even if the user-facing wording in the \c{name}
  570. field is reworded for clarity. If it doesn't stay stable, old
  571. configuration files will not be read correctly.
  572. For \c{config_item}s of type \cw{C_CHOICES}, you must also set an
  573. extra field in \c{u.choices}:
  574. \c const char *choicekws;
  575. This has the same structure as the \c{choicenames} field (a list of
  576. values delimited by the first character in the whole string), and it
  577. provides an identifying keyword for each individual choice in the
  578. list, in the same order as the entries of \c{choicenames}.
  579. \S{backend-set-prefs} \cw{set_prefs()}
  580. \c void (*set_prefs)(game_ui *ui, const config_item *cfg);
  581. This function is the counterpart to \cw{set_prefs()}, as
  582. \cw{custom_params()} is to \cw{configure()}. It receives an array of
  583. \c{config_item}s which was originally created by \cw{get_prefs()},
  584. with the controls' values updated from user input, and it should
  585. transcribe the new settings into the provided \c{game_ui}.
  586. If there are no user preferences, you can set both this function
  587. pointer and \c{get_prefs} to \cw{NULL}.
  588. \S{backend-validate-params} \cw{validate_params()}
  589. \c const char *(*validate_params)(const game_params *params,
  590. \c bool full);
  591. This function takes a \c{game_params} structure as input, and checks
  592. that the parameters described in it fall within sensible limits. (At
  593. the very least, grid dimensions should almost certainly be strictly
  594. positive, for example.)
  595. Return value is \cw{NULL} if no problems were found, or
  596. alternatively a (non-dynamically-allocated) ASCII string describing
  597. the error in human-readable form.
  598. If the \c{full} parameter is set, full validation should be
  599. performed: any set of parameters which would not permit generation
  600. of a sensible puzzle should be faulted. If \c{full} is \e{not} set,
  601. the implication is that these parameters are not going to be used
  602. for \e{generating} a puzzle; so parameters which can't even sensibly
  603. \e{describe} a valid puzzle should still be faulted, but parameters
  604. which only affect puzzle generation should not be.
  605. (The \c{full} option makes a difference when parameter combinations
  606. are non-orthogonal. For example, Net has a boolean option
  607. controlling whether it enforces a unique solution; it turns out that
  608. it's impossible to generate a uniquely soluble puzzle with wrapping
  609. walls and width 2, so \cw{validate_params()} will complain if you
  610. ask for one. However, if the user had just been playing a unique
  611. wrapping puzzle of a more sensible width, and then pastes in a game
  612. ID acquired from somebody else which happens to describe a
  613. \e{non}-unique wrapping width-2 puzzle, then \cw{validate_params()}
  614. will be passed a \c{game_params} containing the width and wrapping
  615. settings from the new game ID and the uniqueness setting from the
  616. old one. This would be faulted, if it weren't for the fact that
  617. \c{full} is not set during this call, so Net ignores the
  618. inconsistency. The resulting \c{game_params} is never subsequently
  619. used to generate a puzzle; this is a promise made by the mid-end
  620. when it asks for a non-full validation.)
  621. \H{backend-descs} Handling game descriptions
  622. In this section I present the functions that deal with a textual
  623. description of a puzzle, i.e. the part that comes after the colon in
  624. a descriptive-format game ID.
  625. \S{backend-new-desc} \cw{new_desc()}
  626. \c char *(*new_desc)(const game_params *params, random_state *rs,
  627. \c char **aux, bool interactive);
  628. This function is where all the really hard work gets done. This is
  629. the function whose job is to randomly generate a new puzzle,
  630. ensuring solubility and uniqueness as appropriate.
  631. As input it is given a \c{game_params} structure and a random state
  632. (see \k{utils-random} for the random number API). It must invent a
  633. puzzle instance, encode it in printable ASCII string form, and
  634. return a dynamically allocated C string containing that encoding.
  635. Additionally, it may return a second dynamically allocated string in
  636. \c{*aux}. (If it doesn't want to, then it can leave that parameter
  637. completely alone; it isn't required to set it to \cw{NULL}, although
  638. doing so is harmless.) That string, if present, will be passed to
  639. \cw{solve()} (\k{backend-solve}) later on; so if the puzzle is
  640. generated in such a way that a solution is known, then information
  641. about that solution can be saved in \c{*aux} for \cw{solve()} to
  642. use.
  643. The \c{interactive} parameter should be ignored by almost all
  644. puzzles. Its purpose is to distinguish between generating a puzzle
  645. within a GUI context for immediate play, and generating a puzzle in
  646. a command-line context for saving to be played later. The only
  647. puzzle that currently uses this distinction (and, I fervently hope,
  648. the only one which will \e{ever} need to use it) is Mines, which
  649. chooses a random first-click location when generating puzzles
  650. non-interactively, but which waits for the user to place the first
  651. click when interactive. If you think you have come up with another
  652. puzzle which needs to make use of this parameter, please think for
  653. at least ten minutes about whether there is \e{any} alternative!
  654. Note that game description strings are not required to contain an
  655. encoding of parameters such as grid size; a game description is
  656. never separated from the \c{game_params} it was generated with, so
  657. any information contained in that structure need not be encoded
  658. again in the game description.
  659. \S{backend-validate-desc} \cw{validate_desc()}
  660. \c const char *(*validate_desc)(const game_params *params,
  661. \c const char *desc);
  662. This function is given a game description, and its job is to
  663. validate that it describes a puzzle which makes sense.
  664. To some extent it's up to the user exactly how far they take the
  665. phrase \q{makes sense}; there are no particularly strict rules about
  666. how hard the user is permitted to shoot themself in the foot when
  667. typing in a bogus game description by hand. (For example, Rectangles
  668. will not verify that the sum of all the numbers in the grid equals
  669. the grid's area. So a user could enter a puzzle which was provably
  670. not soluble, and the program wouldn't complain; there just wouldn't
  671. happen to be any sequence of moves which solved it.)
  672. The one non-negotiable criterion is that any game description which
  673. makes it through \cw{validate_desc()} \e{must not} subsequently
  674. cause a crash or an assertion failure when fed to \cw{new_game()}
  675. and thence to the rest of the back end.
  676. The return value is \cw{NULL} on success, or a
  677. non-dynamically-allocated C string containing an error message.
  678. \S{backend-new-game} \cw{new_game()}
  679. \c game_state *(*new_game)(midend *me, const game_params *params,
  680. \c const char *desc);
  681. This function takes a game description as input, together with its
  682. accompanying \c{game_params}, and constructs a \c{game_state}
  683. describing the initial state of the puzzle. It returns a newly
  684. allocated \c{game_state} structure.
  685. Almost all puzzles should ignore the \c{me} parameter. It is
  686. required by Mines, which needs it for later passing to
  687. \cw{midend_supersede_game_desc()} (see \k{backend-supersede}) once
  688. the user has placed the first click. I fervently hope that no other
  689. puzzle will be awkward enough to require it, so everybody else
  690. should ignore it. As with the \c{interactive} parameter in
  691. \cw{new_desc()} (\k{backend-new-desc}), if you think you have a
  692. reason to need this parameter, please try very hard to think of an
  693. alternative approach!
  694. \H{backend-states} Handling game states
  695. This section describes the functions which create and destroy
  696. \c{game_state} structures.
  697. (Well, except \cw{new_game()}, which is in \k{backend-new-game}
  698. instead of under here; but it deals with game descriptions \e{and}
  699. game states and it had to go in one section or the other.)
  700. \S{backend-dup-game} \cw{dup_game()}
  701. \c game_state *(*dup_game)(const game_state *state);
  702. This function allocates a new \c{game_state} structure and
  703. initialises it with an exact copy of the information in the one
  704. provided as input. It returns a pointer to the new duplicate.
  705. \S{backend-free-game} \cw{free_game()}
  706. \c void (*free_game)(game_state *state);
  707. This function frees a \c{game_state} structure, and any subsidiary
  708. allocations contained within it.
  709. \H{backend-ui} Handling \c{game_ui}
  710. \S{backend-new-ui} \cw{new_ui()}
  711. \c game_ui *(*new_ui)(const game_state *state);
  712. This function allocates and returns a new \c{game_ui} structure for
  713. playing a particular puzzle.
  714. Usually, this function is passed a pointer to the initial
  715. \c{game_state}, in case it needs to refer to that when setting up the
  716. initial values for the new game.
  717. However, if the puzzle defines \c{get_prefs()} and \c{set_prefs()}
  718. functions, then this function may also be called with
  719. \cw{state==NULL}. In this situation it must still allocate a
  720. \c{game_ui} which can be used by \c{get_prefs()} and \c{set_prefs()},
  721. although it need not be usable for actually playing a game.
  722. \S{backend-free-ui} \cw{free_ui()}
  723. \c void (*free_ui)(game_ui *ui);
  724. This function frees a \c{game_ui} structure, and any subsidiary
  725. allocations contained within it.
  726. \S{backend-encode-ui} \cw{encode_ui()}
  727. \c char *(*encode_ui)(const game_ui *ui);
  728. This function encodes any \e{important} data in a \c{game_ui}
  729. structure in printable ASCII string form. It is only called when
  730. saving a half-finished game to a file.
  731. It should be used sparingly. Almost all data in a \c{game_ui} is not
  732. important enough to save. The location of the keyboard-controlled
  733. cursor, for example, can be reset to a default position on reloading
  734. the game without impacting the user experience. If the user should
  735. somehow manage to save a game while a mouse drag was in progress,
  736. then discarding that mouse drag would be an outright \e{feature}.
  737. A typical thing that \e{would} be worth encoding in this function is
  738. the Mines death counter: it's in the \c{game_ui} rather than the
  739. \c{game_state} because it's too important to allow the user to
  740. revert it by using Undo, and therefore it's also too important to
  741. allow the user to revert it by saving and reloading. (Of course, the
  742. user could edit the save file by hand... But if the user is \e{that}
  743. determined to cheat, they could just as easily modify the game's
  744. source.)
  745. The \cw{encode_ui()} function is optional. If a back-end doesn't need
  746. this function it can just set the pointer to \cw{NULL}.
  747. \S{backend-decode-ui} \cw{decode_ui()}
  748. \c void (*decode_ui)(game_ui *ui, const char *encoding,
  749. \c const game_state *state);
  750. This function parses a string previously output by \cw{encode_ui()},
  751. and writes the decoded data back into the freshly-created \c{game_ui}
  752. structure provided. If the string is invalid, the function should do
  753. the best it can, which might just mean not changing the \c{game_ui}
  754. structure at all. This might happen if a save file is corrupted, or
  755. simply from a newer version that encodes more \c{game_ui} data. The
  756. current \c{game_state} is provided in case the function needs to
  757. refer to it for validation.
  758. Like \cw{encode_ui()}, \cw{decode_ui()} is optional. If a back-end
  759. doesn't need this function it can just set the pointer to \cw{NULL}.
  760. \S{backend-changed-state} \cw{changed_state()}
  761. \c void (*changed_state)(game_ui *ui, const game_state *oldstate,
  762. \c const game_state *newstate);
  763. This function is called by the mid-end whenever the current game
  764. state changes, for any reason. Those reasons include:
  765. \b a fresh move being made by \cw{interpret_move()} and
  766. \cw{execute_move()}
  767. \b a solve operation being performed by \cw{solve()} and
  768. \cw{execute_move()}
  769. \b the user moving back and forth along the undo list by means of
  770. the Undo and Redo operations
  771. \b the user selecting Restart to go back to the initial game state.
  772. The job of \cw{changed_state()} is to update the \c{game_ui} for
  773. consistency with the new game state, if any update is necessary. For
  774. example, Same Game stores data about the currently selected tile
  775. group in its \c{game_ui}, and this data is intrinsically related to
  776. the game state it was derived from. So it's very likely to become
  777. invalid when the game state changes; thus, Same Game's
  778. \cw{changed_state()} function clears the current selection whenever
  779. it is called.
  780. When \cw{anim_length()} or \cw{flash_length()} are called, you can
  781. be sure that there has been a previous call to \cw{changed_state()}.
  782. So \cw{changed_state()} can set up data in the \c{game_ui} which will
  783. be read by \cw{anim_length()} and \cw{flash_length()}, and those
  784. functions will not have to worry about being called without the data
  785. having been initialised.
  786. \H{backend-moves} Making moves
  787. This section describes the functions which actually make moves in
  788. the game: that is, the functions which process user input and end up
  789. producing new \c{game_state}s.
  790. \S{backend-interpret-move} \cw{interpret_move()}
  791. \c char *(*interpret_move)(const game_state *state, game_ui *ui,
  792. \c const game_drawstate *ds,
  793. \c int x, int y, int button);
  794. This function receives user input and processes it. Its input
  795. parameters are the current \c{game_state}, the current \c{game_ui}
  796. and the current \c{game_drawstate}, plus details of the input event.
  797. \c{button} is either an ASCII value or a special code (listed below)
  798. indicating an arrow or function key or a mouse event; when
  799. \c{button} is a mouse event, \c{x} and \c{y} contain the pixel
  800. coordinates of the mouse pointer relative to the top left of the
  801. puzzle's drawing area.
  802. (The pointer to the \c{game_drawstate} is marked \c{const}, because
  803. \c{interpret_move} should not write to it. The normal use of that
  804. pointer will be to read the game's tile size parameter in order to
  805. divide mouse coordinates by it.)
  806. \cw{interpret_move()} may return in four different ways:
  807. \b Returning \cw{MOVE_UNUSED} or \cw{MOVE_NO_EFFECT} indicates that no
  808. action whatsoever occurred in response to the input event; the puzzle
  809. was not interested in it at all. The distinction between this is that
  810. \cw{MOVE_NO_EFFECT} implies that the state of the game is what makes
  811. the event uninteresting, while \cw{MOVE_NO_EFFECT} means that the
  812. event is intrinsically uninteresting. For example, a mouse click on
  813. an already-revealed square in Mines might return \cw{MOVE_NO_EFFECT}
  814. while a click outside the board would return \cw{MOVE_UNUSED}.
  815. \b Returning the special value \cw{MOVE_UI_UPDATE} indicates that the input
  816. event has resulted in a change being made to the \c{game_ui} which
  817. will require a redraw of the game window, but that no actual \e{move}
  818. was made (i.e. no new \c{game_state} needs to be created).
  819. \b Returning anything else indicates that a move was made and that a
  820. new \c{game_state} must be created. However, instead of actually
  821. constructing a new \c{game_state} itself, this function is required
  822. to return a printable ASCII string description of the details of the
  823. move. This string will be passed to \cw{execute_move()}
  824. (\k{backend-execute-move}) to actually create the new
  825. \c{game_state}. (Encoding moves as strings in this way means that
  826. the mid-end can keep the strings as well as the game states, and the
  827. strings can be written to disk when saving the game and fed to
  828. \cw{execute_move()} again on reloading.)
  829. The return value from \cw{interpret_move()} is expected to be
  830. dynamically allocated if and only if it is not either \cw{NULL}
  831. \e{or} one of the special string constants \cw{MOVE_UNUSED},
  832. \cw{MOVE_NO_EFFECT}, or \cw{MOVE_UI_UPDATE}.
  833. After this function is called, the back end is permitted to rely on
  834. some subsequent operations happening in sequence:
  835. \b \cw{execute_move()} will be called to convert this move
  836. description into a new \c{game_state}
  837. \b \cw{changed_state()} will be called with the new \c{game_state}.
  838. This means that if \cw{interpret_move()} needs to do updates to the
  839. \c{game_ui} which are easier to perform by referring to the new
  840. \c{game_state}, it can safely leave them to be done in
  841. \cw{changed_state()} and not worry about them failing to happen.
  842. (Note, however, that \cw{execute_move()} may \e{also} be called in
  843. other circumstances. It is only \cw{interpret_move()} which can rely
  844. on a subsequent call to \cw{changed_state()}.)
  845. The special key codes supported by this function are:
  846. \dt \cw{LEFT_BUTTON}, \cw{MIDDLE_BUTTON}, \cw{RIGHT_BUTTON}
  847. \dd Indicate that one of the mouse buttons was pressed down.
  848. \dt \cw{LEFT_DRAG}, \cw{MIDDLE_DRAG}, \cw{RIGHT_DRAG}
  849. \dd Indicate that the mouse was moved while one of the mouse buttons
  850. was still down. The mid-end guarantees that when one of these events
  851. is received, it will always have been preceded by a button-down
  852. event (and possibly other drag events) for the same mouse button,
  853. and no event involving another mouse button will have appeared in
  854. between.
  855. \dt \cw{LEFT_RELEASE}, \cw{MIDDLE_RELEASE}, \cw{RIGHT_RELEASE}
  856. \dd Indicate that a mouse button was released. The mid-end
  857. guarantees that when one of these events is received, it will always
  858. have been preceded by a button-down event (and possibly some drag
  859. events) for the same mouse button, and no event involving another
  860. mouse button will have appeared in between.
  861. \dt \cw{CURSOR_UP}, \cw{CURSOR_DOWN}, \cw{CURSOR_LEFT},
  862. \cw{CURSOR_RIGHT}
  863. \dd Indicate that an arrow key was pressed.
  864. \dt \cw{CURSOR_SELECT}, \cw{CURSOR_SELECT2}
  865. \dd On platforms which have one or two prominent \q{select} button
  866. alongside their cursor keys, indicates that one of those buttons was
  867. pressed. On other platforms, these represent the Enter (or Return)
  868. and Space keys respectively.
  869. In addition, there are some modifiers which can be bitwise-ORed into
  870. the \c{button} parameter:
  871. \dt \cw{MOD_CTRL}, \cw{MOD_SHFT}
  872. \dd These indicate that the Control or Shift key was pressed
  873. alongside the key. They only apply to the cursor keys, not to mouse
  874. buttons or anything else.
  875. \dt \cw{MOD_NUM_KEYPAD}
  876. \dd This applies to some ASCII values, and indicates that the key
  877. code was input via the numeric keypad rather than the main keyboard.
  878. Some puzzles may wish to treat this differently (for example, a
  879. puzzle might want to use the numeric keypad as an eight-way
  880. directional pad), whereas others might not (a game involving numeric
  881. input probably just wants to treat the numeric keypad as numbers).
  882. \dt \cw{MOD_MASK}
  883. \dd This mask is the bitwise OR of all the available modifiers; you
  884. can bitwise-AND with \cw{~MOD_MASK} to strip all the modifiers off
  885. any input value.
  886. \S{backend-execute-move} \cw{execute_move()}
  887. \c game_state *(*execute_move)(const game_state *state, char *move);
  888. This function takes an input \c{game_state} and a move string as
  889. output from \cw{interpret_move()}. It returns a newly allocated
  890. \c{game_state} which contains the result of applying the specified
  891. move to the input game state.
  892. This function may return \cw{NULL} if it cannot parse the move
  893. string (and this is definitely preferable to crashing or failing an
  894. assertion, since one way this can happen is if loading a corrupt
  895. save file). However, it must not return \cw{NULL} for any move
  896. string that really was output from \cw{interpret_move()}: this is
  897. punishable by assertion failure in the mid-end.
  898. \S{backend-can-solve} \c{can_solve}
  899. \c bool can_solve;
  900. This field is set to \cw{true} if the game's \cw{solve()} function
  901. does something. If it's set to \cw{false}, the game will not even
  902. offer the \q{Solve} menu option.
  903. \S{backend-solve} \cw{solve()}
  904. \c char *(*solve)(const game_state *orig, const game_state *curr,
  905. \c const char *aux, const char **error);
  906. This function is called when the user selects the \q{Solve} option
  907. from the menu. If \cw{can_solve} is \cw{false} then it will never
  908. be called and can be \cw{NULL}.
  909. It is passed two input game states: \c{orig} is the game state from
  910. the very start of the puzzle, and \c{curr} is the current one.
  911. (Different games find one or other or both of these convenient.) It
  912. is also passed the \c{aux} string saved by \cw{new_desc()}
  913. (\k{backend-new-desc}), in case that encodes important information
  914. needed to provide the solution.
  915. If this function is unable to produce a solution (perhaps, for
  916. example, the game has no in-built solver so it can only solve
  917. puzzles it invented internally and has an \c{aux} string for) then
  918. it may return \cw{NULL}. If it does this, it must also set
  919. \c{*error} to an error message to be presented to the user (such as
  920. \q{Solution not known for this puzzle}); that error message is not
  921. expected to be dynamically allocated.
  922. If this function \e{does} produce a solution, it returns a printable
  923. ASCII move string suitable for feeding to \cw{execute_move()}
  924. (\k{backend-execute-move}). Like a (non-empty) string returned from
  925. \cw{interpret_move()}, the returned string should be dynamically
  926. allocated.
  927. \H{backend-drawing} Drawing the game graphics
  928. This section discusses the back end functions that deal with
  929. drawing.
  930. \S{backend-new-drawstate} \cw{new_drawstate()}
  931. \c game_drawstate *(*new_drawstate)(drawing *dr,
  932. \c const game_state *state);
  933. This function allocates and returns a new \c{game_drawstate}
  934. structure for drawing a particular puzzle. It is passed a pointer to
  935. a \c{game_state}, in case it needs to refer to that when setting up
  936. any initial data.
  937. This function may not rely on the puzzle having been newly started;
  938. a new draw state can be constructed at any time if the front end
  939. requests a forced redraw. For games like Pattern, in which initial
  940. game states are much simpler than general ones, this might be
  941. important to keep in mind.
  942. The parameter \c{dr} is a drawing object (see \k{drawing}) which the
  943. function might need to use to allocate blitters. (However, this
  944. isn't recommended; it's usually more sensible to wait to allocate a
  945. blitter until \cw{set_size()} is called, because that way you can
  946. tailor it to the scale at which the puzzle is being drawn.)
  947. \S{backend-free-drawstate} \cw{free_drawstate()}
  948. \c void (*free_drawstate)(drawing *dr, game_drawstate *ds);
  949. This function frees a \c{game_drawstate} structure, and any
  950. subsidiary allocations contained within it.
  951. The parameter \c{dr} is a drawing object (see \k{drawing}), which
  952. might be required if you are freeing a blitter.
  953. \S{backend-preferred-tilesize} \c{preferred_tilesize}
  954. \c int preferred_tilesize;
  955. Each game is required to define a single integer parameter which
  956. expresses, in some sense, the scale at which it is drawn. This is
  957. described in the APIs as \cq{tilesize}, since most puzzles are on a
  958. square (or possibly triangular or hexagonal) grid and hence a
  959. sensible interpretation of this parameter is to define it as the
  960. size of one grid tile in pixels; however, there's no actual
  961. requirement that the \q{tile size} be proportional to the game
  962. window size. Window size is required to increase monotonically with
  963. \q{tile size}, however.
  964. The data element \c{preferred_tilesize} indicates the tile size which
  965. should be used in the absence of a good reason to do otherwise (such
  966. as the screen being too small to fit the whole puzzle, or the user
  967. explicitly requesting a resize).
  968. \S{backend-compute-size} \cw{compute_size()}
  969. \c void (*compute_size)(const game_params *params, int tilesize,
  970. \c const game_ui *ui, int *x, int *y);
  971. This function is passed a \c{game_params} structure and a tile size.
  972. It returns, in \c{*x} and \c{*y}, the size in pixels of the drawing
  973. area that would be required to render a puzzle with those parameters
  974. at that tile size.
  975. \S{backend-set-size} \cw{set_size()}
  976. \c void (*set_size)(drawing *dr, game_drawstate *ds,
  977. \c const game_params *params, int tilesize);
  978. This function is responsible for setting up a \c{game_drawstate} to
  979. draw at a given tile size. Typically this will simply involve
  980. copying the supplied \c{tilesize} parameter into a \c{tilesize}
  981. field inside the draw state; for some more complex games it might
  982. also involve setting up other dimension fields, or possibly
  983. allocating a blitter (see \k{drawing-blitter}).
  984. The parameter \c{dr} is a drawing object (see \k{drawing}), which is
  985. required if a blitter needs to be allocated.
  986. Back ends may assume (and may enforce by assertion) that this
  987. function will be called at most once for any \c{game_drawstate}. If
  988. a puzzle needs to be redrawn at a different size, the mid-end will
  989. create a fresh drawstate.
  990. \S{backend-colours} \cw{colours()}
  991. \c float *(*colours)(frontend *fe, int *ncolours);
  992. This function is responsible for telling the front end what colours
  993. the puzzle will need to draw itself.
  994. It returns the number of colours required in \c{*ncolours}, and the
  995. return value from the function itself is a dynamically allocated
  996. array of three times that many \c{float}s, containing the red, green
  997. and blue components of each colour respectively as numbers in the
  998. range [0,1].
  999. The second parameter passed to this function is a front end handle.
  1000. The only things it is permitted to do with this handle are to call
  1001. the front-end function called \cw{frontend_default_colour()} (see
  1002. \k{frontend-default-colour}) or the utility function called
  1003. \cw{game_mkhighlight()} (see \k{utils-game-mkhighlight}). (The
  1004. latter is a wrapper on the former, so front end implementors only
  1005. need to provide \cw{frontend_default_colour()}.) This allows
  1006. \cw{colours()} to take local configuration into account when
  1007. deciding on its own colour allocations. Most games use the front
  1008. end's default colour as their background, apart from a few which
  1009. depend on drawing relief highlights so they adjust the background
  1010. colour if it's too light for highlights to show up against it.
  1011. The first colour in the list is slightly special. The mid-end fills
  1012. the drawing area with it before the first call to \cw{redraw()} (see
  1013. \k{backend-redraw}). Some front ends also use it fill the part of the
  1014. puzzle window outside the puzzle. This means that it is usually
  1015. sensible to make colour 0 the background colour for the puzzle.
  1016. Note that the colours returned from this function are for
  1017. \e{drawing}, not for printing. Printing has an entirely different
  1018. colour allocation policy.
  1019. \S{backend-anim-length} \cw{anim_length()}
  1020. \c float (*anim_length)(const game_state *oldstate,
  1021. \c const game_state *newstate,
  1022. \c int dir, game_ui *ui);
  1023. This function is called when a move is made, undone or redone. It is
  1024. given the old and the new \c{game_state}, and its job is to decide
  1025. whether the transition between the two needs to be animated or can
  1026. be instant.
  1027. \c{oldstate} is the state that was current until this call;
  1028. \c{newstate} is the state that will be current after it. \c{dir}
  1029. specifies the chronological order of those states: if it is
  1030. positive, then the transition is the result of a move or a redo (and
  1031. so \c{newstate} is the later of the two moves), whereas if it is
  1032. negative then the transition is the result of an undo (so that
  1033. \c{newstate} is the \e{earlier} move).
  1034. If this function decides the transition should be animated, it
  1035. returns the desired length of the animation in seconds. If not, it
  1036. returns zero.
  1037. State changes as a result of a Restart operation are never animated;
  1038. the mid-end will handle them internally and never consult this
  1039. function at all. State changes as a result of Solve operations are
  1040. also not animated by default, although you can change this for a
  1041. particular game by setting a flag in \c{flags} (\k{backend-flags}).
  1042. The function is also passed a pointer to the local \c{game_ui}. It
  1043. may refer to information in here to help with its decision (see
  1044. \k{writing-conditional-anim} for an example of this), and/or it may
  1045. \e{write} information about the nature of the animation which will
  1046. be read later by \cw{redraw()}.
  1047. When this function is called, it may rely on \cw{changed_state()}
  1048. having been called previously, so if \cw{anim_length()} needs to
  1049. refer to information in the \c{game_ui}, then \cw{changed_state()}
  1050. is a reliable place to have set that information up.
  1051. Move animations do not inhibit further input events. If the user
  1052. continues playing before a move animation is complete, the animation
  1053. will be abandoned and the display will jump straight to the final
  1054. state.
  1055. \S{backend-flash-length} \cw{flash_length()}
  1056. \c float (*flash_length)(const game_state *oldstate,
  1057. \c const game_state *newstate,
  1058. \c int dir, game_ui *ui);
  1059. This function is called when a move is completed. (\q{Completed}
  1060. means that not only has the move been made, but any animation which
  1061. accompanied it has finished.) It decides whether the transition from
  1062. \c{oldstate} to \c{newstate} merits a \q{flash}.
  1063. A flash is much like a move animation, but it is \e{not} interrupted
  1064. by further user interface activity; it runs to completion in
  1065. parallel with whatever else might be going on on the display. The
  1066. only thing which will rush a flash to completion is another flash.
  1067. The purpose of flashes is to indicate that the game has been
  1068. completed. They were introduced as a separate concept from move
  1069. animations because of Net: the habit of most Net players (and
  1070. certainly me) is to rotate a tile into place and immediately lock
  1071. it, then move on to another tile. When you make your last move, at
  1072. the instant the final tile is rotated into place the screen starts
  1073. to flash to indicate victory \dash but if you then press the lock
  1074. button out of habit, then the move animation is cancelled, and the
  1075. victory flash does not complete. (And if you \e{don't} press the
  1076. lock button, the completed grid will look untidy because there will
  1077. be one unlocked square.) Therefore, I introduced a specific concept
  1078. of a \q{flash} which is separate from a move animation and can
  1079. proceed in parallel with move animations and any other display
  1080. activity, so that the victory flash in Net is not cancelled by that
  1081. final locking move.
  1082. The input parameters to \cw{flash_length()} are exactly the same as
  1083. the ones to \cw{anim_length()}: see \k{backend-anim-length}.
  1084. Just like \cw{anim_length()}, when this function is called, it may
  1085. rely on \cw{changed_state()} having been called previously, so if it
  1086. needs to refer to information in the \c{game_ui} then
  1087. \cw{changed_state()} is a reliable place to have set that
  1088. information up.
  1089. (Some games use flashes to indicate defeat as well as victory;
  1090. Mines, for example, flashes in a different colour when you tread on
  1091. a mine from the colour it uses when you complete the game. In order
  1092. to achieve this, its \cw{flash_length()} function has to store a
  1093. flag in the \c{game_ui} to indicate which flash type is required.)
  1094. \S{backend-get-cursor-location} \cw{get_cursor_location()}
  1095. \c void (*get_cursor_location)(const game_ui *ui,
  1096. \c const game_drawstate *ds,
  1097. \c const game_state *state,
  1098. \c const game_params *params,
  1099. \c int *x, int *y,
  1100. \c int *w, int *h);
  1101. This function queries the backend for the rectangular region
  1102. containing the cursor (in games that have one), or other region of
  1103. interest.
  1104. This function is called by only
  1105. \cw{midend_get_cursor_location()} (\k{midend-get-cursor-location}). Its
  1106. purpose is to allow front ends to query the location of the backend's
  1107. cursor. With knowledge of this location, a front end can, for example,
  1108. ensure that the region of interest remains visible if the puzzle is
  1109. too big to fit on the screen at once.
  1110. On returning, \cw{*x}, \cw{*y} should be set to the X and Y
  1111. coordinates of the upper-left corner of the rectangular region of
  1112. interest, and \cw{*w} and \cw{*h} should be the width and height of
  1113. that region, respectively. In the event that a cursor is not visible
  1114. on screen, this function should return and leave the return parameters
  1115. untouched \dash the midend will notice this. The backend need not
  1116. bother checking that \cw{x}, \cw{y}, \cw{w} and \cw{h} are
  1117. non-\cw{NULL} \dash the midend guarantees that they will not be.
  1118. Defining what constitutes a \q{region of interest} is left up to the
  1119. backend. If a game provides a conventional cursor \dash such as Mines,
  1120. Solo, or any of the other grid-based games \dash the most logical
  1121. choice is of course the location of the cursor itself. However, in
  1122. other cases such as Cube or Inertia, there is no \q{cursor} in the
  1123. conventional sense \dash the player instead controls an object moving
  1124. around the screen. In these cases, it makes sense to define the region
  1125. of interest as the bounding box of the player object or another
  1126. sensible region \dash such as the grid square the player is sitting on
  1127. in Cube.
  1128. If a backend does not provide a cursor mechanism at all, the backend
  1129. is free to provide an empty implementation of this function, or a
  1130. \cw{NULL} pointer in the \cw{game} structure \dash the midend will
  1131. notice either of these cases and behave appropriately.
  1132. \S{backend-status} \cw{status()}
  1133. \c int (*status)(const game_state *state);
  1134. This function returns a status value indicating whether the current
  1135. game is still in play, or has been won, or has been conclusively lost.
  1136. The mid-end uses this to implement \cw{midend_status()}
  1137. (\k{midend-status}).
  1138. The return value should be +1 if the game has been successfully
  1139. solved. If the game has been lost in a situation where further play is
  1140. unlikely, the return value should be -1. If neither is true (so play
  1141. is still ongoing), return zero.
  1142. Front ends may wish to use a non-zero status as a cue to proactively
  1143. offer the option of starting a new game. Therefore, back ends should
  1144. not return -1 if the game has been \e{technically} lost but undoing
  1145. and continuing is still a realistic possibility.
  1146. (For instance, games with hidden information such as Guess or Mines
  1147. might well return a non-zero status whenever they reveal the solution,
  1148. whether or not the player guessed it correctly, on the grounds that a
  1149. player would be unlikely to hide the solution and continue playing
  1150. after the answer was spoiled. On the other hand, games where you can
  1151. merely get into a dead end such as Same Game or Inertia might choose
  1152. to return 0 in that situation, on the grounds that the player would
  1153. quite likely press Undo and carry on playing.)
  1154. \S{backend-redraw} \cw{redraw()}
  1155. \c void (*redraw)(drawing *dr, game_drawstate *ds,
  1156. \c const game_state *oldstate,
  1157. \c const game_state *newstate,
  1158. \c int dir, const game_ui *ui,
  1159. \c float anim_time, float flash_time);
  1160. This function is responsible for actually drawing the contents of
  1161. the game window, and for redrawing every time the game state or the
  1162. \c{game_ui} changes.
  1163. The parameter \c{dr} is a drawing object which may be passed to the
  1164. drawing API functions (see \k{drawing} for documentation of the
  1165. drawing API). This function may not save \c{dr} and use it
  1166. elsewhere; it must only use it for calling back to the drawing API
  1167. functions within its own lifetime.
  1168. \c{ds} is the local \c{game_drawstate}, of course, and \c{ui} is the
  1169. local \c{game_ui}.
  1170. \c{newstate} is the semantically-current game state, and is always
  1171. non-\cw{NULL}. If \c{oldstate} is also non-\cw{NULL}, it means that
  1172. a move has recently been made and the game is still in the process
  1173. of displaying an animation linking the old and new states; in this
  1174. situation, \c{anim_time} will give the length of time (in seconds)
  1175. that the animation has already been running. If \c{oldstate} is
  1176. \cw{NULL}, then \c{anim_time} is unused (and will hopefully be set
  1177. to zero to avoid confusion).
  1178. \c{dir} specifies the chronological order of those states: if it is
  1179. positive, then the transition is the result of a move or a redo (and
  1180. so \c{newstate} is the later of the two moves), whereas if it is
  1181. negative then the transition is the result of an undo (so that
  1182. \c{newstate} is the \e{earlier} move). This allows move animations
  1183. that are not time-symmetric (such as Inertia, where gems are consumed
  1184. during the animation) to be drawn the right way round.
  1185. \c{flash_time}, if it is is non-zero, denotes that the game is in
  1186. the middle of a flash, and gives the time since the start of the
  1187. flash. See \k{backend-flash-length} for general discussion of
  1188. flashes.
  1189. The very first time this function is called for a new
  1190. \c{game_drawstate}, it is expected to redraw the \e{entire} drawing
  1191. area. Since this often involves drawing visual furniture which is
  1192. never subsequently altered, it is often simplest to arrange this by
  1193. having a special \q{first time} flag in the draw state, and
  1194. resetting it after the first redraw. This function can assume that
  1195. the mid-end has filled the drawing area with colour 0 before the first
  1196. call.
  1197. When this function (or any subfunction) calls the drawing API, it is
  1198. expected to pass colour indices which were previously defined by the
  1199. \cw{colours()} function.
  1200. \H{backend-printing} Printing functions
  1201. This section discusses the back end functions that deal with
  1202. printing puzzles out on paper.
  1203. \S{backend-can-print} \c{can_print}
  1204. \c bool can_print;
  1205. This flag is set to \cw{true} if the puzzle is capable of printing
  1206. itself on paper. (This makes sense for some puzzles, such as Solo,
  1207. which can be filled in with a pencil. Other puzzles, such as
  1208. Twiddle, inherently involve moving things around and so would not
  1209. make sense to print.)
  1210. If this flag is \cw{false}, then the functions \cw{print_size()}
  1211. and \cw{print()} will never be called and can be \cw{NULL}.
  1212. \S{backend-can-print-in-colour} \c{can_print_in_colour}
  1213. \c bool can_print_in_colour;
  1214. This flag is set to \cw{true} if the puzzle is capable of printing
  1215. itself differently when colour is available. For example, Map can
  1216. actually print coloured regions in different \e{colours} rather than
  1217. resorting to cross-hatching.
  1218. If the \c{can_print} flag is \cw{false}, then this flag will be
  1219. ignored.
  1220. \S{backend-print-size} \cw{print_size()}
  1221. \c void (*print_size)(const game_params *params, const game_ui *ui,
  1222. \c float *x, float *y);
  1223. This function is passed a \c{game_params} structure and a tile size.
  1224. It returns, in \c{*x} and \c{*y}, the preferred size in
  1225. \e{millimetres} of that puzzle if it were to be printed out on paper.
  1226. If the \c{can_print} flag is \cw{false}, this function will never be
  1227. called.
  1228. \S{backend-print} \cw{print()}
  1229. \c void (*print)(drawing *dr, const game_state *state,
  1230. \c const game_ui *ui, int tilesize);
  1231. This function is called when a puzzle is to be printed out on paper.
  1232. It should use the drawing API functions (see \k{drawing}) to print
  1233. itself.
  1234. This function is separate from \cw{redraw()} because it is often
  1235. very different:
  1236. \b The printing function may not depend on pixel accuracy, since
  1237. printer resolution is variable. Draw as if your canvas had infinite
  1238. resolution.
  1239. \b The printing function sometimes needs to display things in a
  1240. completely different style. Net, for example, is very different as
  1241. an on-screen puzzle and as a printed one.
  1242. \b The printing function is often much simpler since it has no need
  1243. to deal with repeated partial redraws.
  1244. However, there's no reason the printing and redraw functions can't
  1245. share some code if they want to.
  1246. When this function (or any subfunction) calls the drawing API, the
  1247. colour indices it passes should be colours which have been allocated
  1248. by the \cw{print_*_colour()} functions within this execution of
  1249. \cw{print()}. This is very different from the fixed small number of
  1250. colours used in \cw{redraw()}, because printers do not have a
  1251. limitation on the total number of colours that may be used. Some
  1252. puzzles' printing functions might wish to allocate only one \q{ink}
  1253. colour and use it for all drawing; others might wish to allocate
  1254. \e{more} colours than are used on screen.
  1255. One possible colour policy worth mentioning specifically is that a
  1256. puzzle's printing function might want to allocate the \e{same}
  1257. colour indices as are used by the redraw function, so that code
  1258. shared between drawing and printing does not have to keep switching
  1259. its colour indices. In order to do this, the simplest thing is to
  1260. make use of the fact that colour indices returned from
  1261. \cw{print_*_colour()} are guaranteed to be in increasing order from
  1262. zero. So if you have declared an \c{enum} defining three colours
  1263. \cw{COL_BACKGROUND}, \cw{COL_THIS} and \cw{COL_THAT}, you might then
  1264. write
  1265. \c int c;
  1266. \c c = print_mono_colour(dr, 1); assert(c == COL_BACKGROUND);
  1267. \c c = print_mono_colour(dr, 0); assert(c == COL_THIS);
  1268. \c c = print_mono_colour(dr, 0); assert(c == COL_THAT);
  1269. If the \c{can_print} flag is \cw{false}, this function will never be
  1270. called.
  1271. \H{backend-misc} Miscellaneous
  1272. \S{backend-can-format-as-text-ever} \c{can_format_as_text_ever}
  1273. \c bool can_format_as_text_ever;
  1274. This field is \cw{true} if the game supports formatting a
  1275. game state as ASCII text (typically ASCII art) for copying to the
  1276. clipboard and pasting into other applications. If it is \cw{false},
  1277. front ends will not offer the \q{Copy} command at all.
  1278. If this field is \cw{true}, the game does not necessarily have to
  1279. support text formatting for \e{all} games: e.g. a game which can be
  1280. played on a square grid or a triangular one might only support copy
  1281. and paste for the former, because triangular grids in ASCII art are
  1282. just too difficult.
  1283. If this field is \cw{false}, the functions
  1284. \cw{can_format_as_text_now()} (\k{backend-can-format-as-text-now})
  1285. and \cw{text_format()} (\k{backend-text-format}) are never called
  1286. and can be \cw{NULL}.
  1287. \S{backend-can-format-as-text-now} \c{can_format_as_text_now()}
  1288. \c bool (*can_format_as_text_now)(const game_params *params);
  1289. This function is passed a \c{game_params}, and returns \cw{true} if
  1290. the game can support ASCII text output for this particular game type.
  1291. If it returns \cw{false}, front ends will grey out or otherwise
  1292. disable the \q{Copy} command.
  1293. Games may enable and disable the copy-and-paste function for
  1294. different game \e{parameters}, but are currently constrained to
  1295. return the same answer from this function for all game \e{states}
  1296. sharing the same parameters. In other words, the \q{Copy} function
  1297. may enable or disable itself when the player changes game preset,
  1298. but will never change during play of a single game or when another
  1299. game of exactly the same type is generated.
  1300. This function should not take into account aspects of the game
  1301. parameters which are not encoded by \cw{encode_params()}
  1302. (\k{backend-encode-params}) when the \c{full} parameter is set to
  1303. \cw{false}. Such parameters will not necessarily match up between a
  1304. call to this function and a subsequent call to \cw{text_format()}
  1305. itself. (For instance, game \e{difficulty} should not affect whether
  1306. the game can be copied to the clipboard. Only the actual visible
  1307. \e{shape} of the game can affect that.)
  1308. \S{backend-text-format} \cw{text_format()}
  1309. \c char *(*text_format)(const game_state *state);
  1310. This function is passed a \c{game_state}, and returns a newly
  1311. allocated C string containing an ASCII representation of that game
  1312. state. It is used to implement the \q{Copy} operation in many front
  1313. ends.
  1314. This function will only ever be called if the back end field
  1315. \c{can_format_as_text_ever} (\k{backend-can-format-as-text-ever}) is
  1316. \cw{true} \e{and} the function \cw{can_format_as_text_now()}
  1317. (\k{backend-can-format-as-text-now}) has returned \cw{true} for the
  1318. currently selected game parameters.
  1319. The returned string may contain line endings (and will probably want
  1320. to), using the normal C internal \cq{\\n} convention. For
  1321. consistency between puzzles, all multi-line textual puzzle
  1322. representations should \e{end} with a newline as well as containing
  1323. them internally. (There are currently no puzzles which have a
  1324. one-line ASCII representation, so there's no precedent yet for
  1325. whether that should come with a newline or not.)
  1326. \S{backend-wants-statusbar} \cw{wants_statusbar}
  1327. \c bool wants_statusbar;
  1328. This field is set to \cw{true} if the puzzle has a use for a textual
  1329. status line (to display score, completion status, currently active
  1330. tiles, etc). If the \c{redraw()} function ever intends to call
  1331. \c{status_bar()} in the drawing API (\k{drawing-status-bar}), then it
  1332. should set this flag to \c{true}.
  1333. \S{backend-is-timed} \c{is_timed}
  1334. \c bool is_timed;
  1335. This field is \cw{true} if the puzzle is time-critical. If
  1336. so, the mid-end will maintain a game timer while the user plays.
  1337. If this field is \cw{false}, then \cw{timing_state()} will never be
  1338. called and can be \cw{NULL}.
  1339. \S{backend-timing-state} \cw{timing_state()}
  1340. \c bool (*timing_state)(const game_state *state, game_ui *ui);
  1341. This function is passed the current \c{game_state} and the local
  1342. \c{game_ui}; it returns \cw{true} if the game timer should currently
  1343. be running.
  1344. A typical use for the \c{game_ui} in this function is to note when
  1345. the game was first completed (by setting a flag in
  1346. \cw{changed_state()} \dash see \k{backend-changed-state}), and
  1347. freeze the timer thereafter so that the user can undo back through
  1348. their solution process without altering their time.
  1349. \S{backend-request-keys} \cw{request_keys()}
  1350. \c key_label *(*request_keys)(const game_params *params, int *nkeys);
  1351. This function returns a dynamically allocated array of \cw{key_label}
  1352. items containing the buttons the back end deems absolutely
  1353. \e{necessary} for gameplay, not an exhaustive list of every button the
  1354. back end could accept. For example, Keen only returns the digits up to
  1355. the game size and the backspace character, \cw{\\b}, even though it
  1356. \e{could} accept \cw{M}, as only these buttons are actually needed to
  1357. play the game. Each \cw{key_label} item contains the following fields:
  1358. \c struct key_label {
  1359. \c char *label; /* label for frontend use */
  1360. \c int button; /* button to pass to midend */
  1361. \c } key_label;
  1362. The \cw{label} field of this structure can (and often will) be set by
  1363. the backend to \cw{NULL}, in which case the midend will instead call
  1364. \c{button2label()} (\k{utils-button2label}) and fill in a generic
  1365. label. The \cw{button} field is the associated code that can be passed
  1366. to the midend when the frontend deems appropriate.
  1367. If \cw{label} is not \cw{NULL}, then it's a dynamically allocated
  1368. string. Therefore, freeing an array of these structures needs more
  1369. than just a single free operatio. The function \c{free_keys()}
  1370. (\k{utils-free-keys}) can be used to free a whole array of these
  1371. structures conveniently.
  1372. The backend should set \cw{*nkeys} to the number of elements in the
  1373. returned array.
  1374. The field for this function point in the \cw{game} structure might be
  1375. set to \cw{NULL} (and indeed it is for the majority of the games) to
  1376. indicate that no additional buttons (apart from the cursor keys) are
  1377. required to play the game.
  1378. This function should not be called directly by frontends. Instead,
  1379. frontends should use \cw{midend_request_keys()}
  1380. (\k{midend-request-keys}).
  1381. \S{backend-current-key-label} \cw{current_key_label()}
  1382. \c const char *(*current_key_label)(const game_ui *ui,
  1383. \c const game_state *state,
  1384. \c int button);
  1385. This function is called to ask the back-end how certain keys should be
  1386. labelled on platforms (such a feature phones) where this is
  1387. conventional.
  1388. These labels are expected to reflect what the keys will do right now,
  1389. so they can change depending on the game and UI state.
  1390. The \c{ui} and \c{state} arguments describe the state of the game for
  1391. which key labels are required.
  1392. The \c{button} argument is the same as the one passed to
  1393. \cw{interpret_move()}.
  1394. At present, the only values of \c{button} that can be passed to
  1395. \cw{current_key_label()} are \cw{CURSOR_SELECT} and \cw{CURSOR_SELECT2}.
  1396. The return value is a short string describing what the requested key
  1397. will do if pressed.
  1398. Usually the string should be a static string constant.
  1399. If it's really necessary to use a dynamically-allocated string, it
  1400. should remain valid until the next call to \cw{current_key_label()} or
  1401. \cw{free_ui()} with the same \cw{game_ui} (so it can be referenced from
  1402. the \cw{game_ui} and freed at the next one of those calls).
  1403. There's no fixed upper limit on the length of string that this
  1404. function can return, but more than about 12 characters is likely to
  1405. cause problems for front-ends. If two buttons have the same effect,
  1406. their labels should be identical so that the front end can detect
  1407. this. Similarly, keys that do different things should have different
  1408. labels. The label should be an empty string (\cw{""}) if the key does
  1409. nothing.
  1410. Like \cw{request_keys()}, the \cw{current_key_label} pointer in the
  1411. \c{game} structure is allowed to be \cw{NULL}, in which case the
  1412. mid-end will treat it as though it always returned \cw{""}.
  1413. \S{backend-flags} \c{flags}
  1414. \c int flags;
  1415. This field contains miscellaneous per-backend flags. It consists of
  1416. the bitwise OR of some combination of the following:
  1417. \dt \cw{BUTTON_BEATS(x,y)}
  1418. \dd Given any \cw{x} and \cw{y} from the set \{\cw{LEFT_BUTTON},
  1419. \cw{MIDDLE_BUTTON}, \cw{RIGHT_BUTTON}\}, this macro evaluates to a
  1420. bit flag which indicates that when buttons \cw{x} and \cw{y} are
  1421. both pressed simultaneously, the mid-end should consider \cw{x} to
  1422. have priority. (In the absence of any such flags, the mid-end will
  1423. always consider the most recently pressed button to have priority.)
  1424. \dt \cw{SOLVE_ANIMATES}
  1425. \dd This flag indicates that moves generated by \cw{solve()}
  1426. (\k{backend-solve}) are candidates for animation just like any other
  1427. move. For most games, solve moves should not be animated, so the
  1428. mid-end doesn't even bother calling \cw{anim_length()}
  1429. (\k{backend-anim-length}), thus saving some special-case code in
  1430. each game. On the rare occasion that animated solve moves are
  1431. actually required, you can set this flag.
  1432. \dt \cw{REQUIRE_RBUTTON}
  1433. \dd This flag indicates that the puzzle cannot be usefully played
  1434. without the use of mouse buttons other than the left one. On some
  1435. PDA platforms, this flag is used by the front end to enable
  1436. right-button emulation through an appropriate gesture. Note that a
  1437. puzzle is not required to set this just because it \e{uses} the
  1438. right button, but only if its use of the right button is critical to
  1439. playing the game. (Slant, for example, uses the right button to
  1440. cycle through the three square states in the opposite order from the
  1441. left button, and hence can manage fine without it.)
  1442. \dt \cw{REQUIRE_NUMPAD}
  1443. \dd This flag indicates that the puzzle cannot be usefully played
  1444. without the use of number-key input. On some PDA platforms it causes
  1445. an emulated number pad to appear on the screen. Similarly to
  1446. \cw{REQUIRE_RBUTTON}, a puzzle need not specify this simply if its
  1447. use of the number keys is not critical.
  1448. \H{backend-initiative} Things a back end may do on its own initiative
  1449. This section describes a couple of things that a back end may choose
  1450. to do by calling functions elsewhere in the program, which would not
  1451. otherwise be obvious.
  1452. \S{backend-newrs} Create a random state
  1453. If a back end needs random numbers at some point during normal play,
  1454. it can create a fresh \c{random_state} by first calling
  1455. \c{get_random_seed} (\k{frontend-get-random-seed}) and then passing
  1456. the returned seed data to \cw{random_new()}.
  1457. This is likely not to be what you want. If a puzzle needs randomness
  1458. in the middle of play, it's likely to be more sensible to store some
  1459. sort of random state within the \c{game_state}, so that the random
  1460. numbers are tied to the particular game state and hence the player
  1461. can't simply keep undoing their move until they get numbers they
  1462. like better.
  1463. This facility is currently used only in Net, to implement the
  1464. \q{jumble} command, which sets every unlocked tile to a new random
  1465. orientation. This randomness \e{is} a reasonable use of the feature,
  1466. because it's non-adversarial \dash there's no advantage to the user
  1467. in getting different random numbers.
  1468. \S{backend-supersede} Supersede its own game description
  1469. In response to a move, a back end is (reluctantly) permitted to call
  1470. \cw{midend_supersede_game_desc()}:
  1471. \c void midend_supersede_game_desc(midend *me,
  1472. \c char *desc, char *privdesc);
  1473. When the user selects \q{New Game}, the mid-end calls
  1474. \cw{new_desc()} (\k{backend-new-desc}) to get a new game
  1475. description, and (as well as using that to generate an initial game
  1476. state) stores it for the save file and for telling to the user. The
  1477. function above overwrites that game description, and also splits it
  1478. in two. \c{desc} becomes the new game description which is provided
  1479. to the user on request, and is also the one used to construct a new
  1480. initial game state if the user selects \q{Restart}. \c{privdesc} is
  1481. a \q{private} game description, used to reconstruct the game's
  1482. initial state when reloading.
  1483. The distinction between the two, as well as the need for this
  1484. function at all, comes from Mines. Mines begins with a blank grid
  1485. and no idea of where the mines actually are; \cw{new_desc()} does
  1486. almost no work in interactive mode, and simply returns a string
  1487. encoding the \c{random_state}. When the user first clicks to open a
  1488. tile, \e{then} Mines generates the mine positions, in such a way
  1489. that the game is soluble from that starting point. Then it uses this
  1490. function to supersede the random-state game description with a
  1491. proper one. But it needs two: one containing the initial click
  1492. location (because that's what you want to happen if you restart the
  1493. game, and also what you want to send to a friend so that they play
  1494. \e{the same game} as you), and one without the initial click
  1495. location (because when you save and reload the game, you expect to
  1496. see the same blank initial state as you had before saving).
  1497. I should stress again that this function is a horrid hack. Nobody
  1498. should use it if they're not Mines; if you think you need to use it,
  1499. think again repeatedly in the hope of finding a better way to do
  1500. whatever it was you needed to do.
  1501. \C{drawing} The drawing API
  1502. The back end function \cw{redraw()} (\k{backend-redraw}) is required
  1503. to draw the puzzle's graphics on the window's drawing area. The back
  1504. end function \cw{print()} similarly draws the puzzle on paper, if the
  1505. puzzle is printable. To do this portably, the back end is provided
  1506. with a drawing API allowing it to talk directly to the front end. In
  1507. this chapter I document that API, both for the benefit of back end
  1508. authors trying to use it and for front end authors trying to implement
  1509. it.
  1510. The drawing API as seen by the back end is a collection of global
  1511. functions, each of which takes a pointer to a \c{drawing} structure
  1512. (a \q{drawing object}). These objects are supplied as parameters to
  1513. the back end's \cw{redraw()} and \cw{print()} functions.
  1514. In fact these global functions are not implemented directly by the
  1515. front end; instead, they are implemented centrally in \c{drawing.c}
  1516. and form a small piece of middleware. The drawing API as supplied by
  1517. the front end is a structure containing a set of function pointers,
  1518. plus a \cq{void *} handle which is passed to each of those
  1519. functions. This enables a single front end to switch between
  1520. multiple implementations of the drawing API if necessary. For
  1521. example, the Windows API supplies a printing mechanism integrated
  1522. into the same GDI which deals with drawing in windows, and therefore
  1523. the same API implementation can handle both drawing and printing;
  1524. but on Unix, the most common way for applications to print is by
  1525. producing PostScript output directly, and although it would be
  1526. \e{possible} to write a single (say) \cw{draw_rect()} function which
  1527. checked a global flag to decide whether to do GTK drawing operations
  1528. or output PostScript to a file, it's much nicer to have two separate
  1529. functions and switch between them as appropriate.
  1530. When drawing, the puzzle window is indexed by pixel coordinates,
  1531. with the top left pixel defined as \cw{(0,0)} and the bottom right
  1532. pixel \cw{(w-1,h-1)}, where \c{w} and \c{h} are the width and height
  1533. values returned by the back end function \cw{compute_size()}
  1534. (\k{backend-compute-size}).
  1535. When printing, the puzzle's print area is indexed in exactly the
  1536. same way (with an arbitrary tile size provided by the printing
  1537. module \c{printing.c}), to facilitate sharing of code between the
  1538. drawing and printing routines. However, when printing, puzzles may
  1539. no longer assume that the coordinate unit has any relationship to a
  1540. pixel; the printer's actual resolution might very well not even be
  1541. known at print time, so the coordinate unit might be smaller or
  1542. larger than a pixel. Puzzles' print functions should restrict
  1543. themselves to drawing geometric shapes rather than fiddly pixel
  1544. manipulation.
  1545. \e{Puzzles' redraw functions may assume that the surface they draw
  1546. on is persistent}. It is the responsibility of every front end to
  1547. preserve the puzzle's window contents in the face of GUI window
  1548. expose issues and similar. It is not permissible to request that the
  1549. back end redraw any part of a window that it has already drawn,
  1550. unless something has actually changed as a result of making moves in
  1551. the puzzle.
  1552. Most front ends accomplish this by having the drawing routines draw
  1553. on a stored bitmap rather than directly on the window, and copying
  1554. the bitmap to the window every time a part of the window needs to be
  1555. redrawn. Therefore, it is vitally important that whenever the back
  1556. end does any drawing it informs the front end of which parts of the
  1557. window it has accessed, and hence which parts need repainting. This
  1558. is done by calling \cw{draw_update()} (\k{drawing-draw-update}).
  1559. Persistence of old drawing is convenient. However, a puzzle should
  1560. be very careful about how it updates its drawing area. The problem
  1561. is that some front ends do anti-aliased drawing: rather than simply
  1562. choosing between leaving each pixel untouched or painting it a
  1563. specified colour, an antialiased drawing function will \e{blend} the
  1564. original and new colours in pixels at a figure's boundary according
  1565. to the proportion of the pixel occupied by the figure (probably
  1566. modified by some heuristic fudge factors). All of this produces a
  1567. smoother appearance for curves and diagonal lines.
  1568. An unfortunate effect of drawing an anti-aliased figure repeatedly
  1569. is that the pixels around the figure's boundary come steadily more
  1570. saturated with \q{ink} and the boundary appears to \q{spread out}.
  1571. Worse, redrawing a figure in a different colour won't fully paint
  1572. over the old boundary pixels, so the end result is a rather ugly
  1573. smudge.
  1574. A good strategy to avoid unpleasant anti-aliasing artifacts is to
  1575. identify a number of rectangular areas which need to be redrawn,
  1576. clear them to the background colour, and then redraw their contents
  1577. from scratch, being careful all the while not to stray beyond the
  1578. boundaries of the original rectangles. The \cw{clip()} function
  1579. (\k{drawing-clip}) comes in very handy here. Games based on a square
  1580. grid can often do this fairly easily. Other games may need to be
  1581. somewhat more careful. For example, Loopy's redraw function first
  1582. identifies portions of the display which need to be updated. Then,
  1583. if the changes are fairly well localised, it clears and redraws a
  1584. rectangle containing each changed area. Otherwise, it gives up and
  1585. redraws the entire grid from scratch.
  1586. It is possible to avoid clearing to background and redrawing from
  1587. scratch if one is very careful about which drawing functions one
  1588. uses: if a function is documented as not anti-aliasing under some
  1589. circumstances, you can rely on each pixel in a drawing either being
  1590. left entirely alone or being set to the requested colour, with no
  1591. blending being performed.
  1592. In the following sections I first discuss the drawing API as seen by
  1593. the back end, and then the \e{almost} identical function-pointer
  1594. form seen by the front end.
  1595. \H{drawing-backend} Drawing API as seen by the back end
  1596. This section documents the back-end drawing API, in the form of
  1597. functions which take a \c{drawing} object as an argument.
  1598. \S{drawing-draw-rect} \cw{draw_rect()}
  1599. \c void draw_rect(drawing *dr, int x, int y, int w, int h,
  1600. \c int colour);
  1601. Draws a filled rectangle in the puzzle window.
  1602. \c{x} and \c{y} give the coordinates of the top left pixel of the
  1603. rectangle. \c{w} and \c{h} give its width and height. Thus, the
  1604. horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
  1605. inclusive, and the vertical extent from \c{y} to \c{y+h-1}
  1606. inclusive.
  1607. \c{colour} is an integer index into the colours array returned by
  1608. the back end function \cw{colours()} (\k{backend-colours}).
  1609. There is no separate pixel-plotting function. If you want to plot a
  1610. single pixel, the approved method is to use \cw{draw_rect()} with
  1611. width and height set to 1.
  1612. Unlike many of the other drawing functions, this function is
  1613. guaranteed to be pixel-perfect: the rectangle will be sharply
  1614. defined and not anti-aliased or anything like that.
  1615. This function may be used for both drawing and printing.
  1616. \S{drawing-draw-rect-outline} \cw{draw_rect_outline()}
  1617. \c void draw_rect_outline(drawing *dr, int x, int y, int w, int h,
  1618. \c int colour);
  1619. Draws an outline rectangle in the puzzle window.
  1620. \c{x} and \c{y} give the coordinates of the top left pixel of the
  1621. rectangle. \c{w} and \c{h} give its width and height. Thus, the
  1622. horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
  1623. inclusive, and the vertical extent from \c{y} to \c{y+h-1}
  1624. inclusive.
  1625. \c{colour} is an integer index into the colours array returned by
  1626. the back end function \cw{colours()} (\k{backend-colours}).
  1627. From a back end perspective, this function may be considered to be
  1628. part of the drawing API. However, front ends are not required to
  1629. implement it, since it is actually implemented centrally (in
  1630. \cw{misc.c}) as a wrapper on \cw{draw_polygon()}.
  1631. This function may be used for both drawing and printing.
  1632. \S{drawing-draw-rect-corner} \cw{draw_rect_corners()}
  1633. \c void draw_rect_corners(drawing *dr, int cx, int cy, int r, int col);
  1634. Draws four L-shapes at the corners of a square, in the manner of a
  1635. target reticule. This is a convenience function for back ends to use
  1636. to display a keyboard cursor (if they want one in that style).
  1637. \c{cx} and \c{cy} give the coordinates of the centre of the square.
  1638. \c{r} is half the side length of the square, so that the corners are
  1639. at \cw{(cx-r,cy-r)}, \cw{(cx+r,cy-r)}, \cw{(cx-r,cy+r)} and
  1640. \cw{(cx+r,cy+r)}.
  1641. \c{colour} is an integer index into the colours array returned by
  1642. the back end function \cw{colours()} (\k{backend-colours}).
  1643. \S{drawing-draw-line} \cw{draw_line()}
  1644. \c void draw_line(drawing *dr, int x1, int y1, int x2, int y2,
  1645. \c int colour);
  1646. Draws a straight line in the puzzle window.
  1647. \c{x1} and \c{y1} give the coordinates of one end of the line.
  1648. \c{x2} and \c{y2} give the coordinates of the other end. The line
  1649. drawn includes both those points.
  1650. \c{colour} is an integer index into the colours array returned by
  1651. the back end function \cw{colours()} (\k{backend-colours}).
  1652. Some platforms may perform anti-aliasing on this function.
  1653. Therefore, do not assume that you can erase a line by drawing the
  1654. same line over it in the background colour; anti-aliasing might lead
  1655. to perceptible ghost artefacts around the vanished line. Horizontal
  1656. and vertical lines, however, are pixel-perfect and not anti-aliased.
  1657. This function may be used for both drawing and printing.
  1658. \S{drawing-draw-polygon} \cw{draw_polygon()}
  1659. \c void draw_polygon(drawing *dr, const int *coords, int npoints,
  1660. \c int fillcolour, int outlinecolour);
  1661. Draws an outlined or filled polygon in the puzzle window.
  1662. \c{coords} is an array of \cw{(2*npoints)} integers, containing the
  1663. \c{x} and \c{y} coordinates of \c{npoints} vertices.
  1664. \c{fillcolour} and \c{outlinecolour} are integer indices into the
  1665. colours array returned by the back end function \cw{colours()}
  1666. (\k{backend-colours}). \c{fillcolour} may also be \cw{-1} to
  1667. indicate that the polygon should be outlined only.
  1668. The polygon defined by the specified list of vertices is first
  1669. filled in \c{fillcolour}, if specified, and then outlined in
  1670. \c{outlinecolour}.
  1671. \c{outlinecolour} may \e{not} be \cw{-1}; it must be a valid colour
  1672. (and front ends are permitted to enforce this by assertion). This is
  1673. because different platforms disagree on whether a filled polygon
  1674. should include its boundary line or not, so drawing \e{only} a
  1675. filled polygon would have non-portable effects. If you want your
  1676. filled polygon not to have a visible outline, you must set
  1677. \c{outlinecolour} to the same as \c{fillcolour}.
  1678. Some platforms may perform anti-aliasing on this function.
  1679. Therefore, do not assume that you can erase a polygon by drawing the
  1680. same polygon over it in the background colour. Also, be prepared for
  1681. the polygon to extend a pixel beyond its obvious bounding box as a
  1682. result of this; if you really need it not to do this to avoid
  1683. interfering with other delicate graphics, you should probably use
  1684. \cw{clip()} (\k{drawing-clip}). You can rely on horizontal and
  1685. vertical lines not being anti-aliased.
  1686. This function may be used for both drawing and printing.
  1687. \S{drawing-draw-circle} \cw{draw_circle()}
  1688. \c void draw_circle(drawing *dr, int cx, int cy, int radius,
  1689. \c int fillcolour, int outlinecolour);
  1690. Draws an outlined or filled circle in the puzzle window.
  1691. \c{cx} and \c{cy} give the coordinates of the centre of the circle.
  1692. \c{radius} gives its radius. The total horizontal pixel extent of
  1693. the circle is from \c{cx-radius+1} to \c{cx+radius-1} inclusive, and
  1694. the vertical extent similarly around \c{cy}.
  1695. \c{fillcolour} and \c{outlinecolour} are integer indices into the
  1696. colours array returned by the back end function \cw{colours()}
  1697. (\k{backend-colours}). \c{fillcolour} may also be \cw{-1} to
  1698. indicate that the circle should be outlined only.
  1699. The circle is first filled in \c{fillcolour}, if specified, and then
  1700. outlined in \c{outlinecolour}.
  1701. \c{outlinecolour} may \e{not} be \cw{-1}; it must be a valid colour
  1702. (and front ends are permitted to enforce this by assertion). This is
  1703. because different platforms disagree on whether a filled circle
  1704. should include its boundary line or not, so drawing \e{only} a
  1705. filled circle would have non-portable effects. If you want your
  1706. filled circle not to have a visible outline, you must set
  1707. \c{outlinecolour} to the same as \c{fillcolour}.
  1708. Some platforms may perform anti-aliasing on this function.
  1709. Therefore, do not assume that you can erase a circle by drawing the
  1710. same circle over it in the background colour. Also, be prepared for
  1711. the circle to extend a pixel beyond its obvious bounding box as a
  1712. result of this; if you really need it not to do this to avoid
  1713. interfering with other delicate graphics, you should probably use
  1714. \cw{clip()} (\k{drawing-clip}).
  1715. This function may be used for both drawing and printing.
  1716. \S{drawing-draw-thick-line} \cw{draw_thick_line()}
  1717. \c void draw_thick_line(drawing *dr, float thickness,
  1718. \c float x1, float y1, float x2, float y2,
  1719. \c int colour)
  1720. Draws a line in the puzzle window, giving control over the line's
  1721. thickness.
  1722. \c{x1} and \c{y1} give the coordinates of one end of the line.
  1723. \c{x2} and \c{y2} give the coordinates of the other end.
  1724. \c{thickness} gives the thickness of the line, in pixels.
  1725. Note that the coordinates and thickness are floating-point: the
  1726. continuous coordinate system is in effect here. It's important to
  1727. be able to address points with better-than-pixel precision in this
  1728. case, because one can't otherwise properly express the endpoints of
  1729. lines with both odd and even thicknesses.
  1730. Some platforms may perform anti-aliasing on this function. The
  1731. precise pixels affected by a thick-line drawing operation may vary
  1732. between platforms, and no particular guarantees are provided.
  1733. Indeed, even horizontal or vertical lines may be anti-aliased.
  1734. This function may be used for both drawing and printing.
  1735. If the specified thickness is less than 1.0, 1.0 is used.
  1736. This ensures that thin lines are visible even at small scales.
  1737. \S{drawing-draw-text} \cw{draw_text()}
  1738. \c void draw_text(drawing *dr, int x, int y, int fonttype,
  1739. \c int fontsize, int align, int colour,
  1740. \c const char *text);
  1741. Draws text in the puzzle window.
  1742. \c{x} and \c{y} give the coordinates of a point. The relation of
  1743. this point to the location of the text is specified by \c{align},
  1744. which is a bitwise OR of horizontal and vertical alignment flags:
  1745. \dt \cw{ALIGN_VNORMAL}
  1746. \dd Indicates that \c{y} is aligned with the baseline of the text.
  1747. \dt \cw{ALIGN_VCENTRE}
  1748. \dd Indicates that \c{y} is aligned with the vertical centre of the
  1749. text. (In fact, it's aligned with the vertical centre of normal
  1750. \e{capitalised} text: displaying two pieces of text with
  1751. \cw{ALIGN_VCENTRE} at the same \cw{y}-coordinate will cause their
  1752. baselines to be aligned with one another, even if one is an ascender
  1753. and the other a descender.)
  1754. \dt \cw{ALIGN_HLEFT}
  1755. \dd Indicates that \c{x} is aligned with the left-hand end of the
  1756. text.
  1757. \dt \cw{ALIGN_HCENTRE}
  1758. \dd Indicates that \c{x} is aligned with the horizontal centre of
  1759. the text.
  1760. \dt \cw{ALIGN_HRIGHT}
  1761. \dd Indicates that \c{x} is aligned with the right-hand end of the
  1762. text.
  1763. \c{fonttype} is either \cw{FONT_FIXED} or \cw{FONT_VARIABLE}, for a
  1764. monospaced or proportional font respectively. (No more detail than
  1765. that may be specified; it would only lead to portability issues
  1766. between different platforms.)
  1767. \c{fontsize} is the desired size, in pixels, of the text. This size
  1768. corresponds to the overall point size of the text, not to any
  1769. internal dimension such as the cap-height.
  1770. \c{colour} is an integer index into the colours array returned by
  1771. the back end function \cw{colours()} (\k{backend-colours}).
  1772. This function may be used for both drawing and printing.
  1773. The character set used to encode the text passed to this function is
  1774. specified \e{by the drawing object}, although it must be a superset
  1775. of ASCII. If a puzzle wants to display text that is not contained in
  1776. ASCII, it should use the \cw{text_fallback()} function
  1777. (\k{drawing-text-fallback}) to query the drawing object for an
  1778. appropriate representation of the characters it wants.
  1779. \S{drawing-text-fallback} \cw{text_fallback()}
  1780. \c char *text_fallback(drawing *dr, const char *const *strings,
  1781. \c int nstrings);
  1782. This function is used to request a translation of UTF-8 text into
  1783. whatever character encoding is expected by the drawing object's
  1784. implementation of \cw{draw_text()}.
  1785. The input is a list of strings encoded in UTF-8: \cw{nstrings} gives
  1786. the number of strings in the list, and \cw{strings[0]},
  1787. \cw{strings[1]}, ..., \cw{strings[nstrings-1]} are the strings
  1788. themselves.
  1789. The returned string (which is dynamically allocated and must be
  1790. freed when finished with) is derived from the first string in the
  1791. list that the drawing object expects to be able to display reliably;
  1792. it will consist of that string translated into the character set
  1793. expected by \cw{draw_text()}.
  1794. Drawing implementations are not required to handle anything outside
  1795. ASCII, but are permitted to assume that \e{some} string will be
  1796. successfully translated. So every call to this function must include
  1797. a string somewhere in the list (presumably the last element) which
  1798. consists of nothing but ASCII, to be used by any front end which
  1799. cannot handle anything else.
  1800. For example, if a puzzle wished to display a string including a
  1801. multiplication sign (U+00D7 in Unicode, represented by the bytes C3
  1802. 97 in UTF-8), it might do something like this:
  1803. \c static const char *const times_signs[] = { "\xC3\x97", "x" };
  1804. \c char *times_sign = text_fallback(dr, times_signs, 2);
  1805. \c sprintf(buffer, "%d%s%d", width, times_sign, height);
  1806. \c sfree(times_sign);
  1807. \c draw_text(dr, x, y, font, size, align, colour, buffer);
  1808. \c sfree(buffer);
  1809. which would draw a string with a times sign in the middle on
  1810. platforms that support it, and fall back to a simple ASCII \cq{x}
  1811. where there was no alternative.
  1812. \S{drawing-clip} \cw{clip()}
  1813. \c void clip(drawing *dr, int x, int y, int w, int h);
  1814. Establishes a clipping rectangle in the puzzle window.
  1815. \c{x} and \c{y} give the coordinates of the top left pixel of the
  1816. clipping rectangle. \c{w} and \c{h} give its width and height. Thus,
  1817. the horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
  1818. inclusive, and the vertical extent from \c{y} to \c{y+h-1}
  1819. inclusive. (These are exactly the same semantics as
  1820. \cw{draw_rect()}.)
  1821. After this call, no drawing operation will affect anything outside
  1822. the specified rectangle. The effect can be reversed by calling
  1823. \cw{unclip()} (\k{drawing-unclip}). The clipping rectangle is
  1824. pixel-perfect: pixels within the rectangle are affected as usual by
  1825. drawing functions; pixels outside are completely untouched.
  1826. Back ends should not assume that a clipping rectangle will be
  1827. automatically cleared up by the front end if it's left lying around;
  1828. that might work on current front ends, but shouldn't be relied upon.
  1829. Always explicitly call \cw{unclip()}.
  1830. This function may be used for both drawing and printing.
  1831. \S{drawing-unclip} \cw{unclip()}
  1832. \c void unclip(drawing *dr);
  1833. Reverts the effect of a previous call to \cw{clip()}. After this
  1834. call, all drawing operations will be able to affect the entire
  1835. puzzle window again.
  1836. This function may be used for both drawing and printing.
  1837. \S{drawing-draw-update} \cw{draw_update()}
  1838. \c void draw_update(drawing *dr, int x, int y, int w, int h);
  1839. Informs the front end that a rectangular portion of the puzzle
  1840. window has been drawn on and needs to be updated.
  1841. \c{x} and \c{y} give the coordinates of the top left pixel of the
  1842. update rectangle. \c{w} and \c{h} give its width and height. Thus,
  1843. the horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
  1844. inclusive, and the vertical extent from \c{y} to \c{y+h-1}
  1845. inclusive. (These are exactly the same semantics as
  1846. \cw{draw_rect()}.)
  1847. The back end redraw function \e{must} call this function to report
  1848. any changes it has made to the window. Otherwise, those changes may
  1849. not become immediately visible, and may then appear at an
  1850. unpredictable subsequent time such as the next time the window is
  1851. covered and re-exposed.
  1852. This function is only important when drawing. It may be called when
  1853. printing as well, but doing so is not compulsory, and has no effect.
  1854. (So if you have a shared piece of code between the drawing and
  1855. printing routines, that code may safely call \cw{draw_update()}.)
  1856. \S{drawing-status-bar} \cw{status_bar()}
  1857. \c void status_bar(drawing *dr, const char *text);
  1858. Sets the text in the game's status bar to \c{text}. The text is copied
  1859. from the supplied buffer, so the caller is free to deallocate or
  1860. modify the buffer after use.
  1861. (This function is not exactly a \e{drawing} function, but it shares
  1862. with the drawing API the property that it may only be called from
  1863. within the back end redraw function. And it's implemented by front
  1864. ends via the \c{drawing_api} function pointer table. So this is the
  1865. best place to document it.)
  1866. The supplied text is filtered through the mid-end for optional
  1867. rewriting before being passed on to the front end; the mid-end will
  1868. prepend the current game time if the game is timed (and may in
  1869. future perform other rewriting if it seems like a good idea).
  1870. This function is for drawing only; it must never be called during
  1871. printing.
  1872. \S{drawing-blitter} Blitter functions
  1873. This section describes a group of related functions which save and
  1874. restore a section of the puzzle window. This is most commonly used
  1875. to implement user interfaces involving dragging a puzzle element
  1876. around the window: at the end of each call to \cw{redraw()}, if an
  1877. object is currently being dragged, the back end saves the window
  1878. contents under that location and then draws the dragged object, and
  1879. at the start of the next \cw{redraw()} the first thing it does is to
  1880. restore the background.
  1881. The front end defines an opaque type called a \c{blitter}, which is
  1882. capable of storing a rectangular area of a specified size.
  1883. Blitter functions are for drawing only; they must never be called
  1884. during printing.
  1885. \S2{drawing-blitter-new} \cw{blitter_new()}
  1886. \c blitter *blitter_new(drawing *dr, int w, int h);
  1887. Creates a new blitter object which stores a rectangle of size \c{w}
  1888. by \c{h} pixels. Returns a pointer to the blitter object.
  1889. Blitter objects are best stored in the \c{game_drawstate}. A good
  1890. time to create them is in the \cw{set_size()} function
  1891. (\k{backend-set-size}), since it is at this point that you first
  1892. know how big a rectangle they will need to save.
  1893. \S2{drawing-blitter-free} \cw{blitter_free()}
  1894. \c void blitter_free(drawing *dr, blitter *bl);
  1895. Disposes of a blitter object. Best called in \cw{free_drawstate()}.
  1896. (However, check that the blitter object is not \cw{NULL} before
  1897. attempting to free it; it is possible that a draw state might be
  1898. created and freed without ever having \cw{set_size()} called on it
  1899. in between.)
  1900. \S2{drawing-blitter-save} \cw{blitter_save()}
  1901. \c void blitter_save(drawing *dr, blitter *bl, int x, int y);
  1902. This is a true drawing API function, in that it may only be called
  1903. from within the game redraw routine. It saves a rectangular portion
  1904. of the puzzle window into the specified blitter object.
  1905. \c{x} and \c{y} give the coordinates of the top left corner of the
  1906. saved rectangle. The rectangle's width and height are the ones
  1907. specified when the blitter object was created.
  1908. This function is required to cope and do the right thing if \c{x}
  1909. and \c{y} are out of range. (The right thing probably means saving
  1910. whatever part of the blitter rectangle overlaps with the visible
  1911. area of the puzzle window.)
  1912. \S2{drawing-blitter-load} \cw{blitter_load()}
  1913. \c void blitter_load(drawing *dr, blitter *bl, int x, int y);
  1914. This is a true drawing API function, in that it may only be called
  1915. from within the game redraw routine. It restores a rectangular
  1916. portion of the puzzle window from the specified blitter object.
  1917. \c{x} and \c{y} give the coordinates of the top left corner of the
  1918. rectangle to be restored. The rectangle's width and height are the
  1919. ones specified when the blitter object was created.
  1920. Alternatively, you can specify both \c{x} and \c{y} as the special
  1921. value \cw{BLITTER_FROMSAVED}, in which case the rectangle will be
  1922. restored to exactly where it was saved from. (This is probably what
  1923. you want to do almost all the time, if you're using blitters to
  1924. implement draggable puzzle elements.)
  1925. This function is required to cope and do the right thing if \c{x}
  1926. and \c{y} (or the equivalent ones saved in the blitter) are out of
  1927. range. (The right thing probably means restoring whatever part of
  1928. the blitter rectangle overlaps with the visible area of the puzzle
  1929. window.)
  1930. If this function is called on a blitter which had previously been
  1931. saved from a partially out-of-range rectangle, then the parts of the
  1932. saved bitmap which were not visible at save time are undefined. If
  1933. the blitter is restored to a different position so as to make those
  1934. parts visible, the effect on the drawing area is undefined.
  1935. \S{print-mono-colour} \cw{print_mono_colour()}
  1936. \c int print_mono_colour(drawing *dr, int grey);
  1937. This function allocates a colour index for a simple monochrome
  1938. colour during printing.
  1939. \c{grey} must be 0 or 1. If \c{grey} is 0, the colour returned is
  1940. black; if \c{grey} is 1, the colour is white.
  1941. \S{print-grey-colour} \cw{print_grey_colour()}
  1942. \c int print_grey_colour(drawing *dr, float grey);
  1943. This function allocates a colour index for a grey-scale colour
  1944. during printing.
  1945. \c{grey} may be any number between 0 (black) and 1 (white); for
  1946. example, 0.5 indicates a medium grey.
  1947. The chosen colour will be rendered to the limits of the printer's
  1948. halftoning capability.
  1949. \S{print-hatched-colour} \cw{print_hatched_colour()}
  1950. \c int print_hatched_colour(drawing *dr, int hatch);
  1951. This function allocates a colour index which does not represent a
  1952. literal \e{colour}. Instead, regions shaded in this colour will be
  1953. hatched with parallel lines. The \c{hatch} parameter defines what
  1954. type of hatching should be used in place of this colour:
  1955. \dt \cw{HATCH_SLASH}
  1956. \dd This colour will be hatched by lines slanting to the right at 45
  1957. degrees.
  1958. \dt \cw{HATCH_BACKSLASH}
  1959. \dd This colour will be hatched by lines slanting to the left at 45
  1960. degrees.
  1961. \dt \cw{HATCH_HORIZ}
  1962. \dd This colour will be hatched by horizontal lines.
  1963. \dt \cw{HATCH_VERT}
  1964. \dd This colour will be hatched by vertical lines.
  1965. \dt \cw{HATCH_PLUS}
  1966. \dd This colour will be hatched by criss-crossing horizontal and
  1967. vertical lines.
  1968. \dt \cw{HATCH_X}
  1969. \dd This colour will be hatched by criss-crossing diagonal lines.
  1970. Colours defined to use hatching may not be used for drawing lines or
  1971. text; they may only be used for filling areas. That is, they may be
  1972. used as the \c{fillcolour} parameter to \cw{draw_circle()} and
  1973. \cw{draw_polygon()}, and as the colour parameter to
  1974. \cw{draw_rect()}, but may not be used as the \c{outlinecolour}
  1975. parameter to \cw{draw_circle()} or \cw{draw_polygon()}, or with
  1976. \cw{draw_line()} or \cw{draw_text()}.
  1977. \S{print-rgb-mono-colour} \cw{print_rgb_mono_colour()}
  1978. \c int print_rgb_mono_colour(drawing *dr, float r, float g,
  1979. \c float b, float grey);
  1980. This function allocates a colour index for a fully specified RGB
  1981. colour during printing.
  1982. \c{r}, \c{g} and \c{b} may each be anywhere in the range from 0 to 1.
  1983. If printing in black and white only, these values will be ignored,
  1984. and either pure black or pure white will be used instead, according
  1985. to the \q{grey} parameter. (The fallback colour is the same as the
  1986. one which would be allocated by \cw{print_mono_colour(grey)}.)
  1987. \S{print-rgb-grey-colour} \cw{print_rgb_grey_colour()}
  1988. \c int print_rgb_grey_colour(drawing *dr, float r, float g,
  1989. \c float b, float grey);
  1990. This function allocates a colour index for a fully specified RGB
  1991. colour during printing.
  1992. \c{r}, \c{g} and \c{b} may each be anywhere in the range from 0 to 1.
  1993. If printing in black and white only, these values will be ignored,
  1994. and a shade of grey given by the \c{grey} parameter will be used
  1995. instead. (The fallback colour is the same as the one which would be
  1996. allocated by \cw{print_grey_colour(grey)}.)
  1997. \S{print-rgb-hatched-colour} \cw{print_rgb_hatched_colour()}
  1998. \c int print_rgb_hatched_colour(drawing *dr, float r, float g,
  1999. \c float b, float hatched);
  2000. This function allocates a colour index for a fully specified RGB
  2001. colour during printing.
  2002. \c{r}, \c{g} and \c{b} may each be anywhere in the range from 0 to 1.
  2003. If printing in black and white only, these values will be ignored,
  2004. and a form of cross-hatching given by the \c{hatch} parameter will
  2005. be used instead; see \k{print-hatched-colour} for the possible
  2006. values of this parameter. (The fallback colour is the same as the
  2007. one which would be allocated by \cw{print_hatched_colour(hatch)}.)
  2008. \S{print-line-width} \cw{print_line_width()}
  2009. \c void print_line_width(drawing *dr, int width);
  2010. This function is called to set the thickness of lines drawn during
  2011. printing. It is meaningless in drawing: all lines drawn by
  2012. \cw{draw_line()}, \cw{draw_circle} and \cw{draw_polygon()} are one
  2013. pixel in thickness. However, in printing there is no clear
  2014. definition of a pixel and so line widths must be explicitly
  2015. specified.
  2016. The line width is specified in the usual coordinate system. Note,
  2017. however, that it is a hint only: the central printing system may
  2018. choose to vary line thicknesses at user request or due to printer
  2019. capabilities.
  2020. \S{print-line-dotted} \cw{print_line_dotted()}
  2021. \c void print_line_dotted(drawing *dr, bool dotted);
  2022. This function is called to toggle the drawing of dotted lines during
  2023. printing. It is not supported during drawing.
  2024. Setting \cq{dotted} to \cw{true} means that future lines drawn by
  2025. \cw{draw_line()}, \cw{draw_circle} and \cw{draw_polygon()} will be
  2026. dotted. Setting it to \cw{false} means that they will be solid.
  2027. Some front ends may impose restrictions on the width of dotted
  2028. lines. Asking for a dotted line via this front end will override any
  2029. line width request if the front end requires it.
  2030. \H{drawing-frontend} The drawing API as implemented by the front end
  2031. This section describes the drawing API in the function-pointer form
  2032. in which it is implemented by a front end.
  2033. (It isn't only platform-specific front ends which implement this
  2034. API; the platform-independent module \c{ps.c} also provides an
  2035. implementation of it which outputs PostScript. Thus, any platform
  2036. which wants to do PS printing can do so with minimum fuss.)
  2037. The following entries all describe function pointer fields in a
  2038. structure called \c{drawing_api}. Each of the functions takes a
  2039. \cq{void *} context pointer, which it should internally cast back to
  2040. a more useful type. Thus, a drawing \e{object} (\c{drawing *)}
  2041. suitable for passing to the back end redraw or printing functions
  2042. is constructed by passing a \c{drawing_api} and a \cq{void *} to the
  2043. function \cw{drawing_new()} (see \k{drawing-new}).
  2044. \S{drawingapi-draw-text} \cw{draw_text()}
  2045. \c void (*draw_text)(void *handle, int x, int y, int fonttype,
  2046. \c int fontsize, int align, int colour,
  2047. \c const char *text);
  2048. This function behaves exactly like the back end \cw{draw_text()}
  2049. function; see \k{drawing-draw-text}.
  2050. \S{drawingapi-draw-rect} \cw{draw_rect()}
  2051. \c void (*draw_rect)(void *handle, int x, int y, int w, int h,
  2052. \c int colour);
  2053. This function behaves exactly like the back end \cw{draw_rect()}
  2054. function; see \k{drawing-draw-rect}.
  2055. \S{drawingapi-draw-line} \cw{draw_line()}
  2056. \c void (*draw_line)(void *handle, int x1, int y1, int x2, int y2,
  2057. \c int colour);
  2058. This function behaves exactly like the back end \cw{draw_line()}
  2059. function; see \k{drawing-draw-line}.
  2060. \S{drawingapi-draw-polygon} \cw{draw_polygon()}
  2061. \c void (*draw_polygon)(void *handle, const int *coords, int npoints,
  2062. \c int fillcolour, int outlinecolour);
  2063. This function behaves exactly like the back end \cw{draw_polygon()}
  2064. function; see \k{drawing-draw-polygon}.
  2065. \S{drawingapi-draw-circle} \cw{draw_circle()}
  2066. \c void (*draw_circle)(void *handle, int cx, int cy, int radius,
  2067. \c int fillcolour, int outlinecolour);
  2068. This function behaves exactly like the back end \cw{draw_circle()}
  2069. function; see \k{drawing-draw-circle}.
  2070. \S{drawingapi-draw-thick-line} \cw{draw_thick_line()}
  2071. \c void draw_thick_line(drawing *dr, float thickness,
  2072. \c float x1, float y1, float x2, float y2,
  2073. \c int colour)
  2074. This function behaves exactly like the back end
  2075. \cw{draw_thick_line()} function; see \k{drawing-draw-thick-line}.
  2076. An implementation of this API which doesn't provide high-quality
  2077. rendering of thick lines is permitted to define this function
  2078. pointer to be \cw{NULL}. The middleware in \cw{drawing.c} will notice
  2079. and provide a low-quality alternative using \cw{draw_polygon()}.
  2080. \S{drawingapi-draw-update} \cw{draw_update()}
  2081. \c void (*draw_update)(void *handle, int x, int y, int w, int h);
  2082. This function behaves exactly like the back end \cw{draw_update()}
  2083. function; see \k{drawing-draw-update}.
  2084. An implementation of this API which only supports printing is
  2085. permitted to define this function pointer to be \cw{NULL} rather
  2086. than bothering to define an empty function. The middleware in
  2087. \cw{drawing.c} will notice and avoid calling it.
  2088. \S{drawingapi-clip} \cw{clip()}
  2089. \c void (*clip)(void *handle, int x, int y, int w, int h);
  2090. This function behaves exactly like the back end \cw{clip()}
  2091. function; see \k{drawing-clip}.
  2092. \S{drawingapi-unclip} \cw{unclip()}
  2093. \c void (*unclip)(void *handle);
  2094. This function behaves exactly like the back end \cw{unclip()}
  2095. function; see \k{drawing-unclip}.
  2096. \S{drawingapi-start-draw} \cw{start_draw()}
  2097. \c void (*start_draw)(void *handle);
  2098. This function is called at the start of drawing. It allows the front
  2099. end to initialise any temporary data required to draw with, such as
  2100. device contexts.
  2101. Implementations of this API which do not provide drawing services
  2102. may define this function pointer to be \cw{NULL}; it will never be
  2103. called unless drawing is attempted.
  2104. \S{drawingapi-end-draw} \cw{end_draw()}
  2105. \c void (*end_draw)(void *handle);
  2106. This function is called at the end of drawing. It allows the front
  2107. end to do cleanup tasks such as deallocating device contexts and
  2108. scheduling appropriate GUI redraw events.
  2109. Implementations of this API which do not provide drawing services
  2110. may define this function pointer to be \cw{NULL}; it will never be
  2111. called unless drawing is attempted.
  2112. \S{drawingapi-status-bar} \cw{status_bar()}
  2113. \c void (*status_bar)(void *handle, const char *text);
  2114. This function behaves exactly like the back end \cw{status_bar()}
  2115. function; see \k{drawing-status-bar}.
  2116. Front ends implementing this function need not worry about it being
  2117. called repeatedly with the same text; the middleware code in
  2118. \cw{status_bar()} will take care of this.
  2119. Implementations of this API which do not provide drawing services
  2120. may define this function pointer to be \cw{NULL}; it will never be
  2121. called unless drawing is attempted.
  2122. \S{drawingapi-blitter-new} \cw{blitter_new()}
  2123. \c blitter *(*blitter_new)(void *handle, int w, int h);
  2124. This function behaves exactly like the back end \cw{blitter_new()}
  2125. function; see \k{drawing-blitter-new}.
  2126. Implementations of this API which do not provide drawing services
  2127. may define this function pointer to be \cw{NULL}; it will never be
  2128. called unless drawing is attempted.
  2129. \S{drawingapi-blitter-free} \cw{blitter_free()}
  2130. \c void (*blitter_free)(void *handle, blitter *bl);
  2131. This function behaves exactly like the back end \cw{blitter_free()}
  2132. function; see \k{drawing-blitter-free}.
  2133. Implementations of this API which do not provide drawing services
  2134. may define this function pointer to be \cw{NULL}; it will never be
  2135. called unless drawing is attempted.
  2136. \S{drawingapi-blitter-save} \cw{blitter_save()}
  2137. \c void (*blitter_save)(void *handle, blitter *bl, int x, int y);
  2138. This function behaves exactly like the back end \cw{blitter_save()}
  2139. function; see \k{drawing-blitter-save}.
  2140. Implementations of this API which do not provide drawing services
  2141. may define this function pointer to be \cw{NULL}; it will never be
  2142. called unless drawing is attempted.
  2143. \S{drawingapi-blitter-load} \cw{blitter_load()}
  2144. \c void (*blitter_load)(void *handle, blitter *bl, int x, int y);
  2145. This function behaves exactly like the back end \cw{blitter_load()}
  2146. function; see \k{drawing-blitter-load}.
  2147. Implementations of this API which do not provide drawing services
  2148. may define this function pointer to be \cw{NULL}; it will never be
  2149. called unless drawing is attempted.
  2150. \S{drawingapi-begin-doc} \cw{begin_doc()}
  2151. \c void (*begin_doc)(void *handle, int pages);
  2152. This function is called at the beginning of a printing run. It gives
  2153. the front end an opportunity to initialise any required printing
  2154. subsystem. It also provides the number of pages in advance.
  2155. Implementations of this API which do not provide printing services
  2156. may define this function pointer to be \cw{NULL}; it will never be
  2157. called unless printing is attempted.
  2158. \S{drawingapi-begin-page} \cw{begin_page()}
  2159. \c void (*begin_page)(void *handle, int number);
  2160. This function is called during printing, at the beginning of each
  2161. page. It gives the page number (numbered from 1 rather than 0, so
  2162. suitable for use in user-visible contexts).
  2163. Implementations of this API which do not provide printing services
  2164. may define this function pointer to be \cw{NULL}; it will never be
  2165. called unless printing is attempted.
  2166. \S{drawingapi-begin-puzzle} \cw{begin_puzzle()}
  2167. \c void (*begin_puzzle)(void *handle, float xm, float xc,
  2168. \c float ym, float yc, int pw, int ph, float wmm);
  2169. This function is called during printing, just before printing a
  2170. single puzzle on a page. It specifies the size and location of the
  2171. puzzle on the page.
  2172. \c{xm} and \c{xc} specify the horizontal position of the puzzle on
  2173. the page, as a linear function of the page width. The front end is
  2174. expected to multiply the page width by \c{xm}, add \c{xc} (measured
  2175. in millimetres), and use the resulting x-coordinate as the left edge
  2176. of the puzzle.
  2177. Similarly, \c{ym} and \c{yc} specify the vertical position of the
  2178. puzzle as a function of the page height: the page height times
  2179. \c{ym}, plus \c{yc} millimetres, equals the desired distance from
  2180. the top of the page to the top of the puzzle.
  2181. (This unwieldy mechanism is required because not all printing
  2182. systems can communicate the page size back to the software. The
  2183. PostScript back end, for example, writes out PS which determines the
  2184. page size at print time by means of calling \cq{clippath}, and
  2185. centres the puzzles within that. Thus, exactly the same PS file
  2186. works on A4 or on US Letter paper without needing local
  2187. configuration, which simplifies matters.)
  2188. \cw{pw} and \cw{ph} give the size of the puzzle in drawing API
  2189. coordinates. The printing system will subsequently call the puzzle's
  2190. own print function, which will in turn call drawing API functions in
  2191. the expectation that an area \cw{pw} by \cw{ph} units is available
  2192. to draw the puzzle on.
  2193. Finally, \cw{wmm} gives the desired width of the puzzle in
  2194. millimetres. (The aspect ratio is expected to be preserved, so if
  2195. the desired puzzle height is also needed then it can be computed as
  2196. \cw{wmm*ph/pw}.)
  2197. Implementations of this API which do not provide printing services
  2198. may define this function pointer to be \cw{NULL}; it will never be
  2199. called unless printing is attempted.
  2200. \S{drawingapi-end-puzzle} \cw{end_puzzle()}
  2201. \c void (*end_puzzle)(void *handle);
  2202. This function is called after the printing of a specific puzzle is
  2203. complete.
  2204. Implementations of this API which do not provide printing services
  2205. may define this function pointer to be \cw{NULL}; it will never be
  2206. called unless printing is attempted.
  2207. \S{drawingapi-end-page} \cw{end_page()}
  2208. \c void (*end_page)(void *handle, int number);
  2209. This function is called after the printing of a page is finished.
  2210. Implementations of this API which do not provide printing services
  2211. may define this function pointer to be \cw{NULL}; it will never be
  2212. called unless printing is attempted.
  2213. \S{drawingapi-end-doc} \cw{end_doc()}
  2214. \c void (*end_doc)(void *handle);
  2215. This function is called after the printing of the entire document is
  2216. finished. This is the moment to close files, send things to the
  2217. print spooler, or whatever the local convention is.
  2218. Implementations of this API which do not provide printing services
  2219. may define this function pointer to be \cw{NULL}; it will never be
  2220. called unless printing is attempted.
  2221. \S{drawingapi-line-width} \cw{line_width()}
  2222. \c void (*line_width)(void *handle, float width);
  2223. This function is called to set the line thickness, during printing
  2224. only. Note that the width is a \cw{float} here, where it was an
  2225. \cw{int} as seen by the back end. This is because \cw{drawing.c} may
  2226. have scaled it on the way past.
  2227. However, the width is still specified in the same coordinate system
  2228. as the rest of the drawing.
  2229. Implementations of this API which do not provide printing services
  2230. may define this function pointer to be \cw{NULL}; it will never be
  2231. called unless printing is attempted.
  2232. \S{drawingapi-line-dotted} \cw{line_dotted()}
  2233. \c void (*line_dotted)(void *handle, bool dotted);
  2234. This function is called to toggle drawing of dotted lines, during
  2235. printing only.
  2236. Implementations of this API which do not provide printing services
  2237. may define this function pointer to be \cw{NULL}; it will never be
  2238. called unless printing is attempted.
  2239. \S{drawingapi-text-fallback} \cw{text_fallback()}
  2240. \c char *(*text_fallback)(void *handle, const char *const *strings,
  2241. \c int nstrings);
  2242. This function behaves exactly like the back end \cw{text_fallback()}
  2243. function; see \k{drawing-text-fallback}.
  2244. Implementations of this API which do not support any characters
  2245. outside ASCII may define this function pointer to be \cw{NULL}, in
  2246. which case the central code in \cw{drawing.c} will provide a default
  2247. implementation.
  2248. \H{drawingapi-frontend} The drawing API as called by the front end
  2249. There are a small number of functions provided in \cw{drawing.c}
  2250. which the front end needs to \e{call}, rather than helping to
  2251. implement. They are described in this section.
  2252. \S{drawing-new} \cw{drawing_new()}
  2253. \c drawing *drawing_new(const drawing_api *api, midend *me,
  2254. \c void *handle);
  2255. This function creates a drawing object. It is passed a
  2256. \c{drawing_api}, which is a structure containing nothing but
  2257. function pointers; and also a \cq{void *} handle. The handle is
  2258. passed back to each function pointer when it is called.
  2259. The \c{midend} parameter is used for rewriting the status bar
  2260. contents: \cw{status_bar()} (see \k{drawing-status-bar}) has to call
  2261. a function in the mid-end which might rewrite the status bar text.
  2262. If the drawing object is to be used only for printing, or if the
  2263. game is known not to call \cw{status_bar()}, this parameter may be
  2264. \cw{NULL}.
  2265. \S{drawing-free} \cw{drawing_free()}
  2266. \c void drawing_free(drawing *dr);
  2267. This function frees a drawing object. Note that the \cq{void *}
  2268. handle is not freed; if that needs cleaning up it must be done by
  2269. the front end.
  2270. \S{drawing-print-get-colour} \cw{print_get_colour()}
  2271. \c void print_get_colour(drawing *dr, int colour,
  2272. \c bool printing_in_colour,
  2273. \c int *hatch, float *r, float *g, float *b);
  2274. This function is called by the implementations of the drawing API
  2275. functions when they are called in a printing context. It takes a
  2276. colour index as input, and returns the description of the colour as
  2277. requested by the back end.
  2278. \c{printing_in_colour} is \cw{true} iff the implementation is printing
  2279. in colour. This will alter the results returned if the colour in
  2280. question was specified with a black-and-white fallback value.
  2281. If the colour should be rendered by hatching, \c{*hatch} is filled
  2282. with the type of hatching desired. See \k{print-grey-colour} for
  2283. details of the values this integer can take.
  2284. If the colour should be rendered as solid colour, \c{*hatch} is
  2285. given a negative value, and \c{*r}, \c{*g} and \c{*b} are filled
  2286. with the RGB values of the desired colour (if printing in colour),
  2287. or all filled with the grey-scale value (if printing in black and
  2288. white).
  2289. \C{midend} The API provided by the mid-end
  2290. This chapter documents the API provided by the mid-end to be called
  2291. by the front end. You probably only need to read this if you are a
  2292. front end implementor, i.e. you are porting Puzzles to a new
  2293. platform. If you're only interested in writing new puzzles, you can
  2294. safely skip this chapter.
  2295. All the persistent state in the mid-end is encapsulated within a
  2296. \c{midend} structure, to facilitate having multiple mid-ends in any
  2297. port which supports multiple puzzle windows open simultaneously.
  2298. Each \c{midend} is intended to handle the contents of a single
  2299. puzzle window.
  2300. \H{midend-new} \cw{midend_new()}
  2301. \c midend *midend_new(frontend *fe, const game *ourgame,
  2302. \c const drawing_api *drapi, void *drhandle);
  2303. Allocates and returns a new mid-end structure.
  2304. The \c{fe} argument is stored in the mid-end. It will be used when
  2305. calling back to functions such as \cw{activate_timer()}
  2306. (\k{frontend-activate-timer}), and will be passed on to the back end
  2307. function \cw{colours()} (\k{backend-colours}).
  2308. The parameters \c{drapi} and \c{drhandle} are passed to
  2309. \cw{drawing_new()} (\k{drawing-new}) to construct a drawing object
  2310. which will be passed to the back end function \cw{redraw()}
  2311. (\k{backend-redraw}). Hence, all drawing-related function pointers
  2312. defined in \c{drapi} can expect to be called with \c{drhandle} as
  2313. their first argument.
  2314. The \c{ourgame} argument points to a container structure describing
  2315. a game back end. The mid-end thus created will only be capable of
  2316. handling that one game. (So even in a monolithic front end
  2317. containing all the games, this imposes the constraint that any
  2318. individual puzzle window is tied to a single game. Unless, of
  2319. course, you feel brave enough to change the mid-end for the window
  2320. without closing the window...)
  2321. \H{midend-free} \cw{midend_free()}
  2322. \c void midend_free(midend *me);
  2323. Frees a mid-end structure and all its associated data.
  2324. \H{midend-tilesize} \cw{midend_tilesize()}
  2325. \c int midend_tilesize(midend *me);
  2326. Returns the \cq{tilesize} parameter being used to display the
  2327. current puzzle (\k{backend-preferred-tilesize}).
  2328. \H{midend-set-params} \cw{midend_set_params()}
  2329. \c void midend_set_params(midend *me, game_params *params);
  2330. Sets the current game parameters for a mid-end. Subsequent games
  2331. generated by \cw{midend_new_game()} (\k{midend-new-game}) will use
  2332. these parameters until further notice.
  2333. The usual way in which the front end will have an actual
  2334. \c{game_params} structure to pass to this function is if it had
  2335. previously got it from \cw{midend_get_presets()}
  2336. (\k{midend-get-presets}). Thus, this function is usually called in
  2337. response to the user making a selection from the presets menu.
  2338. \H{midend-get-params} \cw{midend_get_params()}
  2339. \c game_params *midend_get_params(midend *me);
  2340. Returns the current game parameters stored in this mid-end.
  2341. The returned value is dynamically allocated, and should be freed
  2342. when finished with by passing it to the game's own
  2343. \cw{free_params()} function (see \k{backend-free-params}).
  2344. \H{midend-size} \cw{midend_size()}
  2345. \c void midend_size(midend *me, int *x, int *y,
  2346. \c bool user_size, double device_pixel_ratio);
  2347. Tells the mid-end to figure out its window size.
  2348. On input, \c{*x} and \c{*y} should contain the maximum or requested
  2349. size for the window. (Typically this will be the size of the screen
  2350. that the window has to fit on, or similar.) The mid-end will
  2351. repeatedly call the back end function \cw{compute_size()}
  2352. (\k{backend-compute-size}), searching for a tile size that best
  2353. satisfies the requirements. On exit, \c{*x} and \c{*y} will contain
  2354. the size needed for the puzzle window's drawing area. (It is of
  2355. course up to the front end to adjust this for any additional window
  2356. furniture such as menu bars and window borders, if necessary. The
  2357. status bar is also not included in this size.)
  2358. Use \c{user_size} to indicate whether \c{*x} and \c{*y} are a
  2359. requested size, or just a maximum size.
  2360. If \c{user_size} is set to \cw{true}, the mid-end will treat the
  2361. input size as a request, and will pick a tile size which
  2362. approximates it \e{as closely as possible}, going over the game's
  2363. preferred tile size if necessary to achieve this. The mid-end will
  2364. also use the resulting tile size as its preferred one until further
  2365. notice, on the assumption that this size was explicitly requested
  2366. by the user. Use this option if you want your front end to support
  2367. dynamic resizing of the puzzle window with automatic scaling of the
  2368. puzzle to fit.
  2369. If \c{user_size} is set to \cw{false}, then the game's tile size
  2370. will never go over its preferred one, although it may go under in
  2371. order to fit within the maximum bounds specified by \c{*x} and
  2372. \c{*y}. This is the recommended approach when opening a new window
  2373. at default size: the game will use its preferred size unless it has
  2374. to use a smaller one to fit on the screen. If the tile size is
  2375. shrunk for this reason, the change will not persist; if a smaller
  2376. grid is subsequently chosen, the tile size will recover.
  2377. The mid-end will try as hard as it can to return a size which is
  2378. less than or equal to the input size, in both dimensions. In extreme
  2379. circumstances it may fail (if even the lowest possible tile size
  2380. gives window dimensions greater than the input), in which case it
  2381. will return a size greater than the input size. Front ends should be
  2382. prepared for this to happen (i.e. don't crash or fail an assertion),
  2383. but may handle it in any way they see fit: by rejecting the game
  2384. parameters which caused the problem, by opening a window larger than
  2385. the screen regardless of inconvenience, by introducing scroll bars
  2386. on the window, by drawing on a large bitmap and scaling it into a
  2387. smaller window, or by any other means you can think of. It is likely
  2388. that when the tile size is that small the game will be unplayable
  2389. anyway, so don't put \e{too} much effort into handling it
  2390. creatively.
  2391. If your platform has no limit on window size (or if you're planning
  2392. to use scroll bars for large puzzles), you can pass dimensions of
  2393. \cw{INT_MAX} as input to this function. You should probably not do
  2394. that \e{and} set the \c{user_size} flag, though!
  2395. The \cw{device_pixel_ratio} allows the front end to specify that its
  2396. pixels are unusually large or small (or should be treated as such).
  2397. The mid-end uses this to adjust the tile size, both at startup (if the
  2398. ratio is not 1) and if the ratio changes.
  2399. A \cw{device_pixel_ratio} of 1 indicates normal-sized pixels.
  2400. \q{Normal} is not precisely defined, but it's about 4 pixels per
  2401. millimetre on a screen designed to be viewed from a metre away, or a
  2402. size such that text 15 pixels high is comfortably readable. Some
  2403. platforms have a concept of a logical pixel that this can be mapped
  2404. onto. For instance, Cascading Style Sheets (CSS) has a unit called
  2405. \cq{px} that only matches physical pixels at a \cw{device_pixel_ratio}
  2406. of 1.
  2407. The \cw{device_pixel_ratio} indicates the number of physical pixels in
  2408. a normal-sized pixel, so values less than 1 indicate unusually large
  2409. pixels and values greater than 1 indicate unusually small pixels.
  2410. The midend relies on the frontend calling \cw{midend_new_game()}
  2411. (\k{midend-new-game}) before calling \cw{midend_size()}.
  2412. \H{midend-reset-tilesize} \cw{midend_reset_tilesize()}
  2413. \c void midend_reset_tilesize(midend *me);
  2414. This function resets the midend's preferred tile size to that of the
  2415. standard puzzle.
  2416. As discussed in \k{midend-size}, puzzle resizes are typically
  2417. 'sticky', in that once the user has dragged the puzzle to a different
  2418. window size, the resulting tile size will be remembered and used when
  2419. the puzzle configuration changes. If you \e{don't} want that, e.g. if
  2420. you want to provide a command to explicitly reset the puzzle size back
  2421. to its default, then you can call this just before calling
  2422. \cw{midend_size()} (which, in turn, you would probably call with
  2423. \c{user_size} set to \cw{false}).
  2424. \H{midend-new-game} \cw{midend_new_game()}
  2425. \c void midend_new_game(midend *me);
  2426. Causes the mid-end to begin a new game. Normally the game will be a
  2427. new randomly generated puzzle. However, if you have previously
  2428. called \cw{midend_game_id()} or \cw{midend_set_config()}, the game
  2429. generated might be dictated by the results of those functions. (In
  2430. particular, you \e{must} call \cw{midend_new_game()} after calling
  2431. either of those functions, or else no immediate effect will be
  2432. visible.)
  2433. You will probably need to call \cw{midend_size()} after calling this
  2434. function, because if the game parameters have been changed since the
  2435. last new game then the window size might need to change. (If you
  2436. know the parameters \e{haven't} changed, you don't need to do this.)
  2437. This function will create a new \c{game_drawstate}, but does not
  2438. actually perform a redraw (since you often need to call
  2439. \cw{midend_size()} before the redraw can be done). So after calling
  2440. this function and after calling \cw{midend_size()}, you should then
  2441. call \cw{midend_redraw()}. (It is not necessary to call
  2442. \cw{midend_force_redraw()}; that will discard the draw state and
  2443. create a fresh one, which is unnecessary in this case since there's
  2444. a fresh one already. It would work, but it's usually excessive.)
  2445. \H{midend-restart-game} \cw{midend_restart_game()}
  2446. \c void midend_restart_game(midend *me);
  2447. This function causes the current game to be restarted. This is done
  2448. by placing a new copy of the original game state on the end of the
  2449. undo list (so that an accidental restart can be undone).
  2450. This function automatically causes a redraw, i.e. the front end can
  2451. expect its drawing API to be called from \e{within} a call to this
  2452. function. Some back ends require that \cw{midend_size()}
  2453. (\k{midend-size}) is called before \cw{midend_restart_game()}.
  2454. \H{midend-force-redraw} \cw{midend_force_redraw()}
  2455. \c void midend_force_redraw(midend *me);
  2456. Forces a complete redraw of the puzzle window, by means of
  2457. discarding the current \c{game_drawstate} and creating a new one
  2458. from scratch before calling the game's \cw{redraw()} function.
  2459. The front end can expect its drawing API to be called from within a
  2460. call to this function. Some back ends require that \cw{midend_size()}
  2461. (\k{midend-size}) is called before \cw{midend_force_redraw()}.
  2462. \H{midend-redraw} \cw{midend_redraw()}
  2463. \c void midend_redraw(midend *me);
  2464. Causes a partial redraw of the puzzle window, by means of simply
  2465. calling the game's \cw{redraw()} function. (That is, the only things
  2466. redrawn will be things that have changed since the last redraw.)
  2467. The front end can expect its drawing API to be called from within a
  2468. call to this function. Some back ends require that \cw{midend_size()}
  2469. (\k{midend-size}) is called before \cw{midend_redraw()}.
  2470. \H{midend-process-key} \cw{midend_process_key()}
  2471. \c int midend_process_key(midend *me, int x, int y, int button)
  2472. The front end calls this function to report a mouse or keyboard event.
  2473. The parameters \c{x} and \c{y} are identical to the ones passed to the
  2474. back end function \cw{interpret_move()} (\k{backend-interpret-move}).
  2475. \c{button} is similar to the parameter passed to
  2476. \cw{interpret_move()}. However, the midend is more relaxed about
  2477. values passed to in, and some additional special button values
  2478. are defined for the front end to pass to the midend (see below).
  2479. Also, the front end is \e{not} required to provide guarantees about
  2480. mouse event ordering. The mid-end will sort out multiple simultaneous
  2481. button presses and changes of button; the front end's responsibility
  2482. is simply to pass on the mouse events it receives as accurately as
  2483. possible.
  2484. (Some platforms may need to emulate absent mouse buttons by means of
  2485. using a modifier key such as Shift with another mouse button. This
  2486. tends to mean that if Shift is pressed or released in the middle of
  2487. a mouse drag, the mid-end will suddenly stop receiving, say,
  2488. \cw{LEFT_DRAG} events and start receiving \cw{RIGHT_DRAG}s, with no
  2489. intervening button release or press events. This too is something
  2490. which the mid-end will sort out for you; the front end has no
  2491. obligation to maintain sanity in this area.)
  2492. The front end \e{should}, however, always eventually send some kind
  2493. of button release. On some platforms this requires special effort:
  2494. Windows, for example, requires a call to the system API function
  2495. \cw{SetCapture()} in order to ensure that your window receives a
  2496. mouse-up event even if the pointer has left the window by the time
  2497. the mouse button is released. On any platform that requires this
  2498. sort of thing, the front end \e{is} responsible for doing it.
  2499. Calling this function is very likely to result in calls back to the
  2500. front end's drawing API and/or \cw{activate_timer()}
  2501. (\k{frontend-activate-timer}).
  2502. The return value from \cw{midend_process_key()} is one of the
  2503. following constants:
  2504. \dt \cw{PKR_QUIT}
  2505. \dd Means that the effect of the keypress was to request termination
  2506. of the program. A front end should shut down the puzzle in response
  2507. to a \cw{PKR_QUIT} return.
  2508. \dt \cw{PKR_SOME_EFFECT}
  2509. \dd The keypress had some other effect, either in the mid-end or in
  2510. the puzzle itself.
  2511. \dt \cw{PKR_NO_EFFECT}
  2512. \dd The keypress had no effect, but might have had an effect in
  2513. slightly different circumstances. For instance it requested a move
  2514. that wasn't possible.
  2515. \dt \cw{PKR_UNUSED}
  2516. \dd The key was one that neither the mid-end nor the back-end has any
  2517. use for at all.
  2518. A front end might respond to the last value by passing the key on to
  2519. something else that might be interested in it.
  2520. The following additional values of \c{button} are permitted to be
  2521. passed to this function by the front end, but are never passed on to
  2522. the back end. They indicate front-end specific UI operations, such as
  2523. selecting an option from a drop-down menu. (Otherwise the front end
  2524. would have to translate the \q{New Game} menu item into an \cq{n}
  2525. keypress, for example.)
  2526. \dt \cw{UI_NEWGAME}
  2527. \dd Indicates that the user requested a new game, similar to pressing
  2528. \cq{n}.
  2529. \dt \cw{UI_SOLVE}
  2530. \dd Indicates that the user requested the solution of the current game.
  2531. \dt \cw{UI_UNDO}
  2532. \dd Indicates that the user attempted to undo a move.
  2533. \dt \cw{UI_REDO}
  2534. \dd Indicates that the user attempted to redo an undone move.
  2535. \dt \cw{UI_QUIT}
  2536. \dd Indicates that the user asked to quit the game. (Of course, a
  2537. front end might perfectly well handle this on its own. But including
  2538. it in this enumeration allows the front end to treat all these menu
  2539. items the same, by translating each of them into a button code passed
  2540. to the midend, and handle quitting by noticing the \c{false} return
  2541. value from \cw{midend_process_key()}.)
  2542. The midend tolerates any modifier being set on any key and removes
  2543. them as necessary before passing the key on to the backend. It will
  2544. also handle translating printable characters combined with
  2545. \cw{MOD_CTRL} into control characters.
  2546. \H{midend-request-keys} \cw{midend_request_keys()}
  2547. \c key_label *midend_request_keys(midend *me, int *nkeys);
  2548. This function behaves similarly to the backend's \cw{request_keys()}
  2549. function (\k{backend-request-keys}). If the backend does not provide
  2550. \cw{request_keys()}, this function will return \cw{NULL} and set
  2551. \cw{*nkeys} to zero. Otherwise, this function will fill in the generic
  2552. labels (i.e. the \cw{key_label} items that have their \cw{label}
  2553. fields set to \cw{NULL}) by using \cw{button2label()}
  2554. (\k{utils-button2label}).
  2555. \H{midend-current-key-label} \cw{midend_current_key_label()}
  2556. \c const char *midend_current_key_label(midend *me, int button);
  2557. This is a thin wrapper around the backend's \cw{current_key_label()}
  2558. function (\k{backend-current-key-label}). Front ends that need to
  2559. label \cw{CURSOR_SELECT} or \cw{CURSOR_SELECT2} should call this
  2560. function after each move (at least after each call to
  2561. \cw{midend_process_key()}) to get the current labels. The front end
  2562. should arrange to copy the returned string somewhere before the next
  2563. call to the mid-end, just in case it's dynamically allocated. If the
  2564. button supplied does nothing, the label returned will be an empty
  2565. string.
  2566. \H{midend-colours} \cw{midend_colours()}
  2567. \c float *midend_colours(midend *me, int *ncolours);
  2568. Returns an array of the colours required by the game, in exactly the
  2569. same format as that returned by the back end function \cw{colours()}
  2570. (\k{backend-colours}). Front ends should call this function rather
  2571. than calling the back end's version directly, since the mid-end adds
  2572. standard customisation facilities. (At the time of writing, those
  2573. customisation facilities are implemented hackily by means of
  2574. environment variables, but it's not impossible that they may become
  2575. more full and formal in future.)
  2576. \H{midend-timer} \cw{midend_timer()}
  2577. \c void midend_timer(midend *me, float tplus);
  2578. If the mid-end has called \cw{activate_timer()}
  2579. (\k{frontend-activate-timer}) to request regular callbacks for
  2580. purposes of animation or timing, this is the function the front end
  2581. should call on a regular basis. The argument \c{tplus} gives the
  2582. time, in seconds, since the last time either this function was
  2583. called or \cw{activate_timer()} was invoked.
  2584. One of the major purposes of timing in the mid-end is to perform
  2585. move animation. Therefore, calling this function is very likely to
  2586. result in calls back to the front end's drawing API.
  2587. \H{midend-get-presets} \cw{midend_get_presets()}
  2588. \c struct preset_menu *midend_get_presets(midend *me, int *id_limit);
  2589. Returns a data structure describing this game's collection of preset
  2590. game parameters, organised into a hierarchical structure of menus and
  2591. submenus.
  2592. The return value is a pointer to a data structure containing the
  2593. following fields (among others, which are not intended for front end
  2594. use):
  2595. \c struct preset_menu {
  2596. \c int n_entries;
  2597. \c struct preset_menu_entry *entries;
  2598. \c /* and other things */
  2599. \e iiiiiiiiiiiiiiiiiiiiii
  2600. \c };
  2601. Those fields describe the intended contents of one particular menu in
  2602. the hierarchy. \cq{entries} points to an array of \cq{n_entries}
  2603. items, each of which is a structure containing the following fields:
  2604. \c struct preset_menu_entry {
  2605. \c char *title;
  2606. \c game_params *params;
  2607. \c struct preset_menu *submenu;
  2608. \c int id;
  2609. \c };
  2610. Of these fields, \cq{title} and \cq{id} are present in every entry,
  2611. giving (respectively) the textual name of the menu item and an integer
  2612. identifier for it. The integer id will correspond to the one returned
  2613. by \c{midend_which_preset} (\k{midend-which-preset}), when that preset
  2614. is the one selected.
  2615. The other two fields are mutually exclusive. Each \c{struct
  2616. preset_menu_entry} will have one of those fields \cw{NULL} and the
  2617. other one non-null. If the menu item is an actual preset, then
  2618. \cq{params} will point to the set of game parameters that go with the
  2619. name; if it's a submenu, then \cq{submenu} instead will be non-null,
  2620. and will point at a subsidiary \c{struct preset_menu}.
  2621. The complete hierarchy of these structures is owned by the mid-end,
  2622. and will be freed when the mid-end is freed. The front end should not
  2623. attempt to free any of it.
  2624. The integer identifiers will be allocated densely from 0 upwards, so
  2625. that it's reasonable for the front end to allocate an array which uses
  2626. them as indices, if it needs to store information per preset menu
  2627. item. For this purpose, the front end may pass the second parameter
  2628. \cq{id_limit} to \cw{midend_get_presets} as the address of an \c{int}
  2629. variable, into which \cw{midend_get_presets} will write an integer one
  2630. larger than the largest id number actually used (i.e. the number of
  2631. elements the front end would need in the array).
  2632. Submenu-type entries also have integer identifiers.
  2633. \H{midend-which-preset} \cw{midend_which_preset()}
  2634. \c int midend_which_preset(midend *me);
  2635. Returns the numeric index of the preset game parameter structure
  2636. which matches the current game parameters, or a negative number if
  2637. no preset matches. Front ends could use this to maintain a tick
  2638. beside one of the items in the menu (or tick the \q{Custom} option
  2639. if the return value is less than zero).
  2640. The returned index value (if non-negative) will match the \c{id} field
  2641. of the corresponding \cw{struct preset_menu_entry} returned by
  2642. \c{midend_get_presets()} (\k{midend-get-presets}).
  2643. \H{midend-wants-statusbar} \cw{midend_wants_statusbar()}
  2644. \c bool midend_wants_statusbar(midend *me);
  2645. This function returns \cw{true} if the puzzle has a use for a
  2646. textual status line (to display score, completion status, currently
  2647. active tiles, time, or anything else).
  2648. Front ends should call this function rather than talking directly to
  2649. the back end.
  2650. \H{midend-get-config} \cw{midend_get_config()}
  2651. \c config_item *midend_get_config(midend *me, int which,
  2652. \c char **wintitle);
  2653. Returns a dialog box description for user configuration.
  2654. On input, \cw{which} should be set to one of three values, which
  2655. select which of the various dialog box descriptions is returned:
  2656. \dt \cw{CFG_SETTINGS}
  2657. \dd Requests the GUI parameter configuration box generated by the
  2658. puzzle itself. This should be used when the user selects \q{Custom}
  2659. from the game types menu (or equivalent). The mid-end passes this
  2660. request on to the back end function \cw{configure()}
  2661. (\k{backend-configure}).
  2662. \dt \cw{CFG_DESC}
  2663. \dd Requests a box suitable for entering a descriptive game ID (and
  2664. viewing the existing one). The mid-end generates this dialog box
  2665. description itself. This should be used when the user selects
  2666. \q{Specific} from the game menu (or equivalent).
  2667. \dt \cw{CFG_SEED}
  2668. \dd Requests a box suitable for entering a random-seed game ID (and
  2669. viewing the existing one). The mid-end generates this dialog box
  2670. description itself. This should be used when the user selects
  2671. \q{Random Seed} from the game menu (or equivalent).
  2672. \dt \cw{CFG_PREFS}
  2673. \dd Requests a box suitable for configuring user preferences.
  2674. (An additional value \cw{CFG_FRONTEND_SPECIFIC} is provided in this
  2675. enumeration, so that frontends can extend it for their own internal
  2676. use. For example, you might wrap this function with a
  2677. \cw{frontend_get_config} which handles some values of \c{which} itself
  2678. and hands others on to the midend, depending on whether \cw{which <
  2679. CFG_FRONTEND_SPECIFIC}.)
  2680. The returned value is an array of \cw{config_item}s, exactly as
  2681. described in \k{backend-configure}. Another returned value is an
  2682. ASCII string giving a suitable title for the configuration window,
  2683. in \c{*wintitle}.
  2684. Both returned values are dynamically allocated and will need to be
  2685. freed. The window title can be freed in the obvious way; the
  2686. \cw{config_item} array is a slightly complex structure, so a utility
  2687. function \cw{free_cfg()} is provided to free it for you. See
  2688. \k{utils-free-cfg}.
  2689. (Of course, you will probably not want to free the \cw{config_item}
  2690. array until the dialog box is dismissed, because before then you
  2691. will probably need to pass it to \cw{midend_set_config}.)
  2692. \H{midend-set-config} \cw{midend_set_config()}
  2693. \c const char *midend_set_config(midend *me, int which,
  2694. \c config_item *cfg);
  2695. Passes the mid-end the results of a configuration dialog box.
  2696. \c{which} should have the same value which it had when
  2697. \cw{midend_get_config()} was called; \c{cfg} should be the array of
  2698. \c{config_item}s returned from \cw{midend_get_config()}, modified to
  2699. contain the results of the user's editing operations.
  2700. This function returns \cw{NULL} on success, or otherwise (if the
  2701. configuration data was in some way invalid) an ASCII string
  2702. containing an error message suitable for showing to the user.
  2703. If the function succeeds, it is likely that the game parameters will
  2704. have been changed and it is certain that a new game will be
  2705. requested. The front end should therefore call
  2706. \cw{midend_new_game()}, and probably also re-think the window size
  2707. using \cw{midend_size()} and eventually perform a refresh using
  2708. \cw{midend_redraw()}.
  2709. \H{midend-game-id} \cw{midend_game_id()}
  2710. \c const char *midend_game_id(midend *me, const char *id);
  2711. Passes the mid-end a string game ID (of any of the valid forms
  2712. \cq{params}, \cq{params:description} or \cq{params#seed}) which the
  2713. mid-end will process and use for the next generated game.
  2714. This function returns \cw{NULL} on success, or otherwise (if the
  2715. configuration data was in some way invalid) an ASCII string
  2716. containing an error message (not dynamically allocated) suitable for
  2717. showing to the user. In the event of an error, the mid-end's
  2718. internal state will be left exactly as it was before the call.
  2719. If the function succeeds, it is likely that the game parameters will
  2720. have been changed and it is certain that a new game will be
  2721. requested. The front end should therefore call
  2722. \cw{midend_new_game()}, and probably also re-think the window size
  2723. using \cw{midend_size()} and eventually case a refresh using
  2724. \cw{midend_redraw()}.
  2725. \H{midend-get-game-id} \cw{midend_get_game_id()}
  2726. \c char *midend_get_game_id(midend *me);
  2727. Returns a descriptive game ID (i.e. one in the form
  2728. \cq{params:description}) describing the game currently active in the
  2729. mid-end. The returned string is dynamically allocated.
  2730. \H{midend-get-random-seed} \cw{midend_get_random_seed()}
  2731. \c char *midend_get_random_seed(midend *me);
  2732. Returns a random game ID (i.e. one in the form \cq{params#seedstring})
  2733. describing the game currently active in the mid-end, if there is one.
  2734. If the game was created by entering a description, no random seed will
  2735. currently exist and this function will return \cw{NULL}.
  2736. The returned string, if it is non-\cw{NULL}, is dynamically allocated.
  2737. Unlike the descriptive game ID, the random seed can contain characters
  2738. outside the printable ASCII set.
  2739. \H{midend-can-format-as-text-now} \cw{midend_can_format_as_text_now()}
  2740. \c bool midend_can_format_as_text_now(midend *me);
  2741. Returns \cw{true} if the game code is capable of formatting puzzles
  2742. of the currently selected game type as ASCII.
  2743. If this returns \cw{false}, then \cw{midend_text_format()}
  2744. (\k{midend-text-format}) will return \cw{NULL}.
  2745. \H{midend-text-format} \cw{midend_text_format()}
  2746. \c char *midend_text_format(midend *me);
  2747. Formats the current game's current state as ASCII text suitable for
  2748. copying to the clipboard. The returned string is dynamically
  2749. allocated.
  2750. If the game's \c{can_format_as_text_ever} flag is \cw{false}, or if
  2751. its \cw{can_format_as_text_now()} function returns \cw{false}, then
  2752. this function will return \cw{NULL}.
  2753. If the returned string contains multiple lines (which is likely), it
  2754. will use the normal C line ending convention (\cw{\\n} only). On
  2755. platforms which use a different line ending convention for data in
  2756. the clipboard, it is the front end's responsibility to perform the
  2757. conversion.
  2758. \H{midend-solve} \cw{midend_solve()}
  2759. \c const char *midend_solve(midend *me);
  2760. Requests the mid-end to perform a Solve operation.
  2761. On success, \cw{NULL} is returned. On failure, an error message (not
  2762. dynamically allocated) is returned, suitable for showing to the
  2763. user.
  2764. The front end can expect its drawing API and/or
  2765. \cw{activate_timer()} to be called from within a call to this
  2766. function. Some back ends require that \cw{midend_size()}
  2767. (\k{midend-size}) is called before \cw{midend_solve()}.
  2768. \H{midend-get-cursor-location} \cw{midend_get_cursor_location()}
  2769. \c bool midend_get_cursor_location(midend *me,
  2770. \c int *x, int *y,
  2771. \c int *w, int *h);
  2772. This function requests the location of the back end's on-screen cursor
  2773. or other region of interest.
  2774. What exactly this region contains is up to the backend, but in general
  2775. the region will be an area that the player is controlling with the
  2776. cursor keys \dash such as the player location in Cube and Inertia, or
  2777. the cursor in any of the conventional grid-based games. With knowledge
  2778. of this location, a front end can, for example, ensure that the region
  2779. of interest remains visible even if the entire puzzle is too big to
  2780. fit on the screen.
  2781. On success, this function returns \cw{true}, and the locations pointed
  2782. to by \cw{x}, \cw{y}, \cw{w} and \cw{h} are updated to describe the
  2783. cursor region, which has an upper-left corner located at \cw{(*x,*y)}
  2784. and a size of \cw{*w} pixels wide by \cw{*h} pixels tall. The caller
  2785. may pass \cw{NULL} for any number of these pointers, which will be
  2786. ignored.
  2787. On failure, this function returns \cw{false}. Failure can occur if
  2788. there is currently no active cursor region, or if the back end lacks
  2789. cursor support.
  2790. \H{midend-status} \cw{midend_status()}
  2791. \c int midend_status(midend *me);
  2792. This function returns +1 if the midend is currently displaying a game
  2793. in a solved state, -1 if the game is in a permanently lost state, or 0
  2794. otherwise. This function just calls the back end's \cw{status()}
  2795. function. Front ends may wish to use this as a cue to proactively
  2796. offer the option of starting a new game.
  2797. (See \k{backend-status} for more detail about the back end's
  2798. \cw{status()} function and discussion of what should count as which
  2799. status code.)
  2800. \H{midend-can-undo} \cw{midend_can_undo()}
  2801. \c bool midend_can_undo(midend *me);
  2802. Returns \cw{true} if the midend is currently in a state where the undo
  2803. operation is meaningful (i.e. at least one position exists on the undo
  2804. chain before the present one). Front ends may wish to use this to
  2805. visually activate and deactivate an undo button.
  2806. \H{midend-can-redo} \cw{midend_can_redo()}
  2807. \c bool midend_can_redo(midend *me);
  2808. Returns \cw{true} if the midend is currently in a state where the redo
  2809. operation is meaningful (i.e. at least one position exists on the redo
  2810. chain after the present one). Front ends may wish to use this to
  2811. visually activate and deactivate a redo button.
  2812. \H{midend-serialise} \cw{midend_serialise()}
  2813. \c void midend_serialise(midend *me,
  2814. \c void (*write)(void *ctx, const void *buf, int len), void *wctx);
  2815. Calling this function causes the mid-end to convert its entire
  2816. internal state into a long ASCII text string, and to pass that
  2817. string (piece by piece) to the supplied \c{write} function.
  2818. The string will consist of printable ASCII characters and line
  2819. feeds.
  2820. Desktop implementations can use this function to save a game in any
  2821. state (including half-finished) to a disk file, by supplying a
  2822. \c{write} function which is a wrapper on \cw{fwrite()} (or local
  2823. equivalent). Other implementations may find other uses for it, such
  2824. as compressing the large and sprawling mid-end state into a
  2825. manageable amount of memory when a palmtop application is suspended
  2826. so that another one can run; in this case \cw{write} might want to
  2827. write to a memory buffer rather than a file. There may be other uses
  2828. for it as well.
  2829. This function will call back to the supplied \c{write} function a
  2830. number of times, with the first parameter (\c{ctx}) equal to
  2831. \c{wctx}, and the other two parameters pointing at a piece of the
  2832. output string.
  2833. \H{midend-deserialise} \cw{midend_deserialise()}
  2834. \c const char *midend_deserialise(midend *me,
  2835. \c bool (*read)(void *ctx, void *buf, int len), void *rctx);
  2836. This function is the counterpart to \cw{midend_serialise()}. It
  2837. calls the supplied \cw{read} function repeatedly to read a quantity
  2838. of data, and attempts to interpret that data as a serialised mid-end
  2839. as output by \cw{midend_serialise()}.
  2840. The \cw{read} function is called with the first parameter (\c{ctx})
  2841. equal to \c{rctx}, and should attempt to read \c{len} bytes of data
  2842. into the buffer pointed to by \c{buf}. It should return \cw{false}
  2843. on failure or \cw{true} on success. It should not report success
  2844. unless it has filled the entire buffer; on platforms which might be
  2845. reading from a pipe or other blocking data source, \c{read} is
  2846. responsible for looping until the whole buffer has been filled.
  2847. If the de-serialisation operation is successful, the mid-end's
  2848. internal data structures will be replaced by the results of the
  2849. load, and \cw{NULL} will be returned. Otherwise, the mid-end's state
  2850. will be completely unchanged and an error message (typically some
  2851. variation on \q{save file is corrupt}) will be returned. As usual,
  2852. the error message string is not dynamically allocated.
  2853. If this function succeeds, it is likely that the game parameters
  2854. will have been changed. The front end should therefore probably
  2855. re-think the window size using \cw{midend_size()}, and probably
  2856. cause a refresh using \cw{midend_redraw()}.
  2857. Because each mid-end is tied to a specific game back end, this
  2858. function will fail if you attempt to read in a save file generated by
  2859. a different game from the one configured in this mid-end, even if your
  2860. application is a monolithic one containing all the puzzles. See
  2861. \k{identify-game} for a helper function which will allow you to
  2862. identify a save file before you instantiate your mid-end in the first
  2863. place.
  2864. \H{midend-save-prefs} \cw{midend_save_prefs()}
  2865. \c void midend_save_prefs(
  2866. \c midend *me, void (*write)(void *ctx, const void *buf, int len),
  2867. \c void *wctx);
  2868. Calling this function causes the mid-end to write out the states of
  2869. all user-settable preference options, including its own cross-platform
  2870. preferences and ones exported by a particular game via
  2871. \cw{get_prefs()} and \cw{set_prefs()} (\k{backend-get-prefs},
  2872. \k{backend-set-prefs}). The output is a textual format suitable for
  2873. writing into a configuration file on disk.
  2874. The \c{write} and \c{wctx} parameters have the same semantics as for
  2875. \cw{midend_serialise()} (\k{midend-serialise}).
  2876. \H{midend-load-prefs} \cw{midend_load_prefs()}
  2877. \c const char *midend_load_prefs(
  2878. \c midend *me, bool (*read)(void *ctx, void *buf, int len),
  2879. \c void *rctx);
  2880. This function is used to load a configuration file in the same format
  2881. emitted by \cw{midend_save_prefs()}, and import all the preferences
  2882. described in the file into the current mid-end.
  2883. \H{identify-game} \cw{identify_game()}
  2884. \c const char *identify_game(char **name,
  2885. \c bool (*read)(void *ctx, void *buf, int len), void *rctx);
  2886. This function examines a serialised midend stream, of the same kind
  2887. used by \cw{midend_serialise()} and \cw{midend_deserialise()}, and
  2888. returns the \cw{name} field of the game back end from which it was
  2889. saved.
  2890. You might want this if your front end was a monolithic one containing
  2891. all the puzzles, and you wanted to be able to load an arbitrary save
  2892. file and automatically switch to the right game. Probably your next
  2893. step would be to iterate through \cw{gamelist} (\k{frontend-backend})
  2894. looking for a game structure whose \cw{name} field matched the
  2895. returned string, and give an error if you didn't find one.
  2896. On success, the return value of this function is \cw{NULL}, and the
  2897. game name string is written into \cw{*name}. The caller should free
  2898. that string after using it.
  2899. On failure, \cw{*name} is \cw{NULL}, and the return value is an error
  2900. message (which does not need freeing at all).
  2901. (This isn't strictly speaking a midend function, since it doesn't
  2902. accept or return a pointer to a midend. You'd probably call it just
  2903. \e{before} deciding what kind of midend you wanted to instantiate.)
  2904. \H{midend-request-id-changes} \cw{midend_request_id_changes()}
  2905. \c void midend_request_id_changes(midend *me,
  2906. \c void (*notify)(void *), void *ctx);
  2907. This function is called by the front end to request notification by
  2908. the mid-end when the current game IDs (either descriptive or
  2909. random-seed) change. This can occur as a result of keypresses ('n' for
  2910. New Game, for example) or when a puzzle supersedes its game
  2911. description (see \k{backend-supersede}). After this function is
  2912. called, any change of the game ids will cause the mid-end to call
  2913. \cw{notify(ctx)} after the change.
  2914. This is for use by puzzles which want to present the game description
  2915. to the user constantly (e.g. as an HTML hyperlink) instead of only
  2916. showing it when the user explicitly requests it.
  2917. This is a function I anticipate few front ends needing to implement,
  2918. so I make it a callback rather than a static function in order to
  2919. relieve most front ends of the need to provide an empty
  2920. implementation.
  2921. \H{midend-which-game} \cw{midend_which_game()}
  2922. \c const game *midend_which_preset(midend *me);
  2923. This function returns the \c{game} structure for the puzzle type this
  2924. midend is committed to.
  2925. \H{frontend-backend} Direct reference to the back end structure by
  2926. the front end
  2927. Although \e{most} things the front end needs done should be done by
  2928. calling the mid-end, there are a few situations in which the front
  2929. end needs to refer directly to the game back end structure.
  2930. The most obvious of these is
  2931. \b passing the game back end as a parameter to \cw{midend_new()}.
  2932. There are a few other back end features which are not wrapped by the
  2933. mid-end because there didn't seem much point in doing so:
  2934. \b fetching the \c{name} field to use in window titles and similar
  2935. \b reading the \c{can_configure}, \c{can_solve} and
  2936. \c{can_format_as_text_ever} fields to decide whether to add those
  2937. items to the menu bar or equivalent
  2938. \b reading the \c{winhelp_topic} field (Windows only)
  2939. \b the GTK front end provides a \cq{--generate} command-line option
  2940. which directly calls the back end to do most of its work. This is
  2941. not really part of the main front end code, though, and I'm not sure
  2942. it counts.
  2943. In order to find the game back end structure, the front end does one
  2944. of two things:
  2945. \b If the particular front end is compiling a separate binary per
  2946. game, then the back end structure is a global variable with the
  2947. standard name \cq{thegame}:
  2948. \lcont{
  2949. \c extern const game thegame;
  2950. }
  2951. \b If the front end is compiled as a monolithic application
  2952. containing all the puzzles together (in which case the preprocessor
  2953. symbol \cw{COMBINED} must be defined when compiling most of the code
  2954. base), then there will be two global variables defined:
  2955. \lcont{
  2956. \c extern const game *gamelist[];
  2957. \c extern const int gamecount;
  2958. \c{gamelist} will be an array of \c{gamecount} game structures,
  2959. declared in the automatically constructed source module \c{list.c}.
  2960. The application should search that array for the game it wants,
  2961. probably by reaching into each game structure and looking at its
  2962. \c{name} field.
  2963. }
  2964. \H{frontend-api} Mid-end to front-end calls
  2965. This section describes the small number of functions which a front
  2966. end must provide to be called by the mid-end or other standard
  2967. utility modules.
  2968. \H{frontend-get-random-seed} \cw{get_random_seed()}
  2969. \c void get_random_seed(void **randseed, int *randseedsize);
  2970. This function is called by a new mid-end, and also occasionally by
  2971. game back ends. Its job is to return a piece of data suitable for
  2972. using as a seed for initialisation of a new \c{random_state}.
  2973. On exit, \c{*randseed} should be set to point at a newly allocated
  2974. piece of memory containing some seed data, and \c{*randseedsize}
  2975. should be set to the length of that data.
  2976. A simple and entirely adequate implementation is to return a piece
  2977. of data containing the current system time at the highest
  2978. conveniently available resolution.
  2979. \H{frontend-activate-timer} \cw{activate_timer()}
  2980. \c void activate_timer(frontend *fe);
  2981. This is called by the mid-end to request that the front end begin
  2982. calling it back at regular intervals.
  2983. The timeout interval is left up to the front end; the finer it is,
  2984. the smoother move animations will be, but the more CPU time will be
  2985. used. Current front ends use values around 20ms (i.e. 50Hz).
  2986. After this function is called, the mid-end will expect to receive
  2987. calls to \cw{midend_timer()} on a regular basis.
  2988. \H{frontend-deactivate-timer} \cw{deactivate_timer()}
  2989. \c void deactivate_timer(frontend *fe);
  2990. This is called by the mid-end to request that the front end stop
  2991. calling \cw{midend_timer()}.
  2992. \H{frontend-fatal} \cw{fatal()}
  2993. \c void fatal(const char *fmt, ...);
  2994. This is called by some utility functions if they encounter a
  2995. genuinely fatal error such as running out of memory. It is a
  2996. variadic function in the style of \cw{printf()}, and is expected to
  2997. show the formatted error message to the user any way it can and then
  2998. terminate the application. It must not return.
  2999. \H{frontend-default-colour} \cw{frontend_default_colour()}
  3000. \c void frontend_default_colour(frontend *fe, float *output);
  3001. This function expects to be passed a pointer to an array of three
  3002. \cw{float}s. It returns the platform's local preferred background
  3003. colour in those three floats, as red, green and blue values (in that
  3004. order) ranging from \cw{0.0} to \cw{1.0}.
  3005. This function should only ever be called by the back end function
  3006. \cw{colours()} (\k{backend-colours}). (Thus, it isn't a
  3007. \e{midend}-to-frontend function as such, but there didn't seem to be
  3008. anywhere else particularly good to put it. Sorry.)
  3009. \C{utils} Utility APIs
  3010. This chapter documents a variety of utility APIs provided for the
  3011. general use of the rest of the Puzzles code.
  3012. \H{utils-random} Random number generation
  3013. Platforms' local random number generators vary widely in quality and
  3014. seed size. Puzzles therefore supplies its own high-quality random
  3015. number generator, with the additional advantage of giving the same
  3016. results if fed the same seed data on different platforms. This
  3017. allows game random seeds to be exchanged between different ports of
  3018. Puzzles and still generate the same games.
  3019. Unlike the ANSI C \cw{rand()} function, the Puzzles random number
  3020. generator has an \e{explicit} state object called a
  3021. \c{random_state}. One of these is managed by each mid-end, for
  3022. example, and passed to the back end to generate a game with.
  3023. \S{utils-random-init} \cw{random_new()}
  3024. \c random_state *random_new(char *seed, int len);
  3025. Allocates, initialises and returns a new \c{random_state}. The input
  3026. data is used as the seed for the random number stream (i.e. using
  3027. the same seed at a later time will generate the same stream).
  3028. The seed data can be any data at all; there is no requirement to use
  3029. printable ASCII, or NUL-terminated strings, or anything like that.
  3030. \S{utils-random-copy} \cw{random_copy()}
  3031. \c random_state *random_copy(random_state *tocopy);
  3032. Allocates a new \c{random_state}, copies the contents of another
  3033. \c{random_state} into it, and returns the new state. If exactly the
  3034. same sequence of functions is subsequently called on both the copy and
  3035. the original, the results will be identical. This may be useful for
  3036. speculatively performing some operation using a given random state,
  3037. and later replaying that operation precisely.
  3038. \S{utils-random-free} \cw{random_free()}
  3039. \c void random_free(random_state *state);
  3040. Frees a \c{random_state}.
  3041. \S{utils-random-bits} \cw{random_bits()}
  3042. \c unsigned long random_bits(random_state *state, int bits);
  3043. Returns a random number from 0 to \cw{2^bits-1} inclusive. \c{bits}
  3044. should be between 1 and 32 inclusive.
  3045. \S{utils-random-upto} \cw{random_upto()}
  3046. \c unsigned long random_upto(random_state *state, unsigned long limit);
  3047. Returns a random number from 0 to \cw{limit-1} inclusive. \c{limit}
  3048. may not be zero.
  3049. \S{utils-random-state-encode} \cw{random_state_encode()}
  3050. \c char *random_state_encode(random_state *state);
  3051. Encodes the entire contents of a \c{random_state} in printable
  3052. ASCII. Returns a dynamically allocated string containing that
  3053. encoding. This can subsequently be passed to
  3054. \cw{random_state_decode()} to reconstruct the same \c{random_state}.
  3055. \S{utils-random-state-decode} \cw{random_state_decode()}
  3056. \c random_state *random_state_decode(char *input);
  3057. Decodes a string generated by \cw{random_state_encode()} and
  3058. reconstructs an equivalent \c{random_state} to the one encoded, i.e.
  3059. it should produce the same stream of random numbers.
  3060. This function has no error reporting; if you pass it an invalid
  3061. string it will simply generate an arbitrary random state, which may
  3062. turn out to be noticeably non-random.
  3063. \S{utils-shuffle} \cw{shuffle()}
  3064. \c void shuffle(void *array, int nelts, int eltsize, random_state *rs);
  3065. Shuffles an array into a random order. The interface is much like
  3066. ANSI C \cw{qsort()}, except that there's no need for a compare
  3067. function.
  3068. \c{array} is a pointer to the first element of the array. \c{nelts}
  3069. is the number of elements in the array; \c{eltsize} is the size of a
  3070. single element (typically measured using \c{sizeof}). \c{rs} is a
  3071. \c{random_state} used to generate all the random numbers for the
  3072. shuffling process.
  3073. \H{utils-presets} Presets menu management
  3074. The function \c{midend_get_presets()} (\k{midend-get-presets}) returns
  3075. a data structure describing a menu hierarchy. Back ends can also
  3076. choose to provide such a structure to the mid-end, if they want to
  3077. group their presets hierarchically. To make this easy, there are a few
  3078. utility functions to construct preset menu structures, and also one
  3079. intended for front-end use.
  3080. \S{utils-preset-menu-new} \cw{preset_menu_new()}
  3081. \c struct preset_menu *preset_menu_new(void);
  3082. Allocates a new \c{struct preset_menu}, and initialises it to hold no
  3083. menu items.
  3084. \S{utils-preset-menu-add_submenu} \cw{preset_menu_add_submenu()}
  3085. \c struct preset_menu *preset_menu_add_submenu
  3086. \c (struct preset_menu *parent, char *title);
  3087. Adds a new submenu to the end of an existing preset menu, and returns
  3088. a pointer to a newly allocated \c{struct preset_menu} describing the
  3089. submenu.
  3090. The string parameter \cq{title} must be dynamically allocated by the
  3091. caller. The preset-menu structure will take ownership of it, so the
  3092. caller must not free it.
  3093. \S{utils-preset-menu-add-preset} \cw{preset_menu_add_preset()}
  3094. \c void preset_menu_add_preset
  3095. \c (struct preset_menu *menu, char *title, game_params *params);
  3096. Adds a preset game configuration to the end of a preset menu.
  3097. Both the string parameter \cq{title} and the game parameter structure
  3098. \cq{params} itself must be dynamically allocated by the caller. The
  3099. preset-menu structure will take ownership of it, so the caller must
  3100. not free it.
  3101. \S{utils-preset-menu-lookup-by-id} \cw{preset_menu_lookup_by_id()}
  3102. \c game_params *preset_menu_lookup_by_id
  3103. \c (struct preset_menu *menu, int id);
  3104. Given a numeric index, searches recursively through a preset menu
  3105. hierarchy to find the corresponding menu entry, and returns a pointer
  3106. to its existing \c{game_params} structure.
  3107. This function is intended for front end use (but front ends need not
  3108. use it if they prefer to do things another way). If a front end finds
  3109. it inconvenient to store anything more than a numeric index alongside
  3110. each menu item, then this function provides an easy way for the front
  3111. end to get back the actual game parameters corresponding to a menu
  3112. item that the user has selected.
  3113. \H{utils-alloc} Memory allocation
  3114. Puzzles has some central wrappers on the standard memory allocation
  3115. functions, which provide compile-time type checking, and run-time
  3116. error checking by means of quitting the application if it runs out
  3117. of memory. This doesn't provide the best possible recovery from
  3118. memory shortage, but on the other hand it greatly simplifies the
  3119. rest of the code, because nothing else anywhere needs to worry about
  3120. \cw{NULL} returns from allocation.
  3121. \S{utils-snew} \cw{snew()}
  3122. \c var = snew(type);
  3123. \e iii iiii
  3124. This macro takes a single argument which is a \e{type name}. It
  3125. allocates space for one object of that type. If allocation fails it
  3126. will call \cw{fatal()} and not return; so if it does return, you can
  3127. be confident that its return value is non-\cw{NULL}.
  3128. The return value is cast to the specified type, so that the compiler
  3129. will type-check it against the variable you assign it into. Thus,
  3130. this ensures you don't accidentally allocate memory the size of the
  3131. wrong type and assign it into a variable of the right one (or vice
  3132. versa!).
  3133. \S{utils-snewn} \cw{snewn()}
  3134. \c var = snewn(n, type);
  3135. \e iii i iiii
  3136. This macro is the array form of \cw{snew()}. It takes two arguments;
  3137. the first is a number, and the second is a type name. It allocates
  3138. space for that many objects of that type, and returns a type-checked
  3139. non-\cw{NULL} pointer just as \cw{snew()} does.
  3140. \S{utils-sresize} \cw{sresize()}
  3141. \c var = sresize(var, n, type);
  3142. \e iii iii i iiii
  3143. This macro is a type-checked form of \cw{realloc()}. It takes three
  3144. arguments: an input memory block, a new size in elements, and a
  3145. type. It re-sizes the input memory block to a size sufficient to
  3146. contain that many elements of that type. It returns a type-checked
  3147. non-\cw{NULL} pointer, like \cw{snew()} and \cw{snewn()}.
  3148. The input memory block can be \cw{NULL}, in which case this function
  3149. will behave exactly like \cw{snewn()}. (In principle any
  3150. ANSI-compliant \cw{realloc()} implementation ought to cope with
  3151. this, but I've never quite trusted it to work everywhere.)
  3152. \S{utils-sfree} \cw{sfree()}
  3153. \c void sfree(void *p);
  3154. This function is pretty much equivalent to \cw{free()}. It is
  3155. provided with a dynamically allocated block, and frees it.
  3156. The input memory block can be \cw{NULL}, in which case this function
  3157. will do nothing. (In principle any ANSI-compliant \cw{free()}
  3158. implementation ought to cope with this, but I've never quite trusted
  3159. it to work everywhere.)
  3160. \S{utils-dupstr} \cw{dupstr()}
  3161. \c char *dupstr(const char *s);
  3162. This function dynamically allocates a duplicate of a C string. Like
  3163. the \cw{snew()} functions, it guarantees to return non-\cw{NULL} or
  3164. not return at all.
  3165. (Many platforms provide the function \cw{strdup()}. As well as
  3166. guaranteeing never to return \cw{NULL}, my version has the advantage
  3167. of being defined \e{everywhere}, rather than inconveniently not
  3168. quite everywhere.)
  3169. \S{utils-free-cfg} \cw{free_cfg()}
  3170. \c void free_cfg(config_item *cfg);
  3171. This function correctly frees an array of \c{config_item}s, including
  3172. walking the array until it gets to the end and freeing any subsidiary
  3173. data items in each \c{u} sub-union which are expected to be
  3174. dynamically allocated.
  3175. (See \k{backend-configure} for details of the \c{config_item}
  3176. structure.)
  3177. \S{utils-free-keys} \cw{free_keys()}
  3178. \c void free_keys(key_label *keys, int nkeys);
  3179. This function correctly frees an array of \c{key_label}s, including
  3180. the dynamically allocated label string for each key.
  3181. (See \k{backend-request-keys} for details of the \c{key_label}
  3182. structure.)
  3183. \H{utils-tree234} Sorted and counted tree functions
  3184. Many games require complex algorithms for generating random puzzles,
  3185. and some require moderately complex algorithms even during play. A
  3186. common requirement during these algorithms is for a means of
  3187. maintaining sorted or unsorted lists of items, such that items can
  3188. be removed and added conveniently.
  3189. For general use, Puzzles provides the following set of functions
  3190. which maintain 2-3-4 trees in memory. (A 2-3-4 tree is a balanced
  3191. tree structure, with the property that all lookups, insertions,
  3192. deletions, splits and joins can be done in \cw{O(log N)} time.)
  3193. All these functions expect you to be storing a tree of \c{void *}
  3194. pointers. You can put anything you like in those pointers.
  3195. By the use of per-node element counts, these tree structures have
  3196. the slightly unusual ability to look elements up by their numeric
  3197. index within the list represented by the tree. This means that they
  3198. can be used to store an unsorted list (in which case, every time you
  3199. insert a new element, you must explicitly specify the position where
  3200. you wish to insert it). They can also do numeric lookups in a sorted
  3201. tree, which might be useful for (for example) tracking the median of
  3202. a changing data set.
  3203. As well as storing sorted lists, these functions can be used for
  3204. storing \q{maps} (associative arrays), by defining each element of a
  3205. tree to be a (key, value) pair.
  3206. \S{utils-newtree234} \cw{newtree234()}
  3207. \c tree234 *newtree234(cmpfn234 cmp);
  3208. Creates a new empty tree, and returns a pointer to it.
  3209. The parameter \c{cmp} determines the sorting criterion on the tree.
  3210. Its prototype is
  3211. \c typedef int (*cmpfn234)(void *, void *);
  3212. If you want a sorted tree, you should provide a function matching
  3213. this prototype, which returns like \cw{strcmp()} does (negative if
  3214. the first argument is smaller than the second, positive if it is
  3215. bigger, zero if they compare equal). In this case, the function
  3216. \cw{addpos234()} will not be usable on your tree (because all
  3217. insertions must respect the sorting order).
  3218. If you want an unsorted tree, pass \cw{NULL}. In this case you will
  3219. not be able to use either \cw{add234()} or \cw{del234()}, or any
  3220. other function such as \cw{find234()} which depends on a sorting
  3221. order. Your tree will become something more like an array, except
  3222. that it will efficiently support insertion and deletion as well as
  3223. lookups by numeric index.
  3224. \S{utils-freetree234} \cw{freetree234()}
  3225. \c void freetree234(tree234 *t);
  3226. Frees a tree. This function will not free the \e{elements} of the
  3227. tree (because they might not be dynamically allocated, or you might
  3228. be storing the same set of elements in more than one tree); it will
  3229. just free the tree structure itself. If you want to free all the
  3230. elements of a tree, you should empty it before passing it to
  3231. \cw{freetree234()}, by means of code along the lines of
  3232. \c while ((element = delpos234(tree, 0)) != NULL)
  3233. \c sfree(element); /* or some more complicated free function */
  3234. \e iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
  3235. \S{utils-add234} \cw{add234()}
  3236. \c void *add234(tree234 *t, void *e);
  3237. Inserts a new element \c{e} into the tree \c{t}. This function
  3238. expects the tree to be sorted; the new element is inserted according
  3239. to the sort order.
  3240. If an element comparing equal to \c{e} is already in the tree, then
  3241. the insertion will fail, and the return value will be the existing
  3242. element. Otherwise, the insertion succeeds, and \c{e} is returned.
  3243. \S{utils-addpos234} \cw{addpos234()}
  3244. \c void *addpos234(tree234 *t, void *e, int index);
  3245. Inserts a new element into an unsorted tree. Since there is no
  3246. sorting order to dictate where the new element goes, you must
  3247. specify where you want it to go. Setting \c{index} to zero puts the
  3248. new element right at the start of the list; setting \c{index} to the
  3249. current number of elements in the tree puts the new element at the
  3250. end.
  3251. Return value is \c{e}, in line with \cw{add234()} (although this
  3252. function cannot fail except by running out of memory, in which case
  3253. it will bomb out and die rather than returning an error indication).
  3254. \S{utils-index234} \cw{index234()}
  3255. \c void *index234(tree234 *t, int index);
  3256. Returns a pointer to the \c{index}th element of the tree, or
  3257. \cw{NULL} if \c{index} is out of range. Elements of the tree are
  3258. numbered from zero.
  3259. \S{utils-find234} \cw{find234()}
  3260. \c void *find234(tree234 *t, void *e, cmpfn234 cmp);
  3261. Searches for an element comparing equal to \c{e} in a sorted tree.
  3262. If \c{cmp} is \cw{NULL}, the tree's ordinary comparison function
  3263. will be used to perform the search. However, sometimes you don't
  3264. want that; suppose, for example, each of your elements is a big
  3265. structure containing a \c{char *} name field, and you want to find
  3266. the element with a given name. You \e{could} achieve this by
  3267. constructing a fake element structure, setting its name field
  3268. appropriately, and passing it to \cw{find234()}, but you might find
  3269. it more convenient to pass \e{just} a name string to \cw{find234()},
  3270. supplying an alternative comparison function which expects one of
  3271. its arguments to be a bare name and the other to be a large
  3272. structure containing a name field.
  3273. Therefore, if \c{cmp} is not \cw{NULL}, then it will be used to
  3274. compare \c{e} to elements of the tree. The first argument passed to
  3275. \c{cmp} will always be \c{e}; the second will be an element of the
  3276. tree.
  3277. (See \k{utils-newtree234} for the definition of the \c{cmpfn234}
  3278. function pointer type.)
  3279. The returned value is the element found, or \cw{NULL} if the search
  3280. is unsuccessful.
  3281. \S{utils-findrel234} \cw{findrel234()}
  3282. \c void *findrel234(tree234 *t, void *e, cmpfn234 cmp, int relation);
  3283. This function is like \cw{find234()}, but has the additional ability
  3284. to do a \e{relative} search. The additional parameter \c{relation}
  3285. can be one of the following values:
  3286. \dt \cw{REL234_EQ}
  3287. \dd Find only an element that compares equal to \c{e}. This is
  3288. exactly the behaviour of \cw{find234()}.
  3289. \dt \cw{REL234_LT}
  3290. \dd Find the greatest element that compares strictly less than
  3291. \c{e}. \c{e} may be \cw{NULL}, in which case it finds the greatest
  3292. element in the whole tree (which could also be done by
  3293. \cw{index234(t, count234(t)-1)}).
  3294. \dt \cw{REL234_LE}
  3295. \dd Find the greatest element that compares less than or equal to
  3296. \c{e}. (That is, find an element that compares equal to \c{e} if
  3297. possible, but failing that settle for something just less than it.)
  3298. \dt \cw{REL234_GT}
  3299. \dd Find the smallest element that compares strictly greater than
  3300. \c{e}. \c{e} may be \cw{NULL}, in which case it finds the smallest
  3301. element in the whole tree (which could also be done by
  3302. \cw{index234(t, 0)}).
  3303. \dt \cw{REL234_GE}
  3304. \dd Find the smallest element that compares greater than or equal to
  3305. \c{e}. (That is, find an element that compares equal to \c{e} if
  3306. possible, but failing that settle for something just bigger than
  3307. it.)
  3308. Return value, as before, is the element found or \cw{NULL} if no
  3309. element satisfied the search criterion.
  3310. \S{utils-findpos234} \cw{findpos234()}
  3311. \c void *findpos234(tree234 *t, void *e, cmpfn234 cmp, int *index);
  3312. This function is like \cw{find234()}, but has the additional feature
  3313. of returning the index of the element found in the tree; that index
  3314. is written to \c{*index} in the event of a successful search (a
  3315. non-\cw{NULL} return value).
  3316. \c{index} may be \cw{NULL}, in which case this function behaves
  3317. exactly like \cw{find234()}.
  3318. \S{utils-findrelpos234} \cw{findrelpos234()}
  3319. \c void *findrelpos234(tree234 *t, void *e, cmpfn234 cmp, int relation,
  3320. \c int *index);
  3321. This function combines all the features of \cw{findrel234()} and
  3322. \cw{findpos234()}.
  3323. \S{utils-del234} \cw{del234()}
  3324. \c void *del234(tree234 *t, void *e);
  3325. Finds an element comparing equal to \c{e} in the tree, deletes it,
  3326. and returns it.
  3327. The input tree must be sorted.
  3328. The element found might be \c{e} itself, or might merely compare
  3329. equal to it.
  3330. Return value is \cw{NULL} if no such element is found.
  3331. \S{utils-delpos234} \cw{delpos234()}
  3332. \c void *delpos234(tree234 *t, int index);
  3333. Deletes the element at position \c{index} in the tree, and returns
  3334. it.
  3335. Return value is \cw{NULL} if the index is out of range.
  3336. \S{utils-count234} \cw{count234()}
  3337. \c int count234(tree234 *t);
  3338. Returns the number of elements currently in the tree.
  3339. \S{utils-splitpos234} \cw{splitpos234()}
  3340. \c tree234 *splitpos234(tree234 *t, int index, bool before);
  3341. Splits the input tree into two pieces at a given position, and
  3342. creates a new tree containing all the elements on one side of that
  3343. position.
  3344. If \c{before} is \cw{true}, then all the items at or after position
  3345. \c{index} are left in the input tree, and the items before that
  3346. point are returned in the new tree. Otherwise, the reverse happens:
  3347. all the items at or after \c{index} are moved into the new tree, and
  3348. those before that point are left in the old one.
  3349. If \c{index} is equal to 0 or to the number of elements in the input
  3350. tree, then one of the two trees will end up empty (and this is not
  3351. an error condition). If \c{index} is further out of range in either
  3352. direction, the operation will fail completely and return \cw{NULL}.
  3353. This operation completes in \cw{O(log N)} time, no matter how large
  3354. the tree or how balanced or unbalanced the split.
  3355. \S{utils-split234} \cw{split234()}
  3356. \c tree234 *split234(tree234 *t, void *e, cmpfn234 cmp, int rel);
  3357. Splits a sorted tree according to its sort order.
  3358. \c{rel} can be any of the relation constants described in
  3359. \k{utils-findrel234}, \e{except} for \cw{REL234_EQ}. All the
  3360. elements having that relation to \c{e} will be transferred into the
  3361. new tree; the rest will be left in the old one.
  3362. The parameter \c{cmp} has the same semantics as it does in
  3363. \cw{find234()}: if it is not \cw{NULL}, it will be used in place of
  3364. the tree's own comparison function when comparing elements to \c{e},
  3365. in such a way that \c{e} itself is always the first of its two
  3366. operands.
  3367. Again, this operation completes in \cw{O(log N)} time, no matter how
  3368. large the tree or how balanced or unbalanced the split.
  3369. \S{utils-join234} \cw{join234()}
  3370. \c tree234 *join234(tree234 *t1, tree234 *t2);
  3371. Joins two trees together by concatenating the lists they represent.
  3372. All the elements of \c{t2} are moved into \c{t1}, in such a way that
  3373. they appear \e{after} the elements of \c{t1}. The tree \c{t2} is
  3374. freed; the return value is \c{t1}.
  3375. If you apply this function to a sorted tree and it violates the sort
  3376. order (i.e. the smallest element in \c{t2} is smaller than or equal
  3377. to the largest element in \c{t1}), the operation will fail and
  3378. return \cw{NULL}.
  3379. This operation completes in \cw{O(log N)} time, no matter how large
  3380. the trees being joined together.
  3381. \S{utils-join234r} \cw{join234r()}
  3382. \c tree234 *join234r(tree234 *t1, tree234 *t2);
  3383. Joins two trees together in exactly the same way as \cw{join234()},
  3384. but this time the combined tree is returned in \c{t2}, and \c{t1} is
  3385. destroyed. The elements in \c{t1} still appear before those in
  3386. \c{t2}.
  3387. Again, this operation completes in \cw{O(log N)} time, no matter how
  3388. large the trees being joined together.
  3389. \S{utils-copytree234} \cw{copytree234()}
  3390. \c tree234 *copytree234(tree234 *t, copyfn234 copyfn,
  3391. \c void *copyfnstate);
  3392. Makes a copy of an entire tree.
  3393. If \c{copyfn} is \cw{NULL}, the tree will be copied but the elements
  3394. will not be; i.e. the new tree will contain pointers to exactly the
  3395. same physical elements as the old one.
  3396. If you want to copy each actual element during the operation, you
  3397. can instead pass a function in \c{copyfn} which makes a copy of each
  3398. element. That function has the prototype
  3399. \c typedef void *(*copyfn234)(void *state, void *element);
  3400. and every time it is called, the \c{state} parameter will be set to
  3401. the value you passed in as \c{copyfnstate}.
  3402. \H{utils-dsf} Disjoint set forests
  3403. This section describes a set of functions implementing the data
  3404. structure variously known as \q{union-find} or \q{Tarjan's disjoint
  3405. set forest}. In this code base, it's universally abbreviated as a
  3406. \q{dsf}.
  3407. A dsf represents a collection of elements partitioned into
  3408. \q{equivalence classes}, in circumstances where equivalences are added
  3409. incrementally. That is, all elements start off considered to be
  3410. different, and you gradually declare more and more of them to be equal
  3411. via the \cw{dsf_merge()} operation, which says that two particular
  3412. elements should be regarded as equal from now on.
  3413. For example, if I start off with A,B,U,V all distinct, and I merge A
  3414. with B and merge U with V, then the structure will tell me that A and
  3415. U are not equivalent. But if I then merge B with V, then after that,
  3416. the structure will tell me that A and U \e{are} equivalent, by
  3417. following the transitive chain of equivalences it knows about.
  3418. The dsf data structure is therefore ideal for tracking incremental
  3419. connectivity in an undirected graph (again, \q{incremental} meaning
  3420. that you only ever add edges, never delete them), and other
  3421. applications in which you gradually acquire knowledge you didn't
  3422. previously have about what things are the same as each other. It's
  3423. used extensively in puzzle solver and generator algorithms, and
  3424. sometimes during gameplay as well.
  3425. The time complexity of dsf operations is not \e{quite} constant time,
  3426. in theory, but it's so close to it as to make no difference in
  3427. practice. In particular, any time a dsf has to do non-trivial work, it
  3428. updates the structure so that that work won't be needed a second time.
  3429. Use dsf operations without worrying about how long they take!
  3430. For some puzzle-game applications, it's useful to augment this data
  3431. structure with extra information about how the elements of an
  3432. equivalence class relate to each other. There's more than one way you
  3433. might do this; the one supported here is useful in cases where the
  3434. objects you're tracking are going to end up in one of two states (say,
  3435. black/white, or on/off), and for any two objects you either know that
  3436. they're in the same one of those states, or you know they're in
  3437. opposite states, or you don't know which yet. Puzzles calls this a
  3438. \q{flip dsf}: it tracks whether objects in the same equivalence class
  3439. are flipped relative to each other.
  3440. As well as querying whether two elements are equivalent, this dsf
  3441. implementation also allows you to ask for the number of elements in a
  3442. given equivalence class, and the smallest element in the class. (The
  3443. latter is used, for example, to decide which square to print the clue
  3444. in each region of a Keen puzzle.)
  3445. \S{utils-dsf-new} \cw{dsf_new()}, \cw{dsf_new_flip()}, \cw{dsf_new_min()}
  3446. \c DSF *dsf_new(int size);
  3447. \c DSF *dsf_new_flip(int size);
  3448. \c DSF *dsf_new_min(int size);
  3449. Each of these functions allocates space for a dsf describing \c{size}
  3450. elements, and initialises it so that every element is in an
  3451. equivalence class by itself.
  3452. The elements described by the dsf are represented by the integers from
  3453. \cw{0} to \cw{size-1} inclusive.
  3454. \cw{dsf_new_flip()} will create a dsf which has the extra ability to
  3455. track whether objects in the same equivalence class are flipped
  3456. relative to each other.
  3457. \cw{dsf_new_min()} will create a dsf which has the extra ability to
  3458. track the smallest element of each equivalence class.
  3459. The returned object from any of these functions must be freed using
  3460. \cw{dsf_free()}.
  3461. \S{utils-dsf-free} \cw{dsf_free()}
  3462. \c void dsf_free(DSF *dsf);
  3463. Frees a dsf allocated by any of the \cw{dsf_new()} functions.
  3464. \S{utils-dsf-reinit} \cw{dsf_reinit()}
  3465. \c void dsf_reinit(DSF *dsf);
  3466. Reinitialises an existing dsf to the state in which all elements are
  3467. distinct, without having to free and reallocate it.
  3468. \S{utils-dsf-copy} \cw{dsf_copy()}
  3469. \c void dsf_copy(DSF *to, DSF *from);
  3470. Copies the contents of one dsf over the top of another. Everything
  3471. previously stored in \c{to} is overwritten.
  3472. The two dsfs must have been created with the same size, and the
  3473. destination dsf may not have any extra information that the source dsf
  3474. does not have.
  3475. \S{utils-dsf-merge} \cw{dsf_merge()}
  3476. \c void dsf_merge(DSF *dsf, int v1, int v2);
  3477. Updates a dsf so that elements \c{v1} and \c{v2} will now be
  3478. considered to be in the same equivalence class. If they were already
  3479. in the same class, this function will safely do nothing.
  3480. This function may not be called on a flip dsf. Use \cw{dsf_merge_flip}
  3481. instead.
  3482. \S{utils-dsf-canonify} \cw{dsf_canonify()}
  3483. \c int dsf_canonify(DSF *dsf, int val);
  3484. Returns the \q{canonical} element of the equivalence class in the dsf
  3485. containing \c{val}. This will be some element of the same equivalence
  3486. class. So in order to determine whether two elements are in the same
  3487. equivalence class, you can call \cw{dsf_canonify} on both of them, and
  3488. compare the results.
  3489. Canonical elements don't necessarily stay the same if the dsf is
  3490. mutated via \c{dsf_merge}. But between two calls to \c{dsf_merge},
  3491. they stay the same.
  3492. \S{utils-dsf-size} \cw{dsf_size()}
  3493. \c int dsf_size(DSF *dsf, int val);
  3494. Returns the number of elements currently in the equivalence class
  3495. containing \c{val}.
  3496. \c{val} itself counts, so in a newly created dsf, the return value
  3497. will be 1.
  3498. \S{utils-dsf-merge-flip} \cw{dsf_merge_flip()}
  3499. \c void edsf_merge(DSF *dsf, int v1, int v2, bool flip);
  3500. Updates a flip dsf so that elements \c{v1} and \c{v2} are in the same
  3501. equivalence class. If \c{flip} is \cw{false}, they will be regarded as
  3502. in the same state as each other; if \c{flip} is \cw{true} then they
  3503. will be regarded as being in opposite states.
  3504. If \c{v1} and \c{v2} were already in the same equivalence class, then
  3505. the new value of \c{flip} will be checked against what the edsf
  3506. previously believed, and an assertion failure will occur if you
  3507. contradict that.
  3508. For example, if you start from a blank flip dsf and do this:
  3509. \c dsf_merge_flip(dsf, 0, 1, false);
  3510. \c dsf_merge_flip(dsf, 1, 2, true);
  3511. then it will create a dsf in which elements 0,1,2 are all in the same
  3512. class, with 0,1 in the same state as each other and 2 in the opposite
  3513. state from both. And then this call will do nothing, because it agrees
  3514. with what the dsf already knew:
  3515. \c dsf_merge_flip(dsf, 0, 2, true);
  3516. But this call will fail an assertion:
  3517. \c dsf_merge_flip(dsf, 0, 2, false);
  3518. \S{utils-dsf-canonify-flip} \cw{dsf_canonify_flip()}
  3519. \c int dsf_canonify_flip(DSF *dsf, int val, bool *inverse);
  3520. Like \c{dsf_canonify()}, this returns the canonical element of the
  3521. equivalence class of a dsf containing \c{val}.
  3522. However, it may only be called on a flip dsf, and it also fills in
  3523. \c{*flip} with a flag indicating whether \c{val} and the canonical
  3524. element are in opposite states: \cw{true} if they are in opposite
  3525. states, or \cw{false} if they're in the same state.
  3526. So if you want to know the relationship between \c{v1} and \c{v2}, you
  3527. can do this:
  3528. \c bool inv1, inv2;
  3529. \c int canon1 = dsf_canonify_flip(dsf, v1, &inv1);
  3530. \c int canon2 = dsf_canonify_flip(dsf, v2, &inv2);
  3531. \c if (canon1 != canon2) {
  3532. \c // v1 and v2 have no known relation
  3533. \c } else if (inv1 == inv2) {
  3534. \c // v1 and v2 are known to be in the same state as each other
  3535. \c } else {
  3536. \c // v1 and v2 are known to be in opposite states
  3537. \c }
  3538. \S{utils-dsf-minimal} \cw{dsf_minimal()}
  3539. \c int dsf_minimal(DSF *dsf, int val);
  3540. Returns the smallest element of the equivalence class in the dsf
  3541. containing \c{val}.
  3542. For this function to work, the dsf must have been created using
  3543. \cw{dsf_new_min()}.
  3544. \H{utils-tdq} To-do queues
  3545. This section describes a set of functions implementing a \q{to-do
  3546. queue}, a simple de-duplicating to-do list mechanism. The code calls
  3547. this a \q{tdq}.
  3548. A tdq can store integers up to a given size (specified at creation
  3549. time). But it can't store the same integer more than once. So you can
  3550. quickly \e{make sure} an integer is in the queue (which will do
  3551. nothing if it's already there), and you can quickly pop an integer
  3552. from the queue and return it, both in constant time.
  3553. The idea is that you might use this in a game solver, in the kind of
  3554. game where updating your knowledge about one square of a grid means
  3555. there's a specific other set of squares (such as its neighbours) where
  3556. it's now worth attempting further deductions. So you keep a tdq of all
  3557. the grid squares you plan to look at next, and every time you make a
  3558. deduction in one square, you add the neighbouring squares to the tdq
  3559. to make sure they get looked at again after that.
  3560. In solvers where deductions are mostly localised, this avoids the
  3561. slowdown of having to find the next thing to do every time by looping
  3562. over the whole grid: instead, you can keep checking the tdq for
  3563. \e{specific} squares to look at, until you run out.
  3564. However, it's common to have games in which \e{most} deductions are
  3565. localised, but not all. In that situation, when your tdq is empty, you
  3566. can re-fill it with every square in the grid using \cw{tdq_fill()},
  3567. which will force an iteration over everything again. And then if the
  3568. tdq becomes empty \e{again} without you having made any progress, give
  3569. up.
  3570. \S{utils-tdq-new} \cw{tdq_new()}
  3571. \c tdq *tdq_new(int n);
  3572. Allocates space for a tdq that tracks items from \cw{0} to \cw{size-1}
  3573. inclusive.
  3574. \S{utils-tdq-free} \cw{tdq_free()}
  3575. \c void tdq_free(tdq *tdq);
  3576. Frees a tdq.
  3577. \S{utils-tdq-add} \cw{tdq_add()}
  3578. \c void tdq_add(tdq *tdq, int k);
  3579. Adds the value \c{k} to a tdq. If \c{k} was already in the to-do list,
  3580. does nothing.
  3581. \S{utils-tdq-remove} \cw{tdq_remove()}
  3582. \c int tdq_remove(tdq *tdq);
  3583. Removes one item from the tdq, and returns it. If the tdq is empty,
  3584. returns \cw{-1}.
  3585. \S{utils-tdq-fill} \cw{tdq_fill()}
  3586. \c void tdq_fill(tdq *tdq);
  3587. Fills a tdq with every element it can possibly keep track of.
  3588. \H{utils-findloop} Finding loops in graphs and grids
  3589. Many puzzles played on grids or graphs have a common gameplay element
  3590. of connecting things together into paths in such a way that you need
  3591. to avoid making loops (or, perhaps, making the \e{wrong} kind of
  3592. loop).
  3593. Just determining \e{whether} a loop exists in a graph is easy, using a
  3594. dsf tracking connectivity between the vertices. Simply iterate over
  3595. each edge of the graph, merging the two vertices at each end of the
  3596. edge \dash but before you do that, check whether those vertices are
  3597. \e{already} known to be connected to each other, and if they are, then
  3598. the new edge is about to complete a loop.
  3599. But if you also want to identify \e{exactly} the set of edges that are
  3600. part of any loop, e.g. to highlight the whole loop red during
  3601. gameplay, then that's a harder problem. This API is provided here for
  3602. all puzzles to use for that purpose.
  3603. \S{utils-findloop-new-state} \cw{findloop_new_state()}
  3604. \c struct findloopstate *findloop_new_state(int nvertices);
  3605. Allocates a new state structure for the findloop algorithm, capable of
  3606. handling a graph with up to \c{nvertices} vertices. The vertices will
  3607. be represented by integers between \c{0} and \c{nvertices-1} inclusive.
  3608. \S{utils-findloop-free-state} \cw{findloop_free_state()}
  3609. \c void findloop_free_state(struct findloopstate *state);
  3610. Frees a state structure allocated by \cw{findloop_new_state()}.
  3611. \S{utils-findloop-run} \cw{findloop_run()}
  3612. \c bool findloop_run(struct findloopstate *state, int nvertices,
  3613. \c neighbour_fn_t neighbour, void *ctx);
  3614. Runs the loop-finding algorithm, which will explore the graph and
  3615. identify whether each edge is or is not part of any loop.
  3616. The algorithm will call the provided function \c{neighbour} to list
  3617. the neighbouring vertices of each vertex. It should have this
  3618. prototype:
  3619. \c int neighbour(int vertex, void *ctx);
  3620. In this callback, \c{vertex} will be the index of a vertex when the
  3621. algorithm \e{first} calls it for a given vertex. The function should
  3622. return the index of one of that vertex's neighbours, or a negative
  3623. number if there are none.
  3624. If the function returned a vertex, the algorithm will then call
  3625. \c{neighbour} again with a \e{negative} number as the \c{vertex}
  3626. parameter, which means \q{please give me another neighbour of the same
  3627. vertex as last time}. Again, the function should return a vertex
  3628. index, or a negative number to indicate that there are no more
  3629. vertices.
  3630. The \c{ctx} parameter passed to \cw{findloop_run()} is passed on
  3631. unchanged to \c{neighbour}, so you can point that at your game state
  3632. or solver state or whatever.
  3633. The return value is \cw{true} if at least one loop exists in the
  3634. graph, and \cw{false} if no loop exists. Also, the algorithm state
  3635. will have been filled in with information that the following query
  3636. functions can use to ask about individual graph edges.
  3637. \S{utils-findloop-is-loop-edge} \cw{findloop_is_loop_edge()}
  3638. \c bool findloop_is_loop_edge(struct findloopstate *state,
  3639. \c int u, int v);
  3640. Queries whether the graph edge between vertices \c{u} and \c{v} is
  3641. part of a loop. If so, the return value is \cw{true}, otherwise
  3642. \cw{false}.
  3643. \S{utils-findloop-is-bridge} \cw{findloop_is_bridge()}
  3644. \c bool findloop_is_bridge(struct findloopstate *pv,
  3645. \c int u, int v, int *u_vertices, int *v_vertices);
  3646. Queries whether the graph edge between vertices \c{u} and \c{v} is a
  3647. \q{bridge}, i.e. an edge which would break the graph into (more)
  3648. disconnected components if it were removed.
  3649. This is the exact inverse of the \q{loop edge} criterion: a vertex
  3650. returns \cw{true} from \cw{findloop_is_loop_edge()} if and only if it
  3651. returns \cw{false} from \cw{findloop_is_bridge()}, and vice versa.
  3652. However, \cw{findloop_is_bridge()} returns more information. If it
  3653. returns \cw{true}, then it also fills in \c{*u_vertices} and
  3654. \c{*v_vertices} with the number of vertices connected to the \c{u} and
  3655. \c{v} sides of the bridge respectively.
  3656. For example, if you have three vertices A,B,C all connected to each
  3657. other, and four vertices U,V,W,X all connected to each other, and a
  3658. single edge between A and V, then calling \cw{findloop_is_bridge()} on
  3659. the pair A,V will return true (removing that edge would separate the
  3660. two sets from each other), and will report that there are three
  3661. vertices on the A side and four on the V side.
  3662. \H{utils-combi} Choosing r things out of n
  3663. This section describes a small API for iterating over all combinations
  3664. of r things out of n.
  3665. For example, if you asked for all combinations of 3 things out of 5,
  3666. you'd get back the sets \{0,1,2\}, \{0,1,3\}, \{0,1,4\}, \{0,2,3\},
  3667. \{0,2,4\}, \{0,3,4\}, \{1,2,3\}, \{1,2,4\}, \{1,3,4\}, and \{2,3,4\}.
  3668. These functions use a structure called a \c{combi_ctx}, which contains
  3669. an element \c{int *a} holding each returned combination, plus other
  3670. fields for implementation use only.
  3671. \S{utils-combi-new} \cw{new_combi()}
  3672. \c combi_ctx *new_combi(int r, int n);
  3673. Allocates a new \c{combi_ctx} structure for enumerating r things out
  3674. of n.
  3675. \S{utils-combi-free} \cw{free_combi()}
  3676. \c void free_combi(combi_ctx *combi);
  3677. Frees a \c{combi_ctx} structure.
  3678. \S{utils-combi-reset} \cw{reset_combi()}
  3679. \c void reset_combi(combi_ctx *combi);
  3680. Resets an existing \c{combi_ctx} structure to the start of its
  3681. iteration
  3682. \S{utils-combi-next} \cw{next_combi()}
  3683. \c combi_ctx *next_combi(combi_ctx *combi);
  3684. Requests a combination from a \c{combi_ctx}.
  3685. If there are none left to return, the return value is \cw{NULL}.
  3686. Otherwise, it returns the input structure \c{combi}, indicating that
  3687. it has filled in \cw{combi->a[0]}, \cw{combi->a[1]}, ...,
  3688. \cw{combi->a[r-1]} with an increasing sequence of distinct integers
  3689. from \cw{0} to \cw{n-1} inclusive.
  3690. \H{utils-misc} Miscellaneous utility functions and macros
  3691. This section contains all the utility functions which didn't
  3692. sensibly fit anywhere else.
  3693. \S{utils-maxmin} \cw{max()} and \cw{min()}
  3694. The main Puzzles header file defines the pretty standard macros
  3695. \cw{max()} and \cw{min()}, each of which is given two arguments and
  3696. returns the one which compares greater or less respectively.
  3697. These macros may evaluate their arguments multiple times. Avoid side
  3698. effects.
  3699. \S{utils-max-digits} \cw{MAX_DIGITS()}
  3700. The \cw{MAX_DIGITS()} macro, defined in the main Puzzles header file,
  3701. takes a type (or a variable of that type) and expands to an integer
  3702. constant representing a reasonable upper bound on the number of
  3703. characters that a number of that type could expand to when formatted
  3704. as a decimal number using the \c{%u} or \c{%d} format of
  3705. \cw{printf()}. This is useful for allocating a fixed-size buffer
  3706. that's guaranteed to be big enough to \cw{sprintf()} a value into.
  3707. Don't forget to add one for the trailing \cw{'\\0'}!
  3708. \S{utils-pi} \cw{PI}
  3709. The main Puzzles header file defines a macro \cw{PI} which expands
  3710. to a floating-point constant representing pi.
  3711. (I've never understood why ANSI's \cw{<math.h>} doesn't define this.
  3712. It'd be so useful!)
  3713. \S{utils-obfuscate-bitmap} \cw{obfuscate_bitmap()}
  3714. \c void obfuscate_bitmap(unsigned char *bmp, int bits, bool decode);
  3715. This function obscures the contents of a piece of data, by
  3716. cryptographic methods. It is useful for games of hidden information
  3717. (such as Mines, Guess or Black Box), in which the game ID
  3718. theoretically reveals all the information the player is supposed to
  3719. be trying to guess. So in order that players should be able to send
  3720. game IDs to one another without accidentally spoiling the resulting
  3721. game by looking at them, these games obfuscate their game IDs using
  3722. this function.
  3723. Although the obfuscation function is cryptographic, it cannot
  3724. properly be called encryption because it has no key. Therefore,
  3725. anybody motivated enough can re-implement it, or hack it out of the
  3726. Puzzles source, and strip the obfuscation off one of these game IDs
  3727. to see what lies beneath. (Indeed, they could usually do it much
  3728. more easily than that, by entering the game ID into their own copy
  3729. of the puzzle and hitting Solve.) The aim is not to protect against
  3730. a determined attacker; the aim is simply to protect people who
  3731. wanted to play the game honestly from \e{accidentally} spoiling
  3732. their own fun.
  3733. The input argument \c{bmp} points at a piece of memory to be
  3734. obfuscated. \c{bits} gives the length of the data. Note that that
  3735. length is in \e{bits} rather than bytes: if you ask for obfuscation
  3736. of a partial number of bytes, then you will get it. Bytes are
  3737. considered to be used from the top down: thus, for example, setting
  3738. \c{bits} to 10 will cover the whole of \cw{bmp[0]} and the \e{top
  3739. two} bits of \cw{bmp[1]}. The remainder of a partially used byte is
  3740. undefined (i.e. it may be corrupted by the function).
  3741. The parameter \c{decode} is \cw{false} for an encoding operation,
  3742. and \cw{true} for a decoding operation. Each is the inverse of the
  3743. other. (There's no particular reason you shouldn't obfuscate by
  3744. decoding and restore cleartext by encoding, if you really wanted to;
  3745. it should still work.)
  3746. The input bitmap is processed in place.
  3747. \S{utils-bin2hex} \cw{bin2hex()}
  3748. \c char *bin2hex(const unsigned char *in, int inlen);
  3749. This function takes an input byte array and converts it into an
  3750. ASCII string encoding those bytes in (lower-case) hex. It returns a
  3751. dynamically allocated string containing that encoding.
  3752. This function is useful for encoding the result of
  3753. \cw{obfuscate_bitmap()} in printable ASCII for use in game IDs.
  3754. \S{utils-hex2bin} \cw{hex2bin()}
  3755. \c unsigned char *hex2bin(const char *in, int outlen);
  3756. This function takes an ASCII string containing hex digits, and
  3757. converts it back into a byte array of length \c{outlen}. If there
  3758. aren't enough hex digits in the string, the contents of the
  3759. resulting array will be undefined.
  3760. This function is the inverse of \cw{bin2hex()}.
  3761. \S{utils-fgetline} \cw{fgetline()}
  3762. \c char *fgetline(FILE *fp);
  3763. This function reads a single line of text from a standard C input
  3764. stream, and returns it as a dynamically allocated string. The returned
  3765. string still has a newline on the end.
  3766. \S{utils-arraysort} \cw{arraysort()}
  3767. Sorts an array, with slightly more flexibility than the standard C
  3768. \cw{qsort()}.
  3769. This function is really implemented as a macro, so it doesn't have a
  3770. prototype as such. But you could imagine it having a prototype like
  3771. this:
  3772. \c void arraysort(element_t *array, size_t nmemb,
  3773. \c arraysort_cmpfn_t cmp, void *ctx);
  3774. in which \c{element_t} is an unspecified type.
  3775. (Really, there's an underlying function that takes an extra parameter
  3776. giving the size of each array element. But callers are encouraged to
  3777. use this macro version, which fills that in automatically using
  3778. \c{sizeof}.)
  3779. This function behaves essentially like \cw{qsort()}: it expects
  3780. \c{array} to point to an array of \c{nmemb} elements, and it will sort
  3781. them in place into the order specified by the comparison function
  3782. \c{cmp}.
  3783. The comparison function should have this prototype:
  3784. \c int cmp(const void *a, const void *b, void *ctx);
  3785. in which \c{a} and \c{b} point at the two elements to be compared, and
  3786. the return value is negative if \cw{a<b} (that is, \c{a} should appear
  3787. before \c{b} in the output array), positive if \cw{a>b}, or zero if
  3788. \c{a=b}.
  3789. The \c{ctx} parameter to \cw{arraysort()} is passed directly to the
  3790. comparison function. This is the feature that makes \cw{arraysort()}
  3791. more flexible than standard \cw{qsort()}: it lets you vary the sorting
  3792. criterion in a dynamic manner without having to write global variables
  3793. in the caller for the compare function to read.
  3794. \S{utils-colour-mix} \cw{colour_mix()}
  3795. \c void colour_mix(const float src1[3], const float src2[3], float p,
  3796. \c float dst[3]);
  3797. This function mixes the colours \c{src1} and \c{src2} in specified
  3798. proportions, producing \c{dst}. \c{p} is the proportion of \c{src2}
  3799. in the result. So if \c{p} is \cw{1.0}, \cw{dst} will be the same as
  3800. \c{src2}. If \c{p} is \cw{0.0}, \cw{dst} will be the same as
  3801. \c{src1}. And if \c{p} is somewhere in between, so will \c{dst} be.
  3802. \c{p} is not restricted to the range \cw{0.0} to \cw{1.0}. Values
  3803. outside that range will produce extrapolated colours, which may be
  3804. useful for some purposes, but may also produce impossible colours.
  3805. \S{utils-game-mkhighlight} \cw{game_mkhighlight()}
  3806. \c void game_mkhighlight(frontend *fe, float *ret,
  3807. \c int background, int highlight, int lowlight);
  3808. It's reasonably common for a puzzle game's graphics to use
  3809. highlights and lowlights to indicate \q{raised} or \q{lowered}
  3810. sections. Fifteen, Sixteen and Twiddle are good examples of this.
  3811. Puzzles using this graphical style are running a risk if they just
  3812. use whatever background colour is supplied to them by the front end,
  3813. because that background colour might be too light or dark to see any
  3814. highlights on at all. (In particular, it's not unheard of for the
  3815. front end to specify a default background colour of white.)
  3816. Therefore, such puzzles can call this utility function from their
  3817. \cw{colours()} routine (\k{backend-colours}). You pass it your front
  3818. end handle, a pointer to the start of your return array, and three
  3819. colour indices. It will:
  3820. \b call \cw{frontend_default_colour()} (\k{frontend-default-colour})
  3821. to fetch the front end's default background colour
  3822. \b alter the brightness of that colour if it's unsuitable
  3823. \b define brighter and darker variants of the colour to be used as
  3824. highlights and lowlights
  3825. \b write those results into the relevant positions in the \c{ret}
  3826. array.
  3827. Thus, \cw{ret[background*3]} to \cw{ret[background*3+2]} will be set
  3828. to RGB values defining a sensible background colour, and similary
  3829. \c{highlight} and \c{lowlight} will be set to sensible colours.
  3830. Either \c{highlight} or \c{lowlight} may be passed in as \cw{-1} to
  3831. indicate that the back-end does not require a highlight or lowlight
  3832. colour, respectively.
  3833. \S{utils-game-mkhighlight-specific} \cw{game_mkhighlight_specific()}
  3834. \c void game_mkhighlight_specific(frontend *fe, float *ret,
  3835. \c int background, int highlight, int lowlight);
  3836. This function behaves exactly like \cw{game_mkhighlight()}, except
  3837. that it expects the background colour to have been filled in
  3838. \e{already} in the elements \cw{ret[background*3]} to
  3839. \cw{ret[background*3+2]}. It will fill in the other two colours as
  3840. brighter and darker versions of that.
  3841. This is useful if you want to show relief sections of a puzzle in more
  3842. than one base colour.
  3843. \S{utils-button2label} \cw{button2label()}
  3844. \c char *button2label(int button);
  3845. This function generates a descriptive text label for \cw{button},
  3846. which should be a button code that can be passed to the midend. For
  3847. example, calling this function with \cw{CURSOR_UP} will result in the
  3848. string \cw{"Up"}. This function should only be called when the
  3849. \cw{key_label} item returned by a backend's \cw{request_keys()}
  3850. (\k{backend-request-keys}) function has its \cw{label} field set to
  3851. \cw{NULL}; in this case, the corresponding \cw{button} field can be
  3852. passed to this function to obtain an appropriate label. If, however,
  3853. the field is not \cw{NULL}, this function should not be called with
  3854. the corresponding \cw{button} field.
  3855. The returned string is dynamically allocated and should be
  3856. \cw{sfree}'d by the caller.
  3857. \S{utils-move-cursor} \cw{move_cursor()}
  3858. \c void move_cursor(int button, int *x, int *y, int w, int h,
  3859. \c bool wrap);
  3860. This function can be called by \cw{interpret_move()} to implement the
  3861. default keyboard API for moving a cursor around a grid.
  3862. \c{button} is the same value passed in to \cw{interpret_move()}. If
  3863. it's not any of \cw{CURSOR_UP}, \cw{CURSOR_DOWN}, \cw{CURSOR_LEFT} or
  3864. \cw{CURSOR_RIGHT}, the function will do nothing.
  3865. \c{x} and \c{y} point to two integers which on input give the current
  3866. location of a cursor in a square grid. \c{w} and \c{h} give the
  3867. dimensions of the grid. On return, \c{x} and \c{y} are updated to give
  3868. the cursor's new position according to which arrow key was pressed.
  3869. This function assumes that the grid coordinates run from \cw{0} to
  3870. \cw{w-1} inclusive (left to right), and from \cw{0} to \cw{h-1}
  3871. inclusive (top to bottom).
  3872. If \c{wrap} is \cw{true}, then trying to move the cursor off any edge
  3873. of the grid will result in it wrapping round to the corresponding
  3874. square on the opposite edge. If \c{wrap} is \cw{false}, such a move
  3875. will have no effect.
  3876. \S{utils-divvy-rectangle} \cw{divvy_rectangle()}
  3877. \c int *divvy_rectangle(int w, int h, int k, random_state *rs);
  3878. Invents a random division of a rectangle into same-sized polyominoes,
  3879. such as is found in the block layout of a Solo puzzle in jigsaw mode,
  3880. or the solution to a Palisade puzzle.
  3881. \c{w} and \c{h} are the dimensions of the rectangle. \c{k} is the size
  3882. of polyomino desired. It must be a factor of \c{w*h}.
  3883. \c{rs} is a \cw{random_state} used to supply the random numbers to
  3884. select a random division of the rectangle.
  3885. The return value is a dsf (see \k{utils-dsf}) whose equivalence
  3886. classes correspond to the polyominoes that the rectangle is divided
  3887. into. The indices of the dsf are of the form \c{y*w+x}, for the cell
  3888. with coordinates \cw{x,y}.
  3889. \S{utils-domino-layout} \cw{domino_layout()}
  3890. \c int *domino_layout(int w, int h, random_state *rs);
  3891. Invents a random tiling of a rectangle with dominoes.
  3892. \c{w} and \c{h} are the dimensions of the rectangle. If they are both
  3893. odd, then one square will be left untiled.
  3894. \c{rs} is a \cw{random_state} used to supply the random numbers to
  3895. select a random division of the rectangle.
  3896. The return value is an array in which element \c{y*w+x} represents the
  3897. cell with coordinates \cw{x,y}. Each element of the array gives the
  3898. index (in the same representation) of the other end of its domino. If
  3899. there's a left-over square, then that element contains its own index.
  3900. \S{utils-domino-layout-prealloc} \cw{domino_layout_prealloc()}
  3901. \c void domino_layout_prealloc(int w, int h, random_state *rs,
  3902. \c int *grid, int *grid2, int *list);
  3903. Just like \cw{domino_layout()}, but does no memory allocation. You can
  3904. use this to save allocator overhead if you expect to need to generate
  3905. many domino tilings of the same grid.
  3906. \c{grid} and \c{grid2} should each have space for \cw{w*h} ints.
  3907. \c{list} should have space for \c{2*w*h} ints.
  3908. The returned array is delivered in \c{grid}.
  3909. \C{writing} How to write a new puzzle
  3910. This chapter gives a guide to how to actually write a new puzzle:
  3911. where to start, what to do first, how to solve common problems.
  3912. The previous chapters have been largely composed of facts. This one
  3913. is mostly advice.
  3914. \H{writing-editorial} Choosing a puzzle
  3915. Before you start writing a puzzle, you have to choose one. Your
  3916. taste in puzzle games is up to you, of course; and, in fact, you're
  3917. probably reading this guide because you've \e{already} thought of a
  3918. game you want to write. But if you want to get it accepted into the
  3919. official Puzzles distribution, then there's a criterion it has to
  3920. meet.
  3921. The current Puzzles editorial policy is that all games should be
  3922. \e{fair}. A fair game is one which a player can only fail to complete
  3923. through demonstrable lack of skill \dash that is, such that a better
  3924. player presented with the same game state would have \e{known} to do
  3925. something different.
  3926. For a start, that means every game presented to the user must have
  3927. \e{at least one solution}. Giving the unsuspecting user a puzzle which
  3928. is actually impossible is not acceptable.
  3929. (An exception to this: if the user has selected some non-default
  3930. option which is clearly labelled as potentially unfair, \e{then}
  3931. you're allowed to generate possibly insoluble puzzles, because the
  3932. user isn't unsuspecting any more. Same Game and Mines both have
  3933. options of this type.)
  3934. Secondly, if the game includes hidden information, then it must be
  3935. possible to deduce a correct move at every stage from the currently
  3936. available information. It's not enough that there should exist some
  3937. sequence of moves which will get from the start state to the solved
  3938. state, if the player doesn't necessarily have enough information to
  3939. \e{find} that solution. For example, in the card solitaire game
  3940. Klondike, it's possible to reach a dead end because you had an
  3941. arbitrary choice to make on no information, and made it the wrong way,
  3942. which violates the fairness criterion, because a better player
  3943. couldn't have known they needed to make the other choice.
  3944. (Of course, games in this collection always have an Undo function, so
  3945. if you did take the wrong route through a Klondike game, you could use
  3946. Undo to back up and try a different choice. This doesn't count. In a
  3947. fair game, you should be able to determine a correct move from the
  3948. information visible \e{now}, without having to make moves to get more
  3949. information that you can then back up and use.)
  3950. Sometimes you can adjust the rules of an unfair puzzle to make it meet
  3951. this definition of fairness. For example, more than one implementation
  3952. of solitaire-style games (including card solitaires and Mahjong
  3953. Solitaire) include a UI action to shuffle the remaining cards or tiles
  3954. without changing their position; this action might be available at any
  3955. time with a time or points penalty, or it might be illegal to use
  3956. unless you have no other possible move. Adding an option like this
  3957. would make a game \e{technically} fair, but it's better to avoid even
  3958. that if you can.
  3959. Providing a \e{unique} solution is a little more negotiable; it
  3960. depends on the puzzle. Solo would have been of unacceptably low
  3961. quality if it didn't always have a unique solution, whereas Twiddle
  3962. inherently has multiple solutions by its very nature and it would
  3963. have been meaningless to even \e{suggest} making it uniquely
  3964. soluble. Somewhere in between, Flip could reasonably be made to have
  3965. unique solutions (by enforcing a zero-dimension kernel in every
  3966. generated matrix) but it doesn't seem like a serious quality problem
  3967. that it doesn't.
  3968. Of course, you don't \e{have} to care about all this. There's
  3969. nothing stopping you implementing any puzzle you want to if you're
  3970. happy to maintain your puzzle yourself, distribute it from your own
  3971. web site, fork the Puzzles code completely, or anything like that.
  3972. It's free software; you can do what you like with it. But any game
  3973. that you want to be accepted into \e{my} Puzzles code base has to
  3974. satisfy the fairness criterion, which means all randomly generated
  3975. puzzles must have a solution (unless the user has deliberately
  3976. chosen otherwise) and it must be possible \e{in theory} to find that
  3977. solution without having to guess.
  3978. \H{writing-gs} Getting started
  3979. The simplest way to start writing a new puzzle is to copy
  3980. \c{nullgame.c}. This is a template puzzle source file which does
  3981. almost nothing, but which contains all the back end function
  3982. prototypes and declares the back end data structure correctly. It is
  3983. built every time the rest of Puzzles is built, to ensure that it
  3984. doesn't get out of sync with the code and remains buildable.
  3985. So start by copying \c{nullgame.c} into your new source file. Then
  3986. you'll gradually add functionality until the very boring Null Game
  3987. turns into your real game.
  3988. Next you'll need to add your puzzle to the build scripts, in order to
  3989. compile it conveniently. Puzzles is a CMake project, so you do this by
  3990. adding a \cw{puzzle()} statement to CMakeLists.txt. Look at the
  3991. existing ones to see what those look like, and add one that looks
  3992. similar.
  3993. Once your source file is building, you can move on to the fun bit.
  3994. \S{writing-generation} Puzzle generation
  3995. Randomly generating instances of your puzzle is almost certain to be
  3996. the most difficult part of the code, and also the task with the
  3997. highest chance of turning out to be completely infeasible. Therefore
  3998. I strongly recommend doing it \e{first}, so that if it all goes
  3999. horribly wrong you haven't wasted any more time than you absolutely
  4000. had to. What I usually do is to take an unmodified \c{nullgame.c},
  4001. and start adding code to \cw{new_game_desc()} which tries to
  4002. generate a puzzle instance and print it out using \cw{printf()}.
  4003. Once that's working, \e{then} I start connecting it up to the return
  4004. value of \cw{new_game_desc()}, populating other structures like
  4005. \c{game_params}, and generally writing the rest of the source file.
  4006. There are many ways to generate a puzzle which is known to be
  4007. soluble. In this section I list all the methods I currently know of,
  4008. in case any of them can be applied to your puzzle. (Not all of these
  4009. methods will work, or in some cases even make sense, for all
  4010. puzzles.)
  4011. Some puzzles are mathematically tractable, meaning you can work out
  4012. in advance which instances are soluble. Sixteen, for example, has a
  4013. parity constraint in some settings which renders exactly half the
  4014. game space unreachable, but it can be mathematically proved that any
  4015. position not in that half \e{is} reachable. Therefore, Sixteen's
  4016. grid generation simply consists of selecting at random from a well
  4017. defined subset of the game space. Cube in its default state is even
  4018. easier: \e{every} possible arrangement of the blue squares and the
  4019. cube's starting position is soluble!
  4020. Another option is to redefine what you mean by \q{soluble}. Black
  4021. Box takes this approach. There are layouts of balls in the box which
  4022. are completely indistinguishable from one another no matter how many
  4023. beams you fire into the box from which angles, which would normally
  4024. be grounds for declaring those layouts unfair; but fortunately,
  4025. detecting that indistinguishability is computationally easy. So
  4026. Black Box doesn't demand that your ball placements match its own; it
  4027. merely demands that your ball placements be \e{indistinguishable}
  4028. from the ones it was thinking of. If you have an ambiguous puzzle,
  4029. then any of the possible answers is considered to be a solution.
  4030. Having redefined the rules in that way, any puzzle is soluble again.
  4031. Those are the simple techniques. If they don't work, you have to get
  4032. cleverer.
  4033. One way to generate a soluble puzzle is to start from the solved
  4034. state and make inverse moves until you reach a starting state. Then
  4035. you know there's a solution, because you can just list the inverse
  4036. moves you made and make them in the opposite order to return to the
  4037. solved state.
  4038. This method can be simple and effective for puzzles where you get to
  4039. decide what's a starting state and what's not. In Pegs, for example,
  4040. the generator begins with one peg in the centre of the board and
  4041. makes inverse moves until it gets bored; in this puzzle, valid
  4042. inverse moves are easy to detect, and \e{any} state that's reachable
  4043. from the solved state by inverse moves is a reasonable starting
  4044. position. So Pegs just continues making inverse moves until the
  4045. board satisfies some criteria about extent and density, and then
  4046. stops and declares itself done.
  4047. For other puzzles, it can be a lot more difficult. Same Game uses
  4048. this strategy too, and it's lucky to get away with it at all: valid
  4049. inverse moves aren't easy to find (because although it's easy to
  4050. insert additional squares in a Same Game position, it's difficult to
  4051. arrange that \e{after} the insertion they aren't adjacent to any
  4052. other squares of the same colour), so you're constantly at risk of
  4053. running out of options and having to backtrack or start again. Also,
  4054. Same Game grids never start off half-empty, which means you can't
  4055. just stop when you run out of moves \dash you have to find a way to
  4056. fill the grid up \e{completely}.
  4057. The other way to generate a puzzle that's soluble is to start from
  4058. the other end, and actually write a \e{solver}. This tends to ensure
  4059. that a puzzle has a \e{unique} solution over and above having a
  4060. solution at all, so it's a good technique to apply to puzzles for
  4061. which that's important.
  4062. One theoretical drawback of generating soluble puzzles by using a
  4063. solver is that your puzzles are restricted in difficulty to those
  4064. which the solver can handle. (Most solvers are not fully general:
  4065. many sets of puzzle rules are NP-complete or otherwise nasty, so
  4066. most solvers can only handle a subset of the theoretically soluble
  4067. puzzles.) It's been my experience in practice, however, that this
  4068. usually isn't a problem; computers are good at very different things
  4069. from humans, and what the computer thinks is nice and easy might
  4070. still be pleasantly challenging for a human. For example, when
  4071. solving Dominosa puzzles I frequently find myself using a variety of
  4072. reasoning techniques that my solver doesn't know about; in
  4073. principle, therefore, I should be able to solve the puzzle using
  4074. only those techniques it \e{does} know about, but this would involve
  4075. repeatedly searching the entire grid for the one simple deduction I
  4076. can make. Computers are good at this sort of exhaustive search, but
  4077. it's been my experience that human solvers prefer to do more complex
  4078. deductions than to spend ages searching for simple ones. So in many
  4079. cases I don't find my own playing experience to be limited by the
  4080. restrictions on the solver.
  4081. (This isn't \e{always} the case. Solo is a counter-example;
  4082. generating Solo puzzles using a simple solver does lead to
  4083. qualitatively easier puzzles. Therefore I had to make the Solo
  4084. solver rather more advanced than most of them.)
  4085. There are several different ways to apply a solver to the problem of
  4086. generating a soluble puzzle. I list a few of them below.
  4087. The simplest approach is brute force: randomly generate a puzzle,
  4088. use the solver to see if it's soluble, and if not, throw it away and
  4089. try again until you get lucky. This is often a viable technique if
  4090. all else fails, but it tends not to scale well: for many puzzle
  4091. types, the probability of finding a uniquely soluble instance
  4092. decreases sharply as puzzle size goes up, so this technique might
  4093. work reasonably fast for small puzzles but take (almost) forever at
  4094. larger sizes. Still, if there's no other alternative it can be
  4095. usable: Pattern and Dominosa both use this technique. (However,
  4096. Dominosa has a means of tweaking the randomly generated grids to
  4097. increase the \e{probability} of them being soluble, by ruling out
  4098. one of the most common ambiguous cases. This improved generation
  4099. speed by over a factor of 10 on the highest preset!)
  4100. An approach which can be more scalable involves generating a grid
  4101. and then tweaking it to make it soluble. This is the technique used
  4102. by Mines and also by Net: first a random puzzle is generated, and
  4103. then the solver is run to see how far it gets. Sometimes the solver
  4104. will get stuck; when that happens, examine the area it's having
  4105. trouble with, and make a small random change in that area to allow
  4106. it to make more progress. Continue solving (possibly even without
  4107. restarting the solver), tweaking as necessary, until the solver
  4108. finishes. Then restart the solver from the beginning to ensure that
  4109. the tweaks haven't caused new problems in the process of solving old
  4110. ones (which can sometimes happen).
  4111. This strategy works well in situations where the usual solver
  4112. failure mode is to get stuck in an easily localised spot. Thus it
  4113. works well for Net and Mines, whose most common failure mode tends
  4114. to be that most of the grid is fine but there are a few widely
  4115. separated ambiguous sections; but it would work less well for
  4116. Dominosa, in which the way you get stuck is to have scoured the
  4117. whole grid and not found anything you can deduce \e{anywhere}. Also,
  4118. it relies on there being a low probability that tweaking the grid
  4119. introduces a new problem at the same time as solving the old one;
  4120. Mines and Net also have the property that most of their deductions
  4121. are local, so that it's very unlikely for a tweak to affect
  4122. something half way across the grid from the location where it was
  4123. applied. In Dominosa, by contrast, a lot of deductions use
  4124. information about half the grid (\q{out of all the sixes, only one
  4125. is next to a three}, which can depend on the values of up to 32 of
  4126. the 56 squares in the default setting!), so this tweaking strategy
  4127. would be rather less likely to work well.
  4128. A more specialised strategy is that used in Solo and Slant. These
  4129. puzzles have the property that they derive their difficulty from not
  4130. presenting all the available clues. (In Solo's case, if all the
  4131. possible clues were provided then the puzzle would already be
  4132. solved; in Slant it would still require user action to fill in the
  4133. lines, but it would present no challenge at all). Therefore, a
  4134. simple generation technique is to leave the decision of which clues
  4135. to provide until the last minute. In other words, first generate a
  4136. random \e{filled} grid with all possible clues present, and then
  4137. gradually remove clues for as long as the solver reports that it's
  4138. still soluble. Unlike the methods described above, this technique
  4139. \e{cannot} fail \dash once you've got a filled grid, nothing can
  4140. stop you from being able to convert it into a viable puzzle.
  4141. However, it wouldn't even be meaningful to apply this technique to
  4142. (say) Pattern, in which clues can never be left out, so the only way
  4143. to affect the set of clues is by altering the solution.
  4144. (Unfortunately, Solo is complicated by the need to provide puzzles
  4145. at varying difficulty levels. It's easy enough to generate a puzzle
  4146. of \e{at most} a given level of difficulty; you just have a solver
  4147. with configurable intelligence, and you set it to a given level and
  4148. apply the above technique, thus guaranteeing that the resulting grid
  4149. is solvable by someone with at most that much intelligence. However,
  4150. generating a puzzle of \e{at least} a given level of difficulty is
  4151. rather harder; if you go for \e{at most} Intermediate level, you're
  4152. likely to find that you've accidentally generated a Trivial grid a
  4153. lot of the time, because removing just one number is sufficient to
  4154. take the puzzle from Trivial straight to Ambiguous. In that
  4155. situation Solo has no remaining options but to throw the puzzle away
  4156. and start again.)
  4157. A final strategy is to use the solver \e{during} puzzle
  4158. construction: lay out a bit of the grid, run the solver to see what
  4159. it allows you to deduce, and then lay out a bit more to allow the
  4160. solver to make more progress. There are articles on the web that
  4161. recommend constructing Sudoku puzzles by this method (which is
  4162. completely the opposite way round to how Solo does it); for Sudoku
  4163. it has the advantage that you get to specify your clue squares in
  4164. advance (so you can have them make pretty patterns).
  4165. Rectangles uses a strategy along these lines. First it generates a
  4166. grid by placing the actual rectangles; then it has to decide where
  4167. in each rectangle to place a number. It uses a solver to help it
  4168. place the numbers in such a way as to ensure a unique solution. It
  4169. does this by means of running a test solver, but it runs the solver
  4170. \e{before} it's placed any of the numbers \dash which means the
  4171. solver must be capable of coping with uncertainty about exactly
  4172. where the numbers are! It runs the solver as far as it can until it
  4173. gets stuck; then it narrows down the possible positions of a number
  4174. in order to allow the solver to make more progress, and so on. Most
  4175. of the time this process terminates with the grid fully solved, at
  4176. which point any remaining number-placement decisions can be made at
  4177. random from the options not so far ruled out. Note that unlike the
  4178. Net/Mines tweaking strategy described above, this algorithm does not
  4179. require a checking run after it completes: if it finishes
  4180. successfully at all, then it has definitely produced a uniquely
  4181. soluble puzzle.
  4182. Most of the strategies described above are not 100% reliable. Each
  4183. one has a failure rate: every so often it has to throw out the whole
  4184. grid and generate a fresh one from scratch. (Solo's strategy would
  4185. be the exception, if it weren't for the need to provide configurable
  4186. difficulty levels.) Occasional failures are not a fundamental
  4187. problem in this sort of work, however: it's just a question of
  4188. dividing the grid generation time by the success rate (if it takes
  4189. 10ms to generate a candidate grid and 1/5 of them work, then it will
  4190. take 50ms on average to generate a viable one), and seeing whether
  4191. the expected time taken to \e{successfully} generate a puzzle is
  4192. unacceptably slow. Dominosa's generator has a very low success rate
  4193. (about 1 out of 20 candidate grids turn out to be usable, and if you
  4194. think \e{that's} bad then go and look at the source code and find
  4195. the comment showing what the figures were before the generation-time
  4196. tweaks!), but the generator itself is very fast so this doesn't
  4197. matter. Rectangles has a slower generator, but fails well under 50%
  4198. of the time.
  4199. So don't be discouraged if you have an algorithm that doesn't always
  4200. work: if it \e{nearly} always works, that's probably good enough.
  4201. The one place where reliability is important is that your algorithm
  4202. must never produce false positives: it must not claim a puzzle is
  4203. soluble when it isn't. It can produce false negatives (failing to
  4204. notice that a puzzle is soluble), and it can fail to generate a
  4205. puzzle at all, provided it doesn't do either so often as to become
  4206. slow.
  4207. One last piece of advice: for grid-based puzzles, when writing and
  4208. testing your generation algorithm, it's almost always a good idea
  4209. \e{not} to test it initially on a grid that's square (i.e.
  4210. \cw{w==h}), because if the grid is square then you won't notice if
  4211. you mistakenly write \c{h} instead of \c{w} (or vice versa)
  4212. somewhere in the code. Use a rectangular grid for testing, and any
  4213. size of grid will be likely to work after that.
  4214. \S{writing-textformats} Designing textual description formats
  4215. Another aspect of writing a puzzle which is worth putting some
  4216. thought into is the design of the various text description formats:
  4217. the format of the game parameter encoding, the game description
  4218. encoding, and the move encoding.
  4219. The first two of these should be reasonably intuitive for a user to
  4220. type in; so provide some flexibility where possible. Suppose, for
  4221. example, your parameter format consists of two numbers separated by
  4222. an \c{x} to specify the grid dimensions (\c{10x10} or \c{20x15}),
  4223. and then has some suffixes to specify other aspects of the game
  4224. type. It's almost always a good idea in this situation to arrange
  4225. that \cw{decode_params()} can handle the suffixes appearing in any
  4226. order, even if \cw{encode_params()} only ever generates them in one
  4227. order.
  4228. These formats will also be expected to be reasonably stable: users
  4229. will expect to be able to exchange game IDs with other users who
  4230. aren't running exactly the same version of your game. So make them
  4231. robust and stable: don't build too many assumptions into the game ID
  4232. format which will have to be changed every time something subtle
  4233. changes in the puzzle code.
  4234. \H{writing-howto} Common how-to questions
  4235. This section lists some common things people want to do when writing
  4236. a puzzle, and describes how to achieve them within the Puzzles
  4237. framework.
  4238. \S{writing-howto-redraw} Redrawing just the changed parts of the window
  4239. Redrawing the entire window on every move is wasteful. If the user
  4240. makes a move changing only one square of a grid, it's better to redraw
  4241. just that square.
  4242. (Yes, computers are fast these days, but these puzzles still try to be
  4243. portable to devices at the less fast end of the spectrum, so it's
  4244. still worth saving effort where it's easy. On the other hand, some
  4245. puzzles just \e{can't} do this easily \dash Untangle is an example
  4246. that really does have no better option than to redraw everything.)
  4247. For a typical grid-oriented puzzle, a robust way to do this is:
  4248. \b Invent a data representation that describes everything about the
  4249. appearance of a grid cell in the puzzle window.
  4250. \b Have \c{game_drawstate} contain an array of those, describing the
  4251. current appearance of each cell, as it was last drawn in the window.
  4252. \b In \cw{redraw()}, loop over each cell deciding what the new
  4253. appearance should be. If it's not the same as the value stored in
  4254. \c{game_drawstate}, then redraw that cell, and update the entry in the
  4255. \c{game_drawstate} array.
  4256. Where possible, I generally make my data representation an integer
  4257. full of bit flags, to save space, and to make it easy to compare the
  4258. old and new versions. If yours needs to be bigger than that, you may
  4259. have to define a small \cw{struct} and write an equality-checking
  4260. function.
  4261. The data representation of the \e{appearance} of a square in
  4262. \c{game_drawstate} will not generally be identical to the
  4263. representation of the \e{logical state} of a square in \c{game_state},
  4264. because many things contribute to a square's appearance other than its
  4265. logical state. For example:
  4266. \b Extra information overlaid on the square by the user interface,
  4267. such as a keyboard-controlled cursor, or highlighting of squares
  4268. currently involved in a mouse drag action.
  4269. \b Error highlights marking violations of the puzzle constraints.
  4270. \b Visual intrusions into one square because of things in nearby
  4271. squares. For example, if you draw thick lines along the edges between
  4272. grid squares, then the corners of those lines will be visible in
  4273. logically unrelated squares. An entry in the \c{game_drawstate} array
  4274. should describe a specific \e{rectangular area of the screen}, so that
  4275. those areas can be erased and redrawn independently \dash so it must
  4276. represent anything that appears in that area, even if it's sticking
  4277. out from a graphic that logically lives in some other square.
  4278. \b Temporary changes to the appearance of a square because of an
  4279. ongoing completion flash.
  4280. \b The current display mode, if a game provides more than one. (For
  4281. example, the optional letters distinguishing the different coloured
  4282. pegs in Guess.)
  4283. All of this must be included in the \c{game_drawstate} representation,
  4284. but should not be in the \c{game_state} at all. \cw{redraw()} will
  4285. pull it all together from the \c{game_state}, the \c{game_ui}, and the
  4286. animation and flash parameters.
  4287. To make sure that \e{everything} affecting a square's appearance is
  4288. included in this representation, it's a good idea to have a separate
  4289. function for drawing a grid square, and deliberately \e{not} pass it a
  4290. copy of the \c{game_state} or the \c{game_ui} at all. That way, if you
  4291. want that function to draw anything differently, you \e{have} to do it
  4292. by including that information in the representation of a square's
  4293. appearance.
  4294. But of course there are a couple of exceptions to this rule. A few
  4295. things \e{don't} have to go in the \c{game_drawstate} array, and can
  4296. safely be passed separately to the redraw-square function:
  4297. \b Anything that remains completely fixed throughout the whole of a
  4298. game, such as the clues provided by the puzzle. This is safe because a
  4299. \c{game_drawstate} is never reused between puzzle instances: when you
  4300. press New Game, a new \c{game_drawstate} will always be created from
  4301. scratch. So the \c{game_drawstate} only needs to describe everything
  4302. that might \e{change} during gameplay. If you have a sub-\cw{struct}
  4303. in your \c{game_state} that describes immutable properties of the
  4304. current game, as suggested in \k{writing-ref-counting}, then it's safe
  4305. to pass \e{that substructure} to the redraw-square function, and have
  4306. it retrieve that information directly.
  4307. \b How far through a move animation the last redraw was. When
  4308. \cw{redraw()} is called multiple times during an animated move, it's
  4309. much easier to just assume that any square involved in the animation
  4310. will \e{always} need redrawing. So \c{anim_length} can safely be
  4311. passed separately to the redraw-square function \dash but you also
  4312. have to remember to redraw a square if \e{either} its appearance is
  4313. different from the last redraw \e{or} it's involved in an animation.
  4314. \S{writing-howto-cursor} Drawing an object at only one position
  4315. A common phenomenon is to have an object described in the
  4316. \c{game_state} or the \c{game_ui} which can only be at one position.
  4317. A cursor \dash probably specified in the \c{game_ui} \dash is a good
  4318. example.
  4319. In the \c{game_ui}, it would \e{obviously} be silly to have an array
  4320. covering the whole game grid with a boolean flag stating whether the
  4321. cursor was at each position. Doing that would waste space, would
  4322. make it difficult to find the cursor in order to do anything with
  4323. it, and would introduce the potential for synchronisation bugs in
  4324. which you ended up with two cursors or none. The obviously sensible
  4325. way to store a cursor in the \c{game_ui} is to have fields directly
  4326. encoding the cursor's coordinates.
  4327. However, it is a mistake to assume that the same logic applies to the
  4328. \c{game_drawstate}. If you replicate the cursor position fields in the
  4329. draw state, the redraw code will get very complicated. In the draw
  4330. state, in fact, it \e{is} probably the right thing to have a cursor
  4331. flag for every position in the grid, and make it part of the
  4332. representation of each square's appearance, as described in
  4333. \k{writing-howto-redraw}. So when you iterate over each square in
  4334. \c{redraw()} working out its position, you set the \q{cursor here}
  4335. flag in the representation of the square's appearance, if its
  4336. coordinates match the cursor coordinates stored in the \c{game_ui}.
  4337. This will automatically ensure that when the cursor moves, the redraw
  4338. loop will redraw the square that \e{previously} contained the cursor
  4339. and doesn't any more, and the one that now contains the cursor.
  4340. \S{writing-keyboard-cursor} Implementing a keyboard-controlled cursor
  4341. It is often useful to provide a keyboard control method in a
  4342. basically mouse-controlled game. A keyboard-controlled cursor is
  4343. best implemented by storing its location in the \c{game_ui} (since
  4344. if it were in the \c{game_state} then the user would have to
  4345. separately undo every cursor move operation). So the procedure would
  4346. be:
  4347. \b Put cursor position fields in the \c{game_ui}.
  4348. \b \cw{interpret_move()} responds to arrow keys by modifying the
  4349. cursor position fields and returning \cw{MOVE_UI_UPDATE}.
  4350. \b \cw{interpret_move()} responds to some other button \dash either
  4351. \cw{CURSOR_SELECT} or some more specific thing like a number key \dash
  4352. by actually performing a move based on the current cursor location.
  4353. \b You might want an additional \c{game_ui} field stating whether
  4354. the cursor is currently visible, and having it disappear when a
  4355. mouse action occurs (so that it doesn't clutter the display when not
  4356. actually in use).
  4357. \b You might also want to automatically hide the cursor in
  4358. \cw{changed_state()} when the current game state changes to one in
  4359. which there is no move to make (which is the case in some types of
  4360. completed game).
  4361. \b \cw{redraw()} draws the cursor using the technique described in
  4362. \k{writing-howto-cursor}.
  4363. \S{writing-howto-dragging} Implementing draggable sprites
  4364. Some games have a user interface which involves dragging some sort
  4365. of game element around using the mouse. If you need to show a
  4366. graphic moving smoothly over the top of other graphics, use a
  4367. blitter (see \k{drawing-blitter} for the blitter API) to save the
  4368. background underneath it. The typical scenario goes:
  4369. \b Have a blitter field in the \c{game_drawstate}.
  4370. \b Set the blitter field to \cw{NULL} in the game's
  4371. \cw{new_drawstate()} function, since you don't yet know how big the
  4372. piece of saved background needs to be.
  4373. \b In the game's \cw{set_size()} function, once you know the size of
  4374. the object you'll be dragging around the display and hence the
  4375. required size of the blitter, actually allocate the blitter.
  4376. \b In \cw{free_drawstate()}, free the blitter if it's not \cw{NULL}.
  4377. \b In \cw{interpret_move()}, respond to mouse-down and mouse-drag
  4378. events by updating some fields in the \cw{game_ui} which indicate
  4379. that a drag is in progress.
  4380. \b At the \e{very end} of \cw{redraw()}, after all other drawing has
  4381. been done, draw the moving object if there is one. First save the
  4382. background under the object in the blitter; then set a clip
  4383. rectangle covering precisely the area you just saved (just in case
  4384. anti-aliasing or some other error causes your drawing to go beyond
  4385. the area you saved). Then draw the object, and call \cw{unclip()}.
  4386. Finally, set a flag in the \cw{game_drawstate} that indicates that
  4387. the blitter needs restoring.
  4388. \b At the very start of \cw{redraw()}, before doing anything else at
  4389. all, check the flag in the \cw{game_drawstate}, and if it says the
  4390. blitter needs restoring then restore it. (Then clear the flag, so
  4391. that this won't happen again in the next redraw if no moving object
  4392. is drawn this time.)
  4393. This way, you will be able to write the rest of the redraw function
  4394. completely ignoring the dragged object, as if it were floating above
  4395. your bitmap and being completely separate.
  4396. \S{writing-ref-counting} Sharing large invariant data between all
  4397. game states
  4398. In some puzzles, there is a large amount of data which never changes
  4399. between game states. The array of numbers in Dominosa is a good
  4400. example.
  4401. You \e{could} dynamically allocate a copy of that array in every
  4402. \c{game_state}, and have \cw{dup_game()} make a fresh copy of it for
  4403. every new \c{game_state}; but it would waste memory and time. A
  4404. more efficient way is to use a reference-counted structure.
  4405. \b Define a structure type containing the data in question, and also
  4406. containing an integer reference count.
  4407. \b Have a field in \c{game_state} which is a pointer to this
  4408. structure.
  4409. \b In \cw{new_game()}, when creating a fresh game state at the start
  4410. of a new game, create an instance of this structure, initialise it
  4411. with the invariant data, and set its reference count to 1.
  4412. \b In \cw{dup_game()}, rather than making a copy of the structure
  4413. for the new game state, simply set the new game state to point at
  4414. the same copy of the structure, and increment its reference count.
  4415. \b In \cw{free_game()}, decrement the reference count in the
  4416. structure pointed to by the game state; if the count reaches zero,
  4417. free the structure.
  4418. This way, the invariant data will persist for only as long as it's
  4419. genuinely needed; \e{as soon} as the last game state for a
  4420. particular puzzle instance is freed, the invariant data for that
  4421. puzzle will vanish as well. Reference counting is a very efficient
  4422. form of garbage collection, when it works at all. (Which it does in
  4423. this instance, of course, because there's no possibility of circular
  4424. references.)
  4425. \S{writing-flash-types} Implementing multiple types of flash
  4426. In some games you need to flash in more than one different way.
  4427. Mines, for example, flashes white when you win, and flashes red when
  4428. you tread on a mine and die.
  4429. The simple way to do this is:
  4430. \b Have a field in the \c{game_ui} which describes the type of flash.
  4431. \b In \cw{flash_length()}, examine the old and new game states to
  4432. decide whether a flash is required and what type. Write the type of
  4433. flash to the \c{game_ui} field whenever you return non-zero.
  4434. \b In \cw{redraw()}, when you detect that \c{flash_time} is
  4435. non-zero, examine the field in \c{game_ui} to decide which type of
  4436. flash to draw.
  4437. \cw{redraw()} will never be called with \c{flash_time} non-zero
  4438. unless \cw{flash_length()} was first called to tell the mid-end that
  4439. a flash was required; so whenever \cw{redraw()} notices that
  4440. \c{flash_time} is non-zero, you can be sure that the field in
  4441. \c{game_ui} is correctly set.
  4442. \S{writing-move-anim} Animating game moves
  4443. A number of puzzle types benefit from a quick animation of each move
  4444. you make.
  4445. For some games, such as Fifteen, this is particularly easy. Whenever
  4446. \cw{redraw()} is called with \c{oldstate} non-\cw{NULL}, Fifteen
  4447. simply compares the position of each tile in the two game states,
  4448. and if the tile is not in the same place then it draws it some
  4449. fraction of the way from its old position to its new position. This
  4450. method copes automatically with undo.
  4451. Other games are less obvious. In Sixteen, for example, you can't
  4452. just draw each tile a fraction of the way from its old to its new
  4453. position: if you did that, the end tile would zip very rapidly past
  4454. all the others to get to the other end and that would look silly.
  4455. (Worse, it would look inconsistent if the end tile was drawn on top
  4456. going one way and on the bottom going the other way.)
  4457. A useful trick here is to define a field or two in the game state
  4458. that indicates what the last move was.
  4459. \b Add a \q{last move} field to the \c{game_state} (or two or more
  4460. fields if the move is complex enough to need them).
  4461. \b \cw{new_game()} initialises this field to a null value for a new
  4462. game state.
  4463. \b \cw{execute_move()} sets up the field to reflect the move it just
  4464. performed.
  4465. \b \cw{redraw()} now needs to examine its \c{dir} parameter. If
  4466. \c{dir} is positive, it determines the move being animated by
  4467. looking at the last-move field in \c{newstate}; but if \c{dir} is
  4468. negative, it has to look at the last-move field in \c{oldstate}, and
  4469. invert whatever move it finds there.
  4470. Note also that Sixteen needs to store the \e{direction} of the move,
  4471. because you can't quite determine it by examining the row or column
  4472. in question. You can in almost all cases, but when the row is
  4473. precisely two squares long it doesn't work since a move in either
  4474. direction looks the same. (You could argue that since moving a
  4475. 2-element row left and right has the same effect, it doesn't matter
  4476. which one you animate; but in fact it's very disorienting to click
  4477. the arrow left and find the row moving right, and almost as bad to
  4478. undo a move to the right and find the game animating \e{another}
  4479. move to the right.)
  4480. \S{writing-conditional-anim} Animating drag operations
  4481. In Untangle, moves are made by dragging a node from an old position
  4482. to a new position. Therefore, at the time when the move is initially
  4483. made, it should not be animated, because the node has already been
  4484. dragged to the right place and doesn't need moving there. However,
  4485. it's nice to animate the same move if it's later undone or redone.
  4486. This requires a bit of fiddling.
  4487. The obvious approach is to have a flag in the \c{game_ui} which
  4488. inhibits move animation, and to set that flag in
  4489. \cw{interpret_move()}. The question is, when would the flag be reset
  4490. again? The obvious place to do so is \cw{changed_state()}, which
  4491. will be called once per move. But it will be called \e{before}
  4492. \cw{anim_length()}, so if it resets the flag then \cw{anim_length()}
  4493. will never see the flag set at all.
  4494. The solution is to have \e{two} flags in a queue.
  4495. \b Define two flags in \c{game_ui}; let's call them \q{current} and
  4496. \q{next}.
  4497. \b Set both to \cw{false} in \c{new_ui()}.
  4498. \b When a drag operation completes in \cw{interpret_move()}, set the
  4499. \q{next} flag to \cw{true}.
  4500. \b Every time \cw{changed_state()} is called, set the value of
  4501. \q{current} to the value in \q{next}, and then set the value of
  4502. \q{next} to \cw{false}.
  4503. \b That way, \q{current} will be \cw{true} \e{after} a call to
  4504. \cw{changed_state()} if and only if that call to
  4505. \cw{changed_state()} was the result of a drag operation processed by
  4506. \cw{interpret_move()}. Any other call to \cw{changed_state()}, due
  4507. to an Undo or a Redo or a Restart or a Solve, will leave \q{current}
  4508. \cw{false}.
  4509. \b So now \cw{anim_length()} can request a move animation if and
  4510. only if the \q{current} flag is \e{not} set.
  4511. \S{writing-cheating} Inhibiting the victory flash when Solve is used
  4512. Many games flash when you complete them, as a visual congratulation
  4513. for having got to the end of the puzzle. It often seems like a good
  4514. idea to disable that flash when the puzzle is brought to a solved
  4515. state by means of the Solve operation.
  4516. This is easily done:
  4517. \b Add a \q{cheated} flag to the \c{game_state}.
  4518. \b Set this flag to \cw{false} in \cw{new_game()}.
  4519. \b Have \cw{solve()} return a move description string which clearly
  4520. identifies the move as a solve operation.
  4521. \b Have \cw{execute_move()} respond to that clear identification by
  4522. setting the \q{cheated} flag in the returned \c{game_state}. The
  4523. flag will then be propagated to all subsequent game states, even if
  4524. the user continues fiddling with the game after it is solved.
  4525. \b \cw{flash_length()} now returns non-zero if \c{oldstate} is not
  4526. completed and \c{newstate} is, \e{and} neither state has the
  4527. \q{cheated} flag set.
  4528. \H{writing-testing} Things to test once your puzzle is written
  4529. Puzzle implementations written in this framework are self-testing as
  4530. far as I could make them.
  4531. Textual game and move descriptions, for example, are generated and
  4532. parsed as part of the normal process of play. Therefore, if you can
  4533. make moves in the game \e{at all} you can be reasonably confident
  4534. that the mid-end serialisation interface will function correctly and
  4535. you will be able to save your game. (By contrast, if I'd stuck with
  4536. a single \cw{make_move()} function performing the jobs of both
  4537. \cw{interpret_move()} and \cw{execute_move()}, and had separate
  4538. functions to encode and decode a game state in string form, then
  4539. those functions would not be used during normal play; so they could
  4540. have been completely broken, and you'd never know it until you tried
  4541. to save the game \dash which would have meant you'd have to test
  4542. game saving \e{extensively} and make sure to test every possible
  4543. type of game state. As an added bonus, doing it the way I did leads
  4544. to smaller save files.)
  4545. There is one exception to this, which is the string encoding of the
  4546. \c{game_ui}. Most games do not store anything permanent in the
  4547. \c{game_ui}, and hence do not need to put anything in its encode and
  4548. decode functions; but if there is anything in there, you do need to
  4549. test game loading and saving to ensure those functions work
  4550. properly.
  4551. It's also worth testing undo and redo of all operations, to ensure
  4552. that the redraw and the animations (if any) work properly. Failing
  4553. to animate undo properly seems to be a common error.
  4554. Other than that, just use your common sense.