Friday, December 30, 2016

Code for a Drawing Game

The other day my wife and kids played a drawing game called Who What Where Jr with some friends. Based on their description of the game mechanics, I wrote a little bit of Javascript that chooses a "who", a "what", and a "where" from columns in a Google Spreadsheet.

I guess it's not quite the same as the actual game, and it took us a while to come up with subjects, verbs, and locations, but we had some fun creating it and playing it. The next step would be to turn this into a web app, including some sort of mechanism for showing each player a different phrase before a timer starts.

Code is available on GitHub.


// in a Google Sheet that has two sheets: Cards and Drawn
// The 'Cards' sheet should have three columns: subject, verb, and location
// This code is public domain, but let me know if there are any copyright concerns.
// https://developers.google.com/apps-script/guides/sheets
// https://docs.google.com/spreadsheets/d/1mrnsKUCSkum-ZmAvGtK10uAf1eypdxsoFP7tbjWynsQ
function addMenu() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Game').addItem('Draw Something', 'drawSomething').addToUi();
}
function drawSomething() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Cards');
var lastRow = sheet.getLastRow();
var random1 = pickRandom(lastRow);
var random2 = pickRandom(lastRow);
var random3 = pickRandom(lastRow);
var who = sheet.getRange(random1, 1).getValue();
var what = sheet.getRange(random2, 2).getValue();
var where = sheet.getRange(random3, 3).getValue();
var phrase = who + ' ' + what + ' ' + where + '.';
logPhrase(phrase);
SpreadsheetApp.getUi().alert(phrase);
}
function pickRandom(max) {
// a number between 2 and max
var min = 2;
for (i = 1; i<20; i++) {
var random = Math.floor(Math.random() * (max - min + 1)) + min;
}
return random;
}
function logPhrase(phrase) {
var time = new Date();
var logSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Drawn');
var lastRowOfLog = logSheet.getLastRow() + 1;
logSheet.getRange(lastRowOfLog, 1).setValue(time);
logSheet.getRange(lastRowOfLog, 2).setValue(phrase);
}