Last active
June 23, 2018 10:59
-
-
Save supergoat/8b304218e8abd1e209d9423ec60c57fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Snake Game</title> | |
</head> | |
<body> | |
<canvas id="gameCanvas" width="300" height="300"></canvas> | |
<script> | |
/** CONSTANTS **/ | |
const CANVAS_BORDER_COLOUR = 'black'; | |
const CANVAS_BACKGROUND_COLOUR = "white"; | |
const SNAKE_COLOUR = 'lightgreen'; | |
const SNAKE_BORDER_COLOUR = 'darkgreen'; | |
let snake = [ | |
{x: 150, y: 150}, | |
{x: 140, y: 150}, | |
{x: 130, y: 150}, | |
{x: 120, y: 150}, | |
{x: 110, y: 150} | |
] | |
// Get the canvas element | |
var gameCanvas = document.getElementById("gameCanvas"); | |
// Return a two dimensional drawing context | |
var ctx = gameCanvas.getContext("2d"); | |
// Select the colour to fill the canvas | |
ctx.fillStyle = CANVAS_BACKGROUND_COLOUR; | |
// Select the colour for the border of the canvas | |
ctx.strokestyle = CANVAS_BORDER_COLOUR; | |
// Draw a "filled" rectangle to cover the entire canvas | |
ctx.fillRect(0, 0, gameCanvas.width, gameCanvas.height); | |
// Draw a "border" around the entire canvas | |
ctx.strokeRect(0, 0, gameCanvas.width, gameCanvas.height); | |
drawSnake(); | |
/** | |
* Draws the snake on the canvas | |
*/ | |
function drawSnake() { | |
// loop through the snake parts drawing each part on the canvas | |
snake.forEach(drawSnakePart) | |
} | |
/** | |
* Draws a part of the snake on the canvas | |
* @param { object } snakePart - The coordinates where the part should be drawn | |
*/ | |
function drawSnakePart(snakePart) { | |
// Set the colour of the snake part | |
ctx.fillStyle = SNAKE_COLOUR; | |
// Set the border colour of the snake part | |
ctx.strokestyle = SNAKE_BORDER_COLOUR; | |
// Draw a "filled" rectangle to represent the snake part at the coordinates | |
// the part is located | |
ctx.fillRect(snakePart.x, snakePart.y, 10, 10); | |
// Draw a border around the snake part | |
ctx.strokeRect(snakePart.x, snakePart.y, 10, 10); | |
} | |
</script> | |
</body> | |
</html> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment