Category: Coding (Page 1 of 2)

Twine Game Data to Google Sheets via Javascript version 2

Using Twine, a free, open-source, text-based game software, you can build choose your own adventure games that explore the untaken paths in literaturepromote empathy through simulated experiences, and provide role-playing adventures in historical scenarios. Twine games are often used in the classroom, because you can quickly build an educational experience about whatever subject you choose. They are also heavily used in the interactive fiction world as a medium for short stories and novels.

I wrote the first version of this post back in October, while Keegan and I were the XP Twine workshop. In this post, I explained how to capture game data from Twine and push it into a Google Sheet. However, in discussing how to implement the original post with @hpkomic, I found out that the javascript code that I wrote back then was invalid because of something called CORS. There are many protections on the web to prevent people trying to inject malicious material into sites. CORS protections kick in when someone is trying to make changes on one domain from another domain, or “cross-origin.” My old code was not CORS compliant, so it didn’t work properly.

The first section of the code as the same as it was back in October. It’s the second section, “Twine Game Code,” that’s new.

Twine games take the form of HTML files with embedded CSS and JS. In my latest round of tinkering, I figured out how to use javascript within a Twine game to send an HTTP post message to pass game-play data to a Google Spreadsheet, thereby creating a database that records each game-play.

Google Sheet/Apps Script Code

In order to track this game data, I suggested that we push the data from Twine to a Google Spreadsheet. Following the lead of Tom Woodward, I’ve found that Google Spreadsheets are a relatively easy place to collect and analyze data. I wanted to use Google Scripts, which are mostly javascript and a few custom functions, to receive data and parse it into the cells of the Google Sheet.

Martin Hawksey wrote a blog post a few years ago called “Google Sheets as a Database – INSERT with Apps Script using POST/GET methods (with ajax example).” Martin had set up an Ajax form that could be embedded in any website that would pass data to his Google Script which would then record it in his Google Sheet. Martin’s code (below) receives an HTTP Get or Post call generated by an Ajax form, parses the parameters of that HTTP call, and stores those parameters in a Google Sheet. Martin also provides comments in his code to help users customize the Google script and initiate it as a Web App.

//  1. Enter sheet name where data is to be written below
        var SHEET_NAME = "DATA";
//  2. Run > setup
//  3. Publish > Deploy as web app 
//    - enter Project Version name and click 'Save New Version' 
//    - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously) 
//  4. Copy the 'Current web app URL' and post this in your form/script action 
//  5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
// If you don't want to expose either GET or POST methods you can comment out the appropriate function
function doGet(e){
  return handleResponse(e);
function doPost(e){
  return handleResponse(e);
function handleResponse(e) {
  // shortly after my original solution Google announced the LockService[1]
  // this prevents concurrent access overwritting data
  // [1]
  // we want a public lock, one that locks for all invocations
  var lock = LockService.getPublicLock();
  lock.waitLock(30000);  // wait 30 seconds before conceding defeat.
  try {
    // next set where we write the data - you could write to multiple/alternate destinations
    var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
    var sheet = doc.getSheetByName(SHEET_NAME);
    // we'll assume header is in row 1 but you can override with header_row in GET/POST data
    //var headRow = e.parameter.header_row || 1; Hawksey's code parsed parameter data
    var postData = e.postData.contents; //my code uses postData instead
    var data = JSON.parse(postData); //parse the postData from JSON
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow()+1; // get next row
    var row = []; 
    // loop through the header columns
    for (i in headers){
      if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
        row.push(new Date());
      } else { // else use header name to get data
    // more efficient to set values as [][] array than individually
    sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
    // return json success results
    return ContentService
          .createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
  } catch(e){
    // if error return this
    return ContentService
          .createTextOutput(JSON.stringify({"result":"error", "error": e}))
  } finally { //release lock
function setup() {
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    SCRIPT_PROP.setProperty("key", doc.getId());

I edited Martin’s original code in lines 39-41. In his code, he’s looking for Post data in a slightly different format than what I generate. Rather than using the parameters from the HTTP Post, my code uses the data from the Post.

Twine Game Code (newer version)

Unlike the earlier version, this code now uses Ajax and jquery, to pass variables that had been collected during gameplay in a Twine game. Twine is built on javascript, so I decided to replace Martin’s Ajax form with a javascript HTTP Post function embedded in Twine. Based on research on how Twine works, I decided that the best way to do this would be to write the javascript code directly into a Twine game passage. My passage, called PostData, would presumably come at or very near the end of my game after all interesting variables have been set:

Screen shot of a Twine game passage showing the code explained in the surrounding post text.

Dan Cox provided me with sample jquery code and explained it. We then wrap the code in Twine’s script syntax <script></script>. This code sends an HTTP Post to whatever url is provided (like the url for your Google Script Web App) with a json package defined in the var data line.

First you need to reference the jquery library in the head of your file:

<script src=”jquery-3.3.1.min.js”></script>

Once that’s been loaded, you place this code at the end of your game (please note that you need to add the <script></script> modifiers in Twine:

var sendData = JSON.stringify({
"var1": harlowe.State.variables['var1'], 
"var2": harlowe.State.variables['var2'], 
"var3": harlowe.State.variables['var3'], 
"var4": harlowe.State.variables['var4'], 
"var5": harlowe.State.variables['var5']
url:"Your Url",
dataType: "json",
data: sendData
}).done(function() {});

However, in order to pull variables out of the Harlowe version of Twine that I was using, I also needed to add the following code by editing the Story Javascript:

Twine Javascript Screen Shot

This bit of Javascript passes all variables defined within the Twine game into an array (window.harlowe) that is accessible by Javascript code that is embedded in the game. Here’s the code in case you want to try this out:

if (!window.harlowe){
	window.harlowe = {"State": State};

I hope this work will be useful in studying any Twine game to see how players are moving through the game. You could record any variables in the game and also the games ‘history’ to see which passages each player went through. This has obvious uses for educational games in being able to provide feedback to players, but it also has implications for game design more broadly with the increased use metrics.

Implement in your own game

In order to implement this for your own game, I would suggest following these steps:

  1. Copy the Javascript code above (starts with if (!window)) into your Twine game’s Javascript panel
  2. Copy the PostData code above and paste it into a TwinePost passage towards the end of your game
  3. Then replace the variables in the TwinePost passage so that harlowe.State.variables[‘var1’] becomes harlowe.State.variables[‘your variable name here’] for each of the variables you want to track
  4. Click this link to get a copy of my Google Spreadsheet
  5. Make sure the column headers in the spreadsheet match your variable names from the TwinePost passage
  6. Share your Google Sheet, so that anyone with the link can edit it. This will allow the incoming data to post
  7. In the Google Sheet, click on Tools->Script Editor and follow Martin Hawksey’s instructions for steps 2-5
  8. When you publish your Script as a Web App, it will give you a URL for the Web App. Copy this URL and paste it into the URL variable in your TwinePost passage code.
  9. You’re done. Play your game and see if everything works. If it doesn’t work, tweet at Tom Woodward. He’s good at fixing code and has nothing but free time on his hands.

I am excited about this code because it answers a question for several of our faculty members and makes Twine games more useful as formative assessments. Hawksey did an excellent job in keeping his code very generalized, and I’ve tried to preserve that, so that you can track whatever variables you want.

You could also use the HTTP Post javascript code outside of Twine in any other web site or web app to pass information to your Google Sheet. Tom has blogged a couple of times about using code to send data to Google Forms and autosubmitting into a Google Spreadsheet. I think the process described above denecessitates that Google Form pass through and moves us a step closer to Google sheets as a no-SQL data base alternative.

Photograph of the staples holding Keegan's head together

Keegan’s Game Jam

This weekend, there is a 48 hour Game Jam in honor of Keegan Long-Wheeler. As most of you know, Keegan had to have brain surgery a couple of weeks ago to remove a tumor. In order to cheer him up, we wanted to encourage his friends to build games about Keegan, friendship, dealing with illness, or whatever else came to mind.

The Game Jam is a 48-hour window to build a game in Twine and post it to the site (by midnight on Sunday). There is a community forum to chat, ask for help, or share ideas. I would also like to see if we can find a time to meetup online next week to play games and talk.

Keegan and I have been teaching Twine as a game building platform for the last couple of years. We like Twine, because it’s very easy to pick up allowing us to focus our attention on creating interesting choose your own adventure stories. We built an open faculty development program called to teach faculty about storytelling in the classroom. The hope with this program is that even if faculty don’t embrace game play or gamification of their courses, they’ll rethink the narrative and student choice within the course. If you haven’t made a game before, I’d suggest going to the site and looking through the material there to help you think about game design and storytelling.  

After, we got started with building games, Keegan got in touch with Dan Cox. Dan is one of the leading figures in the Twine community having built numerous Twine tutorials and the Twine cookbook. Thanks to Dan, several of Keegan’s projects and tutorials have now been incorporated into the Twinery’s guides. When I wanted to set up a game jam for Keegan, I reached out to Dan and he put together this site on, guidelines for the Game Jam, and a set of resources to help everyone out.

So, if you’re a friend of Keegan (if you know me, you probably know and are a friend of Keegan), I hope you’ll join us for our game jam.

Code Ocean

Sarah Clayton in the libraries organized a demo for Code Ocean today. The company offers reproducibility as service allowing you to upload or import code and data in a variety of open source languages and run it on their servers. The most common use case would be someone publishing their code and data along-side a journal publication so that readers can test it for themselves.

Below are a couple of versions of their interface as embeds. I like how you can manipulate the code, run it, and see the results in situ. I’m particularly interested in how this might be used in place of a GitHub gist to teach both code and the various scientific and engineering concepts that the code facilitates.

Page 1 of 2

Powered by WordPress & Theme by Anders Norén