Rock, Paper, Scissors

Cellular Automata map and tiles

Cellular Automata are a way to model systems through interactions of 'cells'; individual entities, governed by a set of rules. Cells are updated at a desired rate through a series of steps, and the outcome of their interactions can be viewed and assessed.

Rock, Paper, Scissors example
example

In this article, we'll look at a simple Cellular Automata system written in Javascript & HTML, used to model interactions between three types of cells; Rocks, Paper, and Scissors. These cells are governed by these simple rules:

  • If there is a "prey" type cell beside me, destroy that cell and create a new cell the same type as me (if there are multiple, choose one at random)
  • Otherwise, if there are empty cells around me, move in to one of them at random

For the sake of readability I'll break this content down in to several seperate files. First of all, a map.js file, which will store the data for the tiles on which the cells move, beginning with a Tile class to hold the information about each tile and the cell which occupies it:


class Tile
{
	constructor(cx, cy)
	{
		this.x		= cx;
		this.y		= cy;
		this.index	= (cy * Map.width) + cx;
		this.cell	= null;
	}
}

Our Map object itself will then store the dimensions of the map we'll be using, as well as an array of tiles which compose the map, and a generate function for creating a new map full of empty tiles:


var Map = {
	width	: 28,
	height	: 18,
	tiles	: [],
	
	generate : function(w, h)
	{
		this.width = w;
		this.height = h;
		this.tiles = [];
		
		for(var y = 0; y < h; y++)
		{
			for(var x = 0; x < w; x++)
			{
				this.tiles.push(new Tile(x, y));
			}
		}
	}
};

We will also create a html document as the container for our canvas and for loading all of our javascripts:


<!DOCTYPE html>
<html>
<head>

	<title>Rock, Paper, Scissors Automata</title>
	
</head>
<body>

	<canvas id="map" width="600" height="400">
		This example requires Javascript & Canvas
	</canvas>
	
	<script type="text/javascript" src="cell.js"></script>
	<script type="text/javascript" src="map.js"></script>
	<script type="text/javascript" src="core.js"></script>

</body>
</html>
Page loaded in 0.077 second(s).