Google Spreadsheets for Game Configuration ~ September 2, 2013

Dynamic game configuration is always useful, and doing it cheaply and easily is especially important for small indy studios. Setting up a Google Spreadsheet with your runtime configuration data enables easy collaborative editing, and having a process that can read that data and export JSON makes it easy to use that data at runtime in whatever client language you find suitable. In this article I’m using Gson for JSON serialization, but it wouldn’t be difficult to use Jackson instead, if that’s how you roll.

When my wife and I started working on our own hidden object game for mobile, we needed a game data editor that wouldn’t take me a long time to write and would be easily extensible. We settled on using a specially formatted spreadsheet in Google Drive that would be read by a process on our dashboard server to generate JSON that the client would load either from the game server or from a static file in Amazon S3.

Example Usage

As shown in the example above, the conversion is pretty straightforward:

Code time

The public entry point to this utility takes a cell feed URL and an instance of GoogleCredential. Retreiving these values is outside the scope of this article. I recommend reading through the Google Spreadsheets API documentation for guidance in setting up your access to spreadsheets in general.

SpreadsheetReader.java
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class SpreadsheetReader {
    /**
     * Converts the worksheet at the given URL to JSON.
     */
    public JsonObject readJson (String url, GoogleCredential cred) {
        SpreadsheetService service = new SpreadsheetService("TestServiceCall");
        service.setOAuth2Credentials(cred);
        try {
            CellFeed feed = service.getFeed(new URL(url), CellFeed.class);
            return readJson(feed);

        } catch (ServiceException se) {
            log.warning("ServiceException reading spreadsheet", se);
        } catch (IOException ioe) {
            log.warning("IOException reading spreadsheet", ioe);
        }
        return null;
    }

Rather than go through this whole class line by line, I’m just going to talk about a couple of meaty bits. The full class may be downloaded from the link at the head of any of these inline code sections.

The static inner class SpreadsheetRow is reponsible for the bulk of the parsing work. It filters out comments:

SpreadsheetReader.java
213
214
215
216
217
218
219
220
            if (key.startsWith("*")) {
                Cell cell;
                // consume any more cells on this row
                while ((cell = iter.hasNext() ? iter.next().getCell() : null) != null &&
                    cell.getRow() == row);
                if (cell != null && cell.getRow() != row) iter.previous();
                return rows;
            }

Finds all the values in a given row:

SpreadsheetReader.java
230
231
232
233
234
235
236
237
238
            // get any valid value cells into the values list.
            Cell valueCell;
            while ((valueCell = iter.hasNext() ? iter.next().getCell() : null) != null &&
                valueCell.getRow() == row) {
                String value = valueCell.getValue().trim();
                if (!value.startsWith("*")) values.add(value);
            }
            // roll back the iterator if we've bumped into the next row.
            if (valueCell != null && valueCell.getRow() != row) iter.previous();

And breaks up compound keys into multiple logical rows for easier processing:

SpreadsheetReader.java
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
                // break up any compound keys into separate key parts. Things like "} Foo Bar {"
                // get broken into "}", "Foo Bar" and "{"
                List<String> keyParts = new ArrayList<String>();
                Matcher m = COMPLEX_CELL.matcher(key);
                boolean found = false;
                int end = 0;
                while (m.find()) {
                    if (found && end != m.start())
                        keyParts.add(key.substring(end, m.start()).trim());
                    end = m.end();
                    if (!found && m.start() > 0) keyParts.add(key.substring(0, m.start()).trim());
                    found = true;
                    keyParts.add(key.substring(m.start(), m.end()).trim());
                }
                if (found) {
                    if (end < key.length() - 1) keyParts.add(key.substring(end).trim());
                } else {
                    keyParts.add(key);
                }

                // Break compound keys into separate rows to make JSON construction much simpler.
                // The values associated with this row in the spreadsheet are attached to the last
                // string key or array opening bracket found in this compound key
                SpreadsheetRow lastRow = null;
                for (String keyPart : keyParts) {
                    if (keyPart.length() == 0) continue;

                    if (keyPart.equals("{")) rows.add(empty(keyPart));
                    else if (keyPart.equals("[")) rows.add(lastRow = empty(keyPart));
                    else if (keyPart.equals("}")) rows.add(empty(keyPart));
                    else if (keyPart.equals("]")) rows.add(empty(keyPart));
                    else rows.add(lastRow = empty(keyPart));
                }
                // if we found a valid key for storing a value, attach this row's value to it
                if (lastRow != null) lastRow.value.addAll(values);

Once the values of the spreadsheet cells have been read and parsed into this format, building up the JSON Object and Array representation is relatively straightforward.

SpreadsheetReader.java
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    /**
     * Returns a JsonElement built out of the rows at the current position of rowIter. The first
     * element is expected to have "{" as the key, and processing continues until a corresponding
     * "}" key is found.
     */
    protected JsonObject createObject (ListIterator<SpreadsheetRow> rowIter) {
        if (!rowIter.hasNext()) {
            return null;
        }

        SpreadsheetRow row = rowIter.next();
        if (row.key == null || !row.key.equals("{")) {
            log.warning("Object not started with {", "key", row.key);
            return null;
        }

        JsonObject obj = new JsonObject();
        while (rowIter.hasNext()) {
            row = rowIter.next();
            // Objects require that a key be associated with each value found. Null keys and objects
            // starting without a corresponding key are an error.
            if (row.key == null) {
                log.warning("Null key in object");
            } else if (row.key.equals("}")) {
                // we've found our matching close brace, return results
                return obj;
            } else if (row.key.equals("{") || row.key.equals("[") || row.key.equals("]")) {
                log.warning("Non key in object", "key", row.key);
            } else {
                if (!row.value.isEmpty()) {
                    JsonElement value = getValue(row.value);
                    if (value != null) obj.add(cellKey(row.key), value);
                } else if (!rowIter.hasNext()) {
                    // this row had no value, and there is no next row to contain a value either.
                    log.warning("Obj has no value", "key", row.key);
                } else {
                    // peek at the next row to see if it's a start of an object or array for this
                    // row's key.
                    String key = row.key;
                    row = rowIter.next(); rowIter.previous(); // peek
                    if (row.key.equals("{")) {
                        obj.add(cellKey(key), createObject(rowIter));
                    } else if (row.key.equals("[")) {
                        obj.add(cellKey(key), createArray(rowIter));
                    } else {
                        log.warning("Invalid row after empty obj key", "key", key, "next", row.key);
                    }
                }
            }
        }
        return obj;
    }

    /**
     * Returns a JsonArray corresponding to the rows starting at the current position of the
     * iterator. The rows are expected to start with a "[" key, and processing continues until a
     * corresponding "]" key is found.
     */
    protected JsonArray createArray (ListIterator<SpreadsheetRow> rowIter) {
        SpreadsheetRow row = rowIter.next();
        if (row.key == null || !row.key.equals("[")) {
            log.warning("create array not started with [", row.key);
            return null;
        }

        JsonArray arr = new JsonArray();
        if (!row.value.isEmpty()) {
            // the opening array row can have a value.
            arr.add(getValue(row.value));
        }
        while (rowIter.hasNext()) {
            row = rowIter.next();
            if (row.key == null) {
                arr.add(getValue(row.value));
            } else if (row.key.equals("[")) {
                rowIter.previous();
                arr.add(createArray(rowIter));
            } else if (row.key.equals("{")) {
                rowIter.previous();
                arr.add(createObject(rowIter));
            } else if (row.key.equals("]")) {
                // we found our corresponding array closure, bounce back the result.
                return arr;
            } else {
                log.warning("Bad key while in array", "key", row.key);
            }
        }
        return arr;
    }

That’s about it! Using this tool, we can quickly release tuning updates to our clients in the wild, without requiring a new client build (especially important for games in any kind of app store that has a vetting process that takes a long time). In a future article, I’ll talk about the tools we’re using to generate code for reading our configuration data format from the generated JSON files.


comments powered by Disqus