DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report

Conway's Game of Life in Google Docs

Swizec Teller decides to build Conway's Game of Life in Google Docs, just for fun.

Swizec Teller user avatar by
Swizec Teller
·
Aug. 17, 16 · Opinion
Like (1)
Save
Tweet
Share
4.02K Views

Join the DZone community and get the full member experience.

Join For Free

Conway glider

Why? Because. 

Have you really never wanted to create Conway’s game of life in a Google Doc spreadsheet? Really, never? Okay, it’s a pretty weird thing to do. And it’s not as fun as I hoped.

You can play with it, here.

I’m giving a 30 min presentation on “How to JavaScript” to our not-engineers—the operations and business development teams. But how? It’s not like you can teach somebody JavaScript from scratch in 30 minutes. The most you can do is show them enough to want to learn more.

That’s easier, but still… how? You can’t just show them a bunch of for loops and functions and hope it sticks. You have to get them excited.

The question I’m trying to answer is: “How can this make my life better?”

They all spend a lot of time in Google Docs. They run a lot of day to day processes in there. Google Docs has scripting capabilities.

See what I’m getting at?

Conway’s Game of Life inside Google Docs, of course. It highlights the basics of reading and manipulating properties of individual cells in spreadsheets, and the game itself is easy to explain:

  1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by overpopulation.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.









I showed one of them some GIFs and he said “Oh dude, I’m excited! That looks so cool.” All the confirmation I needed to go waste 3 hours of my life figuring out how to build this!

Scripting Google Docs is hell.

You can’t alert, there’s no console.log, everything is slow, and ES6 works only partially. You get destructuring, but no string templates. I dared not try arrow functions.

Timers also don’t exist. Which means you have to manually step through the game loop by clicking a button. 

One silver lining is this 3rd party logger called BetterLogger, which lets you Logger.log things to a separate sheet in your spreadsheet. It’s not very smart, but it helps a lot.

And if you thought DOM was slow, wait til you try Docs access. Naively searching through 30×30 cells and counting neighbors took many seconds. Maybe 20 seconds per game tick.

That can be optimized, though. Just access the spreadsheet less.

The first step is to set global vars and add a menu:

// global vars
var maxX = 30,
    maxY = 30,
    Alive = '#000000';

// almost everything needs a reference to this
var Sheet = SpreadsheetApp.getActiveSheet();

// add menu
function onOpen() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var menuItems = [
    {name: 'Step game', functionName: 'stepGame'},
    {name: 'Clear game', functionName: 'clearGame'}
  ];
  spreadsheet.addMenu('Conway\'s game of life', menuItems);
}


Docs runs this code when you open your document. It adds a menu that looks like this:

Image title


Step Game runs an iteration of the game loop, Clear Game clears all cells. Black background means a living cell and white background means a not-living cell.

On each game step, we build a map of living cells, then run the game rules on each. Like this:

function stepGame() {
  var range = Sheet.getRange(1, 1, maxX, maxY);

  var numRows = range.getNumRows(),
      numCols = range.getNumColumns();

  var lifeMap = [];

  for (var y = 1; y <= numRows; y++) {
    lifeMap[y] = [];

    for (var x = 1; x <= numCols; x++) {
      lifeMap[y][x] = range.getCell(y, x).getBackground() == Alive;
    }
  }

  for (var y = 1; y <= numRows; y++) {
    for (var x = 1; x <= numCols; x++) {
      conwayGame(lifeMap, y, x);
    }
  }
}


You can think of the spreadsheet as 2-dimensional memory. First dimension is the row, second is the column. You can store styling information, the value itself, and notes. Docs lets you access directly on both dimension, but it’s slow.

Having 2D memory also means there will be a lot of these nested for loop constructs in your code. You’re limited to O(n2) algorithms at best.

Applying Conway rules to each cell looks like this:

function conwayGame(lifeMap, y, x) {
  var neighborPos = [y > 1 ? y-1 : 1, 
                     x > 1 ? x-1 : 1, 
                     y < maxY ? y+1 : maxY, 
                     x < maxX ? x+1: maxX]

  var livingNeighbors = countLife(lifeMap, neighborPos);

  if (lifeMap[y][x]) {
    livingNeighbors -= 1;
  }

  if ((livingNeighbors < 2 || livingNeighbors > 3) && lifeMap[y][x]) {
    deactivate(Sheet.getRange(y, x));
  }else if (livingNeighbors == 3) {
    activate(Sheet.getRange(y, x));
  }
}


We count living neighbors, discount the current cell if it’s alive, then decide whether to deactivate or activate it. Counting the neighbors literally means walking through a 3×3 array around the current cell and counting cells that have a black background.

Activating or deactivating is a call to cell.setBackground('black')  and cell.setBackground('white').

That’s kind of it… I’m embarrassed it took me 3 hours...

Doc (computing) Google Docs Google (verb)

Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Steel Threads Are a Technique That Will Make You a Better Engineer
  • Integrate AWS Secrets Manager in Spring Boot Application
  • Choosing the Right Framework for Your Project
  • Strategies for Kubernetes Cluster Administrators: Understanding Pod Scheduling

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: