JSFiddle - React, Tailwind, and code Playground
HTML
<div id="gameboard" class="float-l"></div>
<div class="float-l" id="side">
<div class="float-l">
<button onclick="newGame();">New game</button>
</div>
<div class="float-l" id="deadmsg"></div>
<div class="clear-b"></div>
<br/>
<div id="info">Game: <span id="game"></span>
<br/>Score: <span id="score"></span>
<br/>
<br/>Best: <span id="best"></span>
<br/>Average: <span id="avg"></span>
</div>
</div>
<div class="clear-b"></div>
CSS
html, body {
width:100%;
height:100%;
background:#2E3137;
padding:0;
margin:0;
overflow:hidden;
font-family:Arial;
}
#gameboard {
height:100%;
}
.float-l {
float:left;
}
.float-r {
float:right;
}
.clear-b {
clear:both;
}
.cell {
cursor:default;
}
.even {
background:#0a0a0a;
}
.odd {
background:#101010;
}
.snake {
background:#bBc44B;
}
.food {
background:#c1414D;
}
.dead {
background:#a9b4bE;
}
#deadmsg {
color:#c00;
margin-top:4px;
}
#side {
padding:5px;
background:#1E2127;
margin-left:20px;
font-weight:bold;
}
#info {
color:#8Ea1a7;
}
button {
cursor:pointer;
}
JavaScript
//Initial variable declarations and initializations ////////////////////
//Average score
var avg = 0;
//High score
var best = 0;
//Holds the current game (instance of Snake class)
var currentGame;
//Current game number
var game = 0;
//Game score history
var games = [];
//DOM element placeholders for game history
var placeholders = {
$game: $('#game'),
$score: $('#score'),
$best: $('#best'),
$avg: $('#avg')
};
////////////////////////////////////////////////////////////////////////
//Classes //////////////////////////////////////////////////////////////
//Snake class, defines game logic
function Snake(divid, w, h, ix, iy, d, speed) {
this.updateIntv = null;
//Builds the grid in the DOM at the provided id (divid)
this.buildGrid = function () {
this.$el.html('');
var sw = 100.0 / w;
var sh = 100.0 / h;
for (var r = 0; r < h; r++) {
var $rowel = $('<div id="r-' + r + '" style="height:' + sh + '%; width:100%;"></div>');
for (var c = 0; c < w; c++) {
$colel = $('<div id="cell' + c + '-' + r + '" style="height:100%; width:' + sw + '%;" class="float-l cell ' + (((r + c) % 2 === 0) ? 'even' : 'odd') + '"></div>');
$rowel.append($colel);
}
$rowel.append('<div class="clear-b"></div>');
this.$el.append($rowel);
}
};
//Draws the game board to the DOM
this.draw = function () {
$('.cell').removeClass('snake');
$('.cell').removeClass('food');
this.getCellEl(this.food.x, this.food.y).addClass('food');
for (var i = 0; i < this.snake.body.length; i++)
this.getCellEl(this.snake.body[i].x, this.snake.body[i].y).addClass('snake');
};
//Returns the jQuery object at the provided coordinates
this.getCellEl = function (x, y) {
return $('#cell' + x + '-' + y);
};
//Returns a random coordinate on the board
this.randCoor = function () {
...