HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<html>
<head>
<title>Snake game</title>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script src="game.js"></script>
</body>
</html>
// Repository: https://codeberg.org/dandeto/HTML5-Snake
// Tutorial: https://www.scipress.io/post/RD2DB4zGgNNkZ6wR9uz0/html5-canvas-snake
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
const width = Number(canvas.width);
const height = Number(canvas.height);
const tileWidth = 50;
const tileHeight = 50;
const tilesX = Math.round(width / tileWidth);
const tilesY = Math.round(height / tileHeight);
const totalTiles = tilesX * tilesY;
const borderWidth = 2;
let gameOver = false;
let eaten = false;
let player = [];
let apple;
let highscore = 0;
// Keyboard controls
let lastKey;
let bufferedKey;
let deniedKey = {
"ArrowLeft": "ArrowRight",
"ArrowRight": "ArrowLeft",
"ArrowUp": "ArrowDown",
"ArrowDown": "ArrowUp",
"undefined": "ArrowLeft"
}
document.addEventListener("keydown", function (e) {
bufferedKey = e.key;
});
function getKey() {
if(bufferedKey == "ArrowLeft" || bufferedKey == "ArrowRight" || bufferedKey == "ArrowUp" || bufferedKey == "ArrowDown") {
if(!(deniedKey[lastKey] == bufferedKey)) {
lastKey = bufferedKey;
}
}
else if(gameOver && bufferedKey == " ") {
lastKey = bufferedKey;
}
}
// Setup the game - called once each time we init the game.
function setup() {
if(player.length > highscore)
highscore = player.length;
gameOver = false;
lastKey = undefined;
player = [
{
x: 4,
y: 5
},
{
x: 3,
y: 5
},
{
x: 2,
y: 5
},
{
x: 1,
y: 5
}
];
createApple();
}
// Update - called every frame
function update() {
getKey();
if(lastKey == undefined)
return;
if(gameOver) {
if(lastKey == " ") {
setup();
}
return;
}
// Remove the last element in the array
if(!eaten)
player.pop();
else
eaten = false;
// This is a confusing line of code. We are copying the head of the snake at player[0]
// into an empty object {} and returning it to the variable `head`.
// If we use `head = player[0]`, we would be referencing `player[0]` instead of copying it.
let head = Object.assign({}, player[0]);
if(lastKey == "ArrowLeft")
--head.x;
else if(lastKey == "ArrowRight")
++head.x;
else if(lastKey == "ArrowUp")
--head.y;
else if(lastKey == "ArrowDown")
++head.y;
// Add the head of the snake to the beginning of the array
player.unshift(head);
for(let i = 0; i < player.length; ++i) {
// Check if the snake has hit itself
if(i > 0 && head.x == player[i].x && head.y == player[i].y) {
gameOver = true;
}
// Check if the snake is out of bounds
if(player[i].x == tilesX)
player[i].x = 0;
else if(player[i].x == -1)
player[i].x = tilesX -1;
if(player[i].y == tilesY)
player[i].y = 0;
else if(player[i].y == -1)
player[i].y = tilesY -1;
}
// Check if the snake hit the apple
if(head.x == apple.x && head.y == apple.y) {
eaten = true;
createApple();
}
}
// Render - called every frame
function render() {
// Draw background
ctx.fillStyle = "black";
ctx.fillRect(0, 0, width, height);
if(!gameOver) {
// Draw grid
for(var i = 0; i < tilesX; ++i) {
for(var j = 0; j < tilesY; ++j) {
// Set the default tile color
ctx.fillStyle = "blue";
// Detect if the player is in this tile
for(var k = 0; k < player.length; ++k) {
if(player[k].x == i && player[k].y == j) {
ctx.fillStyle = "green";
break;
}
}
drawTile(i,j);
}
}
// Draw apple
ctx.fillStyle = "red";
drawTile(apple.x, apple.y);
}
else {
// Draw GameOver screen
ctx.font = "50px serif";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("GAME OVER", width / 2, height / 2);
ctx.font = "25px serif";
ctx.fillText("Press Space to Restart", width / 2, height / 2 + 50);
}
// Draw the score
ctx.font = "20px sans serif";
ctx.fillStyle = "yellow";
ctx.textAlign = "left";
ctx.fillText(`Score: ${player.length}`, 10, 20);
ctx.textAlign = "right";
ctx.fillText(`Highscore: ${highscore}`, width - 10, 20);
}
// The entry point for the game
function main() {
update();
render();
}
// Utility functions
function randomTile(max) {
// Generate a random number between 0 and max
let randomFloat = Math.random() * max;
// Convert float (decimal) to integer
return Math.floor(randomFloat);
}
function drawTile(x, y) {
// Calculate the x, y, w, h for each tile
x = x * tileWidth + borderWidth;
y = y * tileHeight + borderWidth;
let w = tileWidth - borderWidth * 2;
let h = tileHeight - borderWidth * 2;
// Draw each tile
ctx.fillRect(x, y, w, h);
}
function createApple() {
let collision;
do {
collision = false;
// Choose a random tile for the Apple
apple = {
x: randomTile(tilesX),
y: randomTile(tilesY)
}
// Check to see if the apple was generated on a tile the player occupies
for(let i = 0; i < player.length; ++i) {
if(player[i].x == apple.x && player[i].y == apple.y) {
collision = true;
break;
}
}
} while(collision);
}
// Setup the game before starting the game loop
setup();
// This will call the function main at 10fps and start the game
setInterval(main, 1000 / 10);
Also see: Tab Triggers