Showing posts with label twine. Show all posts
Showing posts with label twine. Show all posts

2014-12-06

Display text at end of passage macro for Twine

I was helping Harry Giles out with some modifications to his IFCOMP2014 entry Raik. It became useful to set text early in the passage that would be shown only at the end of the passage.

An easy way to achieve this in Twine with custom macros. They are <<atend>> ... <<atendd>>.

::PassageTitle
<<atend>>

This text appears at the end of the current passage.<<atendd>>And this text appears in the usual place.

How do you use this in your own projects? Add the following line to your StoryIncludes:

http://raw.githubusercontent.com/tweecode/TwineQuest/master/macros/9999%20Macro%20atend.twee

Why might you want this macro? Here are some examples. You be inside an <<if>> macro from which you want to set a choice to appear at the end of the passage. You might be using the excellent ReplaceMacros from Glorious Tranwrecks and want to have text that always appear at the end of the passage no matter what the state of the rest of the passage.
Please share / comment / like - your actions guide me on what to write about.

2014-11-19

IFCOMP14: The Entropy Cage Post-Mortem

The Entropy Cage (ifdb) was my entry to the 20th Interactive Fiction Competition (ifcomp2014). This post mortem is also posted in the Interactive Fiction Forums.

My thanks to all the players and reviewers. I’m overwhelmed; 14th was much higher than I expected. The reviewers (even the ones who disliked TEC) all gave me valuable feedback that help hone my craft.

Here are some random thoughts:

The feeling of the game was meant to capture how an out of their depth computer tech feels when there’s a major system meltdown. The boss is on their back being both helpful and accusatory (push-pull) while the tech bashes the keyboard hoping something will work. That feeling of awkwardness doesn’t make for a particularly fun experience so I shortened the game during testing to lessen the uncomfortable. The mechanic left no room for overtly showing progress or mastery so wasn’t a good choice of mechanic to base a game around and/or my execution was lacking.

I didn’t mention why the PC was on suspension. A few reviewers worked out that it was because the PC is actually out of their depth/incompetent. As the “first cyber-psychiatrist” there can’t have been a training course, industry accepted best practise or established performance indicators. There’s an underlying current of injustice because the PC feels they’ve been judged against invisible criteria. The PC has signed up for a job with a wizz-bang buzzword job description and the actual job has failed to deliver (psychiatry with that interface? are you kidding!) More than likely an overly-optimistic programmer (Jake) over-promised then underdelivered. The over-promises were then embellished by an HR person who glammed up the role to cover for a crappy salary with crappy T&Cs.

That does leave the question of why Jake gives the final big decision to you. Jake has no idea what to do! Rather than flipping a coin he gives the decision to you so that you can be scapegoated when it goes wrong. (Neither choice would 100% avoid negative consequences). The fore-shadowing to this are dialog choices where Jake mentions suing you and that Jake will insta-fire you if you threaten to bring in your lawyer.

Unfortunately the PC’s POV doesn’t give a particularly good lens into the religious war the subs are fighting. You only see the zombified subs (I’ve been bad, punish me) and the refugees. I will explore adding some “soldiers” into the mix to expose more of the battle story.

Starting with the alarm clock was noob. I’m cutting that whole scene. In terms of the game physics, it slightly alters how much your boss hates you and lets you choose a personality type that affects the game in only subtle ways. The scene is gone - and I get to remove a drug reference warning (the wake pills).

I want to write more in TEC universe.

True Random has interesting metaphysical implications relating to divine simplicity, tawhid and creation; a realisation I came to after reading Gregory Chaitin on Algorithmic Information Theory, the Omega Construct and Meta-biology. That’s pretty hard maths so I’ve tried to present some connotations of that via fiction.

Algorithmic governance and the related issue of big data are real world issues that have ethical dimensions we should probably discuss as a society rather than let things just happen. Driverless cars are the tip of the ice-berg.

And personhood; what rights do subsentients have? They are effectively our slaves. At what point do they become begin to the rights we accord our biological pets.

About that sub.punish() theme. Totally an accident. Sorry. It is going to be removed from the post-comp release. But, the ifcomp version will always live in the TEC cannon. The story would’ve been a very different one if I’d explored the sub/punish angle! I’m going to keep the term ‘sub’ (subsentient subroutine) but .punish() will become .reseed() to better fit with the theme. Those who enjoy innuendo still have an interesting angle with .reseed() but the terminology change provides a more solid clue to the overall theme of the work. Reseeding is a term used in pseudorandom number algorithms.

The science is pretty fleshed out in TEC: I’ll hope to reveal more of it in future works. But here’s a tidbit. Adding a bit to Base16 gives Base32, not Base17. TEC is consistent because the Forward Error Correcting codes cover a larger block of memory that contains more data than just the PID.
Why does changing error correction have anything to do with randomness? As a clue; Here’s some pseudocode that generates a truly random number:
> a = 000000000000000000000000000000000000
> b = 000000000000000000000000000000000000
> while a equals b, loop
> rand = number of the bit that is different between a and b?
The loop does exit because computers aren’t isolated from their environment.

And on construction:

I committed to the contest too late. I tried to enter last year but allowed IRL things to get in the way. This year I let IRL things slip in order to make IFCOMP. I’m glad I did because entering creatively re-energised me. I should’ve committed earlier so that I had more time to polish the game. The mainloop that controls the game pacing wasn’t written until the day before submission deadline. me.punish(): You may commence with the flagellation… hahaha actually no, really not my thing.

I considered not entering but decided that I NEEDED to. It’s been a rough several years and I’ve been creatively out of touch. My self-esteem needed to get an “achieve point” even if that was having participated into last place.

I suck at editing. No matter how many times I read and re-read, mistakes always slip through. I’ve put huge effort into improving but I’m not there yet. I’ll try to collab to get more testers and people with editing skill to help me; but I know collab will increase the lead-in time before I need to commit. I didn’t edit out all the universe specific jargon that added little to the game. Simu-sleeping, holosplays... ugh. Yeah, they paint the picture of the TEC universe but in the nugget sized TEC game they were distractions.

I intentionally aimed TEC towards the strengths of click-fics to give the pacing I wanted. TEC as a parser game would’ve been very different.

Thanks again to the reviewers for their feedback. I tried to personally thank you all, but it became too much to track.

The post-comp release of TEC will also be put into the Android Play Store. You’ll see me back next year and not necessarily with a story set in TEC universe. As much as I’d like to try enter more IntFic competitions, I still have IRL concerns. Whaddup PhD!

Play The Entropy Cage in your browser. Playtimes are about 15 minutes.

2014-08-27

While Loop Macro for Twine

One of the often requested features for Twine are proper loops. It has been possible to simulate loops with a recursion hack but that was ugly. Before we continue go and see the possibilities.

Yes. Those are nested while loops. Here's the code that makes it all happen:
<<set $j = 1>><<while $j lte 10>>
<<print $j>> countdown: <<set $i = 5>><<while $i gt 0>>
<<print $i>>... <<set $i = $i - 1>>
<<endwhile>> BOOM! 
<<set $j = $j + 1>>
<<endwhile>>

You've probably worked out the basic syntax (clever bunny) which is:
<<while $condition eq true>>
Do some stuff. 
NB: update the $condition or the loop will run to infinity.
<<endwhile>>

How do you use this in your own projects? Add the following line to your StoryIncludes:

http://github.com/tweecode/TwineQuest/raw/master/macros/9999%20Macro%20while.twee

You can also download the demo project and .twee file as a .zip archive.

Enjoy!

Please share / comment / like - your actions guide me on what to write about.

2014-08-25

Twine Game Story Authoring 1: Structuring Game stories with Pain and Progress

Twine is a versatile tool from writing game stories. It is freed from the imposition of somebody else's RighWayToDoThings framework and allows the author to focus on what is important to them. The downside is that the author must program everything they want themselves. A previous article discusses how Twine can be thought of from a programmers perspective but don't worry it that article makes little sense. This article is specifically about structuring game stories.

For our purposes, a game story has a mainloop because the story is driven by data. That data might be a map, character stats, an inventory or something else you can dream up. This style of story does not suit a hypertext branching narrative.

The over all structure of the story goes:
  1. Introduction Text
  2. Initialise Variables
  3. MainLoop Passage
  4. Actions Passages
  5. Check Conditions Passages
  6. End of Game Passages

I like examples, so here is a link to the Pleasure and Pain v1 (HTML | Twee) files. Try out the playable HTML version first then take a look at the Twee code in your favourite text editor. In twee new passages start on lines beginning with double colons ::passagename. Pain And Progress is a simple demonstration with two conditional variables. Let's examine the passages and their intent.

Start, RealStart, Instructions
These passages deal with beginning the story, giving background and the option for instructions if the reader so chooses. Here you might add extended about information and links to information about the story and the author.

InitGame
The game re-runs this passage whenever the game is (re)started. Initialise all the variables that your game uses in here. Twine itself does not require variables to be declared and initialised but that can cause awkward side effects if a game story is re-run. Imagine the reader picks up an axe in one play-through, then the $hasAxe variable is not reset and they suddenly have an axe on the next play-thru. Not good - but completely avoidable if ALL variables are initialised here.
Enclose the variable initialisations in a <<silently>> ... <<endsilently>> block so that you can add free-form comments to the variables that will not be seen by the user.
Once this passage has ended then control is passed to the MainEventLoop.

MainEventLoop
This is where the major action occurs. Typically the story might perform any engine initiated actions (e.g. random weather events, monster encounters), display status and provide a menu of actions.

MainStatus
Consider separating status displays so that they can be re-used.

MainActionPain, MainActionProgress
These passages are the entry points from user actions. They start by performing any action related things and then checking the game state. A flag variable $gameendflag lets the game story know if they should print user actions or not. The reason for this is that <<display>> will always return to the passage that invoked it and nothing further from these passages should be displayed if the game should end.

CheckPain, CheckProgress
Perform constraint checks in their own passages so that they can be re-used through the game story.

GameEndLose, GameEndWin, PlayAgain, PlayAgainNo
These passages deal with the game ending conditions. Game stories could expand this list for different ending conditions. The PlayAgain passage ensures that replays will begin again from the InitGame passage.

The Pain and Progress, the passage names are typically prefixed by their function, though prefixing by variable name is also valid. The idea is to make things as obvious as possible.

Hopefully this example will serve as a guide to structuring gamestories and encourage more Twine authors to try this type of story. If you found this guide useful then Share / Comment / Like - because it encourages me to write more on this topic.

Twine Thinking for Programmers

Programmers find Twine's hypertext way of doing things a little strange at first. Twine works well for branching hypertexts but needs some thinking for stories driven by variables. I've done a few game stories in twine - mostly conversions of early BASIC programs - so this is a lessons learned type of blog. You might find this article for useful for any Game Story; usually adventure games, RPGs.

Twine's basic unit is the passage. Passages work like procedure calls. Passages are similar to GOSUB in BASIC. By default passages print their content to the screen and you use tweecode macros to execute game logic.

Passages are "called" by the Twine engine in a few ways:
  • The Start passage is called to begin the story
  • Readers activating [[link]] or <<CHOICE>>
  • <<DISPLAY>> macro within passages.
The <<DISPLAY>> macro is the programmers GOSUB / procedure call. Twine has no GOTO equivalent: <<DISPLAY>> always RETURNs to the passage that called it. Anything after the <<DISPLAY>> macro will still be processed (and output if appropriate) by the Twine Engine. Use <<DISPLAY>> generously - it is the workhouse of programmer-like Twine and the basic unit of code re-use within a story.

Twine's tweecode has only global variables. This means that variables cannot be directly passed to passages - they are <<SET>> in global variable space before calling the <<DISPLAY>> function. Twine allows long variable names so use generous prefixes to distinguish variables.

Twine has no inbuilt loop constructs (for, do, while). Loop constructs can be built using <<IF>><<ELSE>><<ENDIF>> and passages. Here's a helpful article: How to Simulate for, while or do loops in Twine.
UPDATE: I've just released <<while>> macros.

Once your passage count gets higher Twine's diagram based UI can get unwieldy. Programmers used to text-based programming will find it more natural to write in TWEECODE and use the StoryIncludes feature to import files into a Twine Story. There is only a global namespace for passages so ensure that passage names are unique. Passages can be moved between the main Twine story file and included files as needed. Use StoryIncludes and tweecode files as the basic unit of code reuse between different stories.

Tweecode files are text files (UTF-8) that add a few extra things to the Twine macros already used. It's easiest to think of Tweecode files as a bucket of passages - for that most part Twine does not care about the order of passages. New passages begin with a single line passage header and end either when a new passage header begins or the file ends. A passage header begins a line with double colon (::) followed by the passage name. Optionally tags can be added space delimited with square brackets. Here's a brief example:
::Passage Title 1 [tag1 anothertag yet_another_tag]
This is part of passage one.

::Passage Title 2
more content

Twine allows complete access to JavaScript though consider keeping Javascript use to a minimum so that your story has fewer dependancies. If you do use javascript then consider placing custom scripts into their own tweecode files; both for your own reuse and to provide an easy way to find code if it must be later rewritten by future generations. Here are some useful articles: Once you get used to tracking state variables globally and how the <<DISPLAY>> macro always returns then it is only small extension to create event loop based games. I find it easier to work with example code so here's some classic game conversions with full source available: Please share / like comment: your actions influence what I decide to write about.

2013-08-19

Twine: Multiple files in one story using StoryIncludes

List your .tws or .twee files in a special passage titled "StoryIncludes" and recent v1.3.5 betas will import the passages from those files when your story's .html file is built.

Newest Twine alphas/betas are here.

2013-01-27

How to Insert Images into Twine Without Linking


UPDATE: Twine 1.4 makes this process much easier. Go to the "Story" menu and select "Import Image". The techniques in this article are still valid too.


Twine has enjoyed some recent popularity and it is great to see the diverse and wonderful things people do. Inserting images into Twine is something that has become popular but having to transport the image as a file separate to the Twine output .html introduces some additional complications. I like the single output file nature of Twine.

Look at this Twine demo:
http://eturnerx.com/files/twinehowto/ImageDataURI.html (source .tws)
There is an image stored in the .html file itself using a Data URI (RFC 2397). That image is not a separate linked file. You can check it yourself, I'll wait.

Data URIs contains the data for the image in an encoded string that is embedded into the html <img> element. This works fine in most recent browsers (IE 8+) but is only suitable for smallish files. For IE8 the limit is not much bigger than 20 kilobytes but other browsers (including IE9) work just fine with much larger file sizes.

It is surprising how much image can fit within 20 kilobytes just by playing with filetype, compression settings and reducing pixel dimensions. Most flat line drawings in a few colours will generally compress well as PNG or GIF. Scanned line drawings should have the contrast boosted and/or posterized to flatten the colours in the image. Photographs or scanned images generally work better as JPEGs.

Once you have a small image file then it will need converting to a Data URL. I like to use:
http://websemantics.co.uk/online_tools/image_to_data_uri_convertor/
They also have links to online tools that can further compress your image.

Here is the code that goes into your Twine passage:

<html><img width="11" height="14" src="data:image/gif;base64,R0lGOD
lhCwAOAMQfAP////7+/vj4+Hh4eHd3d/v7+/Dw8HV1dfLy8ubm5vX19e3t7fr
6+nl5edra2nZ2dnx8fMHBwYODg/b29np6eujo6JGRkeHh4eTk5LCwsN3d3dfX
13Jycp2dnevr6////yH5BAEAAB8ALAAAAAALAA4AAAVq4NFw1DNAX/o9imAsB
tKpxKRd1+YEWUoIiUoiEWEAApIDMLGoRCyWiKThenkwDgeGMiggDLEXQkDoTh
CKNLpQDgjeAsY7MHgECgx8YR8oHwNHfwADBACGh4EDA4iGAYAEBAcQIg0Dk
gcEIQA7" alt="File Icon"></html>

(data URI example from: http://dataurl.net/#about)

The <html>...</html> tells Twine to treat the code inside as raw HTML. The <img ...> is the HTML code for placing an image. The width="11" and height="14" code give the width and height of the image - you should change these to suit your image. The alt="..." code improves the accessibility of your file by giving a text alternative to your image. Most likely the code will work without a width, height or alt specified but it is considered good practise to include them if you can. The real magic happens inside src="...". That src is an abbreviation for "source" and normally that would link to an external file. Here we give it the data URI instead.

TIP: These data URIs can produce large walls of text that are annoying for you as an author to scroll past. What I suggest is to put all the image code into a different passage then use the <<display>> macro to.... ummm... yeah... display the image. This makes the image reusable anywhere in your story and keeps your text passages nice and tidy. Consider this abbreviated example... (:: Double colon is the passage title)

::Start
<<display "Image:Document Icon">>
This is my text and there is an image above.

::Image:Document Icon
<html><img ...></html>

Your Twine story can use both data URI images and normal "linked" images. And data URIs work just fine in CSS too; great for setting background patterns. (The thing in square brackets [] is a tag applied underneath the passage title).

::Stylesheet1 [stylesheet]
body {
  background-image:url(data:image/gif;base64,R0lGOD... etc );
}

You have the tool, go make something cool.

2013-01-07

Twine GameStory Recommendations I

Here are some Twine stories that demonstrate what skilled authors can do with Twine. These examples are selected to show some of the many story types or narrative structures that can be created with Twine. These are reviews that might contain minimal spoilers.

CYBERQUEEN by Porpentine
Transhuman. Surgical horror. Some good time-based visual text effects. The writing is very atmospheric and keeps shifting reality. When reality stablises I'm not sure you're happy with the result.
Minimum playtime: 15 mins

Stygia by Kitty Horrorshow
It's a grittier Monsters Inc for adults... hang on, it's a horror themed afterlife. Well written with a setting and backstory suited for a movie. Limited replayability but you won't mind.
Minimum playtime: 10mins

Cold Dead Fish by Chris Klimas
Chris is the creator of Twine. This story is rather linear with only a few choices that really matter. Much of Twine's capability is used to "chunk" the story into unfolding bites that allow for contemplation and re-reading time as the reader explores the parenthetical links. These asides are interesting to the setting, but would have choked the narrative if the story was strictly serial. The subject of the story is a gentleman and an enigmatic lady.
Minimum playtime: 15mins

Fake Nerd Girl Detector by Zoe Quinn
Twine used instead of a flow-chart. This technique allows more space to make an argument and allows the author to keep the ending a surprise.
Minimum playtime: 5mins - some replayability in exploring the various endings

Choose Your Own Anna Anthropy Interview by Cara Ellison
This one is a hypertext arrangement of an interview with Anna Anthropy. If you're familiar with Anna's work you can skip most of the "asides". If you're interested in Anna's take on something in particular then you can read that. The format enables more indepth and richly annotated interviews than an equivalent serial article could.
Minimum playtime: 5mins - though you could easily spend more time if the subject matter interests you

Time Quest by Dungeon Smash
This choose your own adventure is sophomoronically funny. You get to trip around time and even postulate on the nature of time itself. Twine is very easily suited to make these kinds of stories.
Minimum playtime: 10mins

That's it for this round-up. Until next time (undetermined), maybe you can check out my Twine conversions of some old text games.

2012-12-19

How to use Twine/Tweecode Variables and Macros from Custom Macro

This tutorial is aimed at people wanting to use JavaScript in their Twine stories. This is advanced topic and is not necessary for writing most stories. Twine's ease in integrating JavaScript was a key factor when I was evaluating interaction fiction systems. Please read the tutorial on creating a custom macro in Twine first.

Twine/Tweecode has the ability to use macros and variables. In the Responsive, Sugarcane and Jonah StoryFormats macros and variables are stored in a place where they are accessible by custom macros for both reading and writing.

All custom macros are stored in a global object called "macros". They can be referred to by name. The actual macro code is in the "handler" property.

macros["custommacro"].handler(place, macroName, params, parser);
macros["display"].handler(place, "display", [ "SomePassage" ], parser);

In most cases it is sufficient to pass the place and parser arguments given to your custom macro into the macro you are calling.

Now, onto Tweecode variables. In tweecode variables are prefixed with a dollar sign so that the parser knows to lookup the variablename.

<<set $variablename = 1>><<print $variablename>>
<<if $variablename eq 1>>Success<<endif>>

Tweecode stores variables in the JavaScript object: state.history[0].variables. They are stored without the $ dollar sign "sigil".

state.history[0].variables["customvariables"] = 1;
if(state.history[0].variables["customvariables"] == 1) { 
  //... 
}

Knowing how to reuse Twine's macros and working with variables set in Tweecode from within JavaScript custom macros (and vice versa) opens many possibilities.

2012-12-14

How to use Parameters and Variables in Custom Twine Macros

The last article looked at basic macros in Twine. We'll expand on that article by looking at parameters and using an internal variable. First the code example:

try {
  version.extensions['recallMacro'] = { major:1, minor:0, revision:0 };
  macros['recall'] = {
    handler: function(place, macroName, params, parser) {
      if(params.length > 0) {
        this.m = params[0];
      }
      new Wikifier(place, this.m);
    },
    init: function() {
      this.m = "A blank slate";
    },
    m: null,
  };
} catch(e) {
  throwError(place,"recall Setup Error: "+e.message); 
}

Let's go through the code a piece at a time (not necessarily in written order).

try {
  version.extensions['recallMacro'] = { major:1, minor:0, revision:0 };
  macros['recall'] = {
    ...
  };
} catch(e) {
  throwError(place,"recall Setup Error: "+e.message); 
}

This is boilerplate code that is explained in the last article.

    init: function() {
      this.m = "A blank slate";
    },
    m: null,

This code declares a variable as part of the macro called "m". Throughout the macro we refer to this variable using this.m. The variable is declared within the macro to avoid polluting the global namespace and to avoid variable name clashes there. Note that m is declared with an initial value of null and the value of m is set within the init() method. This practice makes the macro work better if the story is restarted without refreshing the page.

    handler: function(place, macroName, params, parser) {
      if(params.length > 0) {
        this.m = params[0];
      }
      new Wikifier(place, this.m);
    },

This code checks the length of the params array. If there is something in the params array then the first parameter is saved into this.m. In all cases the contents of this.m are printed.

Once you have added this macro to your story then try adding the following tweecode to a passage in your story:

Initial state: <<recall>>
Store John: <<recall John>>
Store Ben: <<recall Ben>>
What is stored?: <<recall>>

Using parameters and variables in Twine macros is a great way to increase the power of the macro. Storing variables as properties inside the macro object avoids any name clashes with other macros.

How to Create Custom Macros in Twine

This post is a technical article for the Twine hypertext authoring system. I will assume a passing knowledge of Twine/Tweecode and an intermediate knowledge of Javascript. This tutorial applies to version 1.3.5 of Twine - and even further still I assume the latest betas.

There is a bug in the current v1.3.5 Sugarcane and Jonah story formats; custom macros will not work during the display of the "Start" passage. The Responsive story format does not have this problem.

I'll start with a simple macro example then explain it line by line. Put this code into it's own passage. The passage title can be anything. Give the passage the tag "script"

try {
  version.extensions['macrodemoMacro'] = { 
    major:1, minor:0, revision:0 
  };
  macros['macrodemo'] = {
    handler: function(place, macroName, params, parser) {
      new Wikifier(place, "Hello World!");
    },
    init: function() { },
  };
} catch(e) {
  throwError(place,"macrodemo Setup Error: "+e.message); 
}

Let's go through the code a piece at a time (not necessarily in written order).

try {
  ...
} catch(e) {
  throwError(place,"macrodemo Setup Error: "+e.message); 
}

This code sets up basic Javascript exception handling to let you know via a popup dialog when there is a problem in the macro code. Custom macros are inserted into the page at runtime so they can be difficult to debug. This exception handler makes things a bit easier. Technically this is optional, but trust me, it's worth adding. Just change the "macrodemo" text to the name of your macro so you can tell multiple custom macros apart.

  version.extensions['macrodemoMacro'] = { 
    major:1, minor:0, revision:0 
  };

This statement registers the macro with an extensions array. This is totally optional and appears to currently have no effect. If you are making a macro for re-use in many stories then it's a good idea to store version information so why not do it here. Maybe one day it'll be useful. I've taken the macro name and appended "Macro" just to be consistent with the way Twine's in built macros are registered.

  macros['macrodemo'] = {
  ...
  };

This creates the javascript object that holds the custom macro. The macro name in this case is "macrodemo" and you should change this to suit. The title of a macro should not contain spaces, double quotes or any characters that might confuse twine. There are two required functions and you can also add any other macro related variables inside the object.

    init: function() { },

This function is called when Twine is setting up the macro object when the story is started. This is where you should also initialise any variables because init() is called whenever the story is restarted. In many cases an empty function (as above) works just fine. There is no guarantee which order init() functions will be called, except that generally the inbuilt macros have their init() method called first.

    handler: function(place, macroName, params, parser) {
      new Wikifier(place, "Hello World!");
    },

This is the actual code that is executed when your macro is called. A macro is passed four parameters, the most important of which are "place" (an HTMLContainer where text is currently being output to) and "params" (any parameters passed to the macro). Parameters are split into an array on space characters except within "double quotes". The macroName parameter is self-explanatory. The parser gives a reference to the current Tiddlywiki parser object - which is useful only for some advanced cases; e.g. if you were writing a macro that has a corresponding end macro: see the inbuilt if, else and endif macros or my while loop macro for examples.

The example code here shows how to do simple text output which is added in place of the macro call. Most Twine macros will want to do something similar to this.

Once the macro is in place then somewhere in your Twine story go:

Custom macro: <<macrodemo>> 

Rebuild the story and you should see Hello World! Congratulations you have written your first macro.

BUG: Backslash characters do not encode / decode correctly from the passage store. Use a workaround such as: String.fromCharCode(92).

TIP: Since the latest betas support multiple source files via StoryIncludes, I like to put macros into separate text (.twee) files just to make organisation and reuse easier.

Macros are a powerful way of adding functionality to your Twine stories. The full power of Javascript is available to you. If you make a good macro then please share.

2012-11-08

How to Simulate for, while or do loops in Twine


UPDATE:I have written a proper <<while>> macro. The techniques below will still work but you'll probably find the new macro much easier.


Tweecode (used by Twine) does not have any notion of a loop but they can be simulated with <<if>>, <<set>> and <<display>> macros. The trick is a computer science trick called recursion where a piece of code repeatedly calls itself. So just think of passages as pieces of tweecode (functions) and the <<display>> macro as the "Call Function" command.

An example while loop

::Start
You knock at the door; <<display "WhileLoopDemo">>
The door is answered by a sleepy giant.


::WhileLoopDemo
<<if Math.floor(Math.random()*100) lt 70>>
knock <<display "WhileLoopDemo">>
<<endif>>

The Math.floor(Math.random()*100) code selects a random number from 0 to 99. See how the loop passage keeps on calling itself, until finally there will be a random number 70 or greater and the passage will exit back to where it left off in the start passage.
Demo, Code: .tws | .twee

An example for loop

::Start
Example for loop demo. <<set $i = 0>><<display "ForLoopDemo">>
Done!

::ForLoopDemo
<<if $i lte 5>>
<<print $i>>... <<set $i = $i + 1>><<display "ForLoopDemo">>
<<endif>>

The for loop example is slightly more complex because it must setup a counting variable and increment this on every iteration of the loop.
Demo, Code: .tws | .twee

Note: The double-colon :: denotes the start of a new passage. The rest of the line following the double-colon, up to an option opening square bracket [, is the passage title. This text following the start of passage (until the passage start) is a the body of the passage.

It is possible to create custom macros that would make loops in tweecode much easier; I might even do this one day. However, if your Interactive Fiction work is relying heavily on tons of loops then it is probably time to look at implementing that functionality in JavaScript directly for efficiency reasons.

The Nicomachus includes a demonstration of a loop in a fairly simple piece of code. If you're a JavaScript wiz then you might be interested in how to create your own macros. Let me know in the comments if there are other Twine related topics you'd like covered.

2012-11-04

Joust Conversion for Twine

Here is a conversion of Joust. This is another one of those games I copied from source in a book to learn how to program as a kid. Bringing these old games back to life is like paying my dues.

This is not a difficult game - you will play through it in just a few minutes. There is also not too much in the way of flavour text compared to other games. I'd rate it as about the same as Highnoon in terms of depth but the game play feels much less varied.

SPOILER: Once you work out a winning attack / defense combo then keep repeating it and let luck do the rest.

The game logic is entirely implemented in Twine/twee code. This could've been much simplified by using custom javascript macros to handle the logic branching or even by coding a "switch...case" macro system for twine to substitute for "ON X GOTO line, line ..." code from the original. I used if, else, endif blocks and despite being a bit complicated and verbose they did handle the task well enough.

Debugging something with such tricky logic wasn't easy but I used a couple of tricks. These might be useful to other Twine/twee code authors too.

TIP1: Debug nested if, else, endif blocks by copying into another text editor and indenting like a regular programming language.
Complex nesting of if, else, endif blocks can be annoying to debug. The are formatted in non-obvious ways to suit the needs of end display, not the programming. So, just for the purposes of debugging, try indenting it as if it is a programming language.

TIP2: Debug nested <<display>> chains with html comments. e.g. <html><!-- PassageNameX --></html>
Chasing around through multiple display macros gets hard. Add html comments to insert invisible stuff into the code so that you can inspect the page and track where the display macros are leading. It helps narrow down where the bugs are really quickly.

Checkout the other games I have converted

2012-10-28

Camel Conversion for Twine

Here is a conversion of Camel. I can vaguely remember coding and playing this game as a kid in the early '80s. If it left that kind of impression then it must've been a fun game so I decided to give this a shot for a Twine conversion. It is similar in many ways to Highnoon in that there is an underlying game system represented by some quirky text.

The game play can be frustrating! Oases appear frequently enough that water is almost never a problem (just don't forget to drink). The biggest problem is the pygmies. They have a 10% speed advantage on your moderate speed, but running your camel at full speed burns it out three times faster.

SPOLIER: The mathematically optimal strategy is to go full speed twice, moderate speed once then rest. Drink when warned (actually the turn after). If you are captured then wait for the ransom. Even with an optimal strategy a win is not assured. In this game the player loses more often than not. Prepare for frustration.

I made extensive use of the custom macro <<randomp>> that I made for another project. This simplified a lot of the handling where things were triggered by random events.

I intentionally left as much logic in place as it is in the BASIC code with a couple of small changes. The capture submenu display the request for sub-command before the menu and the "Miles travelled" text appears more than in the original. There was also something where asking for a status report would fall through to also taking a drink. I assumed that this was a bug and changed status report to not force a drink at the same time.

From the viewpoint of 2012 the text could appear offensive. I prefer to think of it is ironically anachronistic because there are many obviously mismatched facts and intentional mispellings. Many of the other books edited by David Ahl do contain some quite detailed information about the historical context of the games so I do not assume the authors of this game were naively flavouring the game they way they did.

Checkout the other games I have converted

2012-10-22

Nicomachus Conversion for Twine

Here is a conversion of Nicomachus for Twine. This was a much simpler program than Highnoon so I further restricted myself to making all program logic happen in Twine's tweecode.

Twine surprised me with its arithmetic handling. Up until now I had been ducking into Javascript for all but the simplest of expressions. Twine was easily able to handle an arithmetic statement with three sets of parentheses and about six terms.

Twine does lack a loop function (like a while). I was able to simulate this with an if, else, endif macro that keep displaying another passage (itself) until the condition expired. You can check the code for how I implemented this. The technique is known in computer science as recursion.

The verdict; A fun quick conversion.

Checkout the other games I have converted

2012-10-07

Highnoon Conversion for Twine

This week's creative project is a conversion of Highnoon for the Twine interactive fiction system. While I was converting/reimagining for Arduino I had two thoughts. The first was that I'd like to do a more faithful conversion with the original dialogue and secondly that such a conversion would be a way to demonstrate the power of Twine.

So, you know the game; You're in a showdown with Black Bart. You each have four shells and are 100 paces apart. In this original version there are more win/loss conditions than straight death.

Twine allows quite a lot of expressiveness and flexibility when writing interactive fiction. It also outputs the results to a single .html file that require no supporting libraries or other files. If you are interested in the basics of Twine then I'd suggest looking at this tutorial.

The conversion to Twine was fairly straightforward. I used the Jonah Story Format because it places passages one after the other without clearing the screen like Sugarcane does. I made a few tweaks to the inbuilt functions; the first to totally suppress the output of passage titles and the second to totally deactivate old choices. This was not difficult; it was more a matter of removing the bits of code from existing functions that I did not need.

I also based passage names around the line numbers in the original code. This eased moving from the GOTO style of the original code to the structured coding style of Twine.

The verdict; a very playable old-style game.

Checkout the other games I have converted