JSFiddle - React, Tailwind, and code Playground
by adamgrossman
HTML
<body>
<center>
<canvas id="canvas" width="400" height="400"></canvas>
<div>
<button id="startGame">Start Game</button>
<p>Don't hit the red squares!</p>
<h2 class='boost'>Get the green square for extra points!</h2>
</div>
</center>
</body>
CSS
h2 {
display: none;
}
JavaScript
$(document).ready(function () {
// Let's set up some variables to save the canvas elements and properties
var canvas = $("#canvas")[0];
var canvasContext = canvas.getContext("2d");
var width = $("#canvas").width();
var height = $("#canvas").height();
var cellWidth = 12;
var currentDirection;
var food;
var boost;
var badCells = [];
var score;
var highScore = 0;
// Will represent each body cell of the snake
var snakeBody;
// Timer representing our game loop
var gameLoopInterval;
function startGame() {
$("#startGame").hide();
// Default the snake going right
currentDirection = "right";
// Set initial score to 0
score = 0;
// Create the initial snake
createSnake();
// Create the initial food
createFood();
// Create three initial bad
for (var i = 0; i < 5; i++) {
createBad();
}
// Create super
createSuper();
// Let's set the game loop to run every 60 milliseconds
gameLoopInterval = setInterval(gameLoop, 80);
}
function createSnake() {
// Starting length of the snake will be 5 cells
var length = 5;
// Let's set the snake body back to an empty array
snakeBody = [];
// Add cells to the snake body starting from the top left hand corner of the screen
for (var i = length - 1; i >= 0; i--) {
snakeBody.push({
x: i,
y: 0
});
}
}
// Create a random piece of food
function createFood() {
food = {
x: Math.round(Math.random() * (width - cellWidth) / cellWidth),
y: Math.round(Math.random() * (height - cellWidth) / cellWidth)
};
}
// Create bad
function createBad() {
var bad = {
x: Math.round(Math.random() * (width - cellWidth) / cellWidth),
y:...