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.
var JS_SNAKE = {};
JS_SNAKE.equalCoordinates = function (coord1, coord2) {
return coord1[0] === coord2[0] && coord1[1] === coord2[1];
}
JS_SNAKE.checkCoordinateInArray = function (coord, arr) {
var isInArray = false;
$.each(arr, function (index, item) {
if (JS_SNAKE.equalCoordinates(coord, item)) {
isInArray = true;
}
});
return isInArray;
};
JS_SNAKE.game = (function () {
var canvas, ctx;
var frameLength;
var snake;
var apple;
var score;
var timeout;
JS_SNAKE.width = 200;
JS_SNAKE.height = 200;
JS_SNAKE.blockSize = 10;
JS_SNAKE.widthInBlocks = JS_SNAKE.width / JS_SNAKE.blockSize;
JS_SNAKE.heightInBlocks = JS_SNAKE.height / JS_SNAKE.blockSize;
function init() {
var $canvas = $('#jsSnake');
if ($canvas.length === 0) {
$('body').append('<canvas id="jsSnake">');
}
$canvas = $('#jsSnake');
$canvas.attr('width', JS_SNAKE.width);
$canvas.attr('height', JS_SNAKE.height);
canvas = $canvas[0];
ctx = canvas.getContext('2d');
score = 0;
frameLength = 500;
snake = JS_SNAKE.snake();
apple = JS_SNAKE.apple();
bindEvents();
gameLoop();
}
function gameLoop() {
ctx.clearRect(0, 0, JS_SNAKE.width, JS_SNAKE.height);
snake.advance(apple);
draw();
if (snake.checkCollision()) {
snake.retreat(); //move snake back to previous position
snake.draw(ctx); //draw snake in its previous position
gameOver();
}
else {
timeout = setTimeout(gameLoop, frameLength);
}
}
function draw() {
snake.draw(ctx);
drawBorder();
apple.draw(ctx);
drawScore();
}
function drawScore() {
ctx.save();
ctx.font = 'bold 102px sans-serif';
ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var centreX = JS_SNAKE.width / 2;
var centreY = JS_SNAKE.width / 2;
ctx.fillText(score.toString(), centreX, centreY);
ctx.restore();
}
function gameOver() {
ctx.save();
ctx.font = 'bold 30px sans-serif';
ctx.fillStyle = '#000';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.strokeStyle = 'white';
ctx.lineWidth = 2;
var centreX = JS_SNAKE.width / 2;
var centreY = JS_SNAKE.width / 2;
ctx.strokeText('Game Over', centreX, centreY - 10);
ctx.fillText('Game Over', centreX, centreY - 10);
ctx.font = 'bold 15px sans-serif';
ctx.strokeText('Press space to restart', centreX, centreY + 15);
ctx.fillText('Press space to restart', centreX, centreY + 15);
ctx.restore();
}
function drawBorder() {
ctx.save();
ctx.strokeStyle = 'gray';
ctx.lineWidth = JS_SNAKE.blockSize;
ctx.lineCap = 'square';
var offset = ctx.lineWidth / 2;
var corners = [
[offset, offset],
[JS_SNAKE.width - offset, offset],
[JS_SNAKE.width - offset, JS_SNAKE.height - offset],
[offset, JS_SNAKE.height - offset]
];
ctx.beginPath();
ctx.moveTo(corners[3][0], corners[3][1]);
$.each(corners, function (index, corner) {
ctx.lineTo(corner[0], corner[1]);
});
ctx.stroke();
ctx.restore();
}
function restart() {
clearTimeout(timeout);
$('body').unbind('keydown');
$(JS_SNAKE).unbind('appleEaten');
$(canvas).unbind('click');
JS_SNAKE.game.init();
}
function bindEvents() {
var keysToDirections = {
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
$(document).keydown(function (event) {
var key = event.which;
var direction = keysToDirections[key];
if (direction) {
snake.setDirection(direction);
event.preventDefault();
}
else if (key === 32) {
restart();
}
});
$(JS_SNAKE).bind('appleEaten', function (event, snakePositions) {
apple.setNewPosition(snakePositions);
score++;
frameLength *= 0.99; //subtle speed-up
});
$(canvas).click(restart);
}
return {
init: init
};
})();
JS_SNAKE.apple = function () {
var position = [6, 6];
function draw(ctx) {
ctx.save();
ctx.fillStyle = '#0a0'; //apple green
ctx.beginPath();
var radius = JS_SNAKE.blockSize / 2;
var x = position[0] * JS_SNAKE.blockSize + radius;
var y = position[1] * JS_SNAKE.blockSize + radius;
ctx.arc(x, y, radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.restore();
}
function random(low, high) {
return Math.floor(Math.random() * (high - low + 1) + low);
}
//get a random position within the game bounds
function getRandomPosition() {
var x = random(1, JS_SNAKE.widthInBlocks - 2);
var y = random(1, JS_SNAKE.heightInBlocks - 2);
return [x, y];
}
function setNewPosition(snakeArray) {
var newPosition = getRandomPosition();
//if new position is already covered by the snake, try again
if (JS_SNAKE.checkCoordinateInArray(newPosition, snakeArray)) {
return setNewPosition(snakeArray);
}
//otherwise set position to the new position
else {
position = newPosition;
}
}
function getPosition() {
return position;
}
return {
draw: draw,
setNewPosition: setNewPosition,
getPosition: getPosition
};
};
JS_SNAKE.snake = function () {
var previousPosArray;
var posArray = [];
posArray.push([6, 4]);
posArray.push([5, 4]);
var direction = 'right';
var nextDirection = direction;
function setDirection(newDirection) {
var allowedDirections;
switch (direction) {
case 'left':
case 'right':
allowedDirections = ['up', 'down'];
break;
case 'up':
case 'down':
allowedDirections = ['left', 'right'];
break;
default:
throw('Invalid direction');
}
if (allowedDirections.indexOf(newDirection) > -1) {
nextDirection = newDirection;
}
}
function drawSection(ctx, position) {
var x = JS_SNAKE.blockSize * position[0];
var y = JS_SNAKE.blockSize * position[1];
ctx.fillRect(x, y, JS_SNAKE.blockSize, JS_SNAKE.blockSize);
}
function draw(ctx) {
ctx.save();
ctx.fillStyle = '#33a';
for(var i = 0; i < posArray.length; i++) {
drawSection(ctx, posArray[i]);
}
ctx.restore();
}
function checkCollision() {
var wallCollision = false;
var snakeCollision = false;
var head = posArray[0]; //just the head
var rest = posArray.slice(1); //the rest of the snake
var snakeX = head[0];
var snakeY = head[1];
var minX = 1;
var minY = 1;
var maxX = JS_SNAKE.widthInBlocks - 1;
var maxY = JS_SNAKE.heightInBlocks - 1;
var outsideHorizontalBounds = snakeX < minX || snakeX >= maxX;
var outsideVerticalBounds = snakeY < minY || snakeY >= maxY;
if (outsideHorizontalBounds || outsideVerticalBounds) {
wallCollision = true;
}
//check if the snake head coords overlap the rest of the snake
snakeCollision = JS_SNAKE.checkCoordinateInArray(head, rest);
return wallCollision || snakeCollision;
}
function advance(apple) {
//make a copy of the head of the snake otherwise
//the changes below would affect the head of the snake
var nextPosition = posArray[0].slice();
direction = nextDirection;
switch (direction) {
case 'left':
nextPosition[0] -= 1;
break;
case 'up':
nextPosition[1] -= 1;
break;
case 'right':
nextPosition[0] += 1;
break;
case 'down':
nextPosition[1] += 1;
break;
default:
throw('Invalid direction');
}
previousPosArray = posArray.slice(); //save previous array
posArray.unshift(nextPosition);
if (isEatingApple(posArray[0], apple)) {
$(JS_SNAKE).trigger('appleEaten', [posArray]);
}
else {
posArray.pop();
}
}
function isEatingApple(head, apple) {
return JS_SNAKE.equalCoordinates(head, apple.getPosition());
}
function retreat() {
posArray = previousPosArray;
}
return {
draw: draw,
advance: advance,
retreat: retreat,
setDirection: setDirection,
checkCollision: checkCollision
};
};
JS_SNAKE.game.init();
Also see: Tab Triggers