Simple Colored Cell Game

* At the start of the game, there is a blue-colored cell in the middle of the canvas. * On every left-click, the cell increases in size. * If an arrow key is pressed, the cell changes color and moves to that direction. * If the enter key is pressed, the game is reset.

by Aya Alao

HTML

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<canvas id="canvas" width="450" height="450"></canvas>

JavaScript

$(document).ready(function(){
  
 // canvas stuff
 var canvas = document.getElementById("canvas");
 var ctx = canvas.getContext("2d");
 var w = canvas.width;
 var h = canvas.height;
 var locX; // location in X
 var locY; // location in Y
 var pxX; // pixel size in X
 var pxY; // pixel size in Y
 var cellColor;
 var BGColor;
 var strokeColor;
  
 function init()
 {
  // set default color
  BGColor = "white";
  cellColor = "blue";
  strokeColor = "black";
   
  // set default pixel size
  pxX = 10;
  pxY = 10;
    
  // set default location (center of canvas)
  locX = (w - pxX) / 2;
  locY = (h - pxY) / 2;
   
  paint();  
 }
  
 init();
 
 function paint()
 {
  // paint background
  ctx.fillStyle = BGColor;
  ctx.fillRect(0, 0, w, h);
  ctx.strokeStyle = strokeColor;
  ctx.strokeRect(0, 0, w, h);
   
  // paint cell
  ctx.fillStyle = cellColor;
  ctx.fillRect(locX, locY, pxX, pxY);
  ctx.strokeStyle = strokeColor;
  ctx.strokeRect(locX, locY, pxX, pxY);
 }
  
 $(document).click(function()
 { 
  // add one pixel for x and y on every click
  pxX++;
  pxY++;
     
  paint();
 })
  
 $(document).keydown(function(e)
 {
  var key = e.which;
   
  if(key == "37") // left
  {
   locX--;
   cellColor = "red";
  }
  else if(key == "38") // up
  {
   locY--;
   cellColor = "blue";
  }
  else if(key == "39") // right
  {
   locX++;
   cellColor = "yellow";
  }
  else if(key == "40") // down
  {
   locY++;
   cellColor = "green";
  }
  else if(key == "13") // enter
   init();
   
  paint();
 })
  
})