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.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Snake Game</title>
<style>
* { padding: 0; margin: 0; }
canvas { background: #000000;
display: block;
margin: 0 auto;
border-color: #A9A9A9;
border-style: dashed;
border-width: 8px;
margin-top: 80px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="600" height="600"></canvas>
<script src="snake.js">
</script>
</body>
</html>
/*****
* deliverables:
* snake game ends when
* 1 snake touches itself
* 2 snake touches outside border
* when the game ends, the gameplay should stop and the user should be notified that the game is over
* the snake should grow one length when it eats the apple
* the new apple should appear randomly on the screen after the previous one has been eaten
* the snake should be controlled by the arrow keys on the keyboard
* the game will show a score of how many apples have been eaten
*/
var gameCanvas = document.getElementById("myCanvas");
let ctx = myCanvas.getContext("2d");
//apple size
var appleWidth = 10;
var appleHeight = 10;
const DIRECTION = {
NORTH: 'NORTH',
SOUTH: 'SOUTH',
EAST: 'EAST',
WEST: 'WEST'
};
var snake;
var snakeDirection;
var score;
var appleLocation;
var gameOver;
var dx = 10;
var dy = 10;
var lives = 3;
ctx.fillRect(0, 0, myCanvas.width, myCanvas.height);
ctx.strokeRect(0, 0, myCanvas.width, myCanvas.height);
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener('mousedown', handleMouseClick);
function startGame() {
snake = [{
x: 150,
y: 150
},
{
x: 140,
y: 150
},
{
x: 130,
y: 150
},
{
x: 120,
y: 150
},
{
x: 110,
y: 150
},
{
x: 100,
y: 150
},
{
x: 90,
y: 150
},
{
x: 80,
y: 150
},
{
x: 70,
y: 60
},
{
x: 50,
y: 150
}
];
snakeDirection = DIRECTION.EAST;
appleLocation = {
x: 250,
y: 150
};
score = 0;
gameInterval = setInterval(Draw, 100);
}
function Draw() {
ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
drawApple();
moveSnake();
drawSnake();
collision();
eatApple();
drawScore();
}
function keyDownHandler(e) {
if (e.key == "Right" || e.key == "ArrowRight") {
snakeDirection = DIRECTION.EAST;
} else if (e.key == "Left" || e.key == "ArrowLeft") {
snakeDirection = DIRECTION.WEST;
} else if (e.key == "Up" || e.key == "ArrowUp") {
snakeDirection = DIRECTION.NORTH;
} else if (e.key == "Down" || e.key == "ArrowDown") {
snakeDirection = DIRECTION.SOUTH;
}
}
function drawApple() {
ctx.fillStyle = 'red';
ctx.strokestyle = 'darkred';
ctx.fillRect(appleLocation.x, appleLocation.y, appleWidth, appleHeight);
ctx.strokeRect(appleLocation.x, appleLocation.y, appleWidth, appleHeight)
}
function drawSnake() {
snake.forEach(drawSnakePart)
}
function drawSnakePart(snake) {
ctx.fillStyle = 'lightgreen';
ctx.strokestyle = 'darkgreen';
ctx.fillRect(snake.x, snake.y, 10, 10);
ctx.strokeRect(snake.x, snake.y, 10, 10);
}
function moveSnake() {
//create copy of snake
var snakeCopy = [];
//loop through snake
for (var i = 0; i < snake.length; i++) {
//for each iteration, add snake body to snake copy
snakeCopy.push({
x: snake[i].x,
y: snake[i].y
});
}
for (var i = 0; i < snake.length; i++) {
if (i === 0) {
if (snakeDirection === DIRECTION.EAST) {
snake[i].x += dx;
}
if (snakeDirection === DIRECTION.WEST) {
snake[i].x -= dx;
}
if (snakeDirection === DIRECTION.NORTH) {
snake[i].y -= dy;
}
if (snakeDirection === DIRECTION.SOUTH) {
snake[i].y += dy;
}
} else {
snake[i].x = snakeCopy[i - 1].x;
snake[i].y = snakeCopy[i - 1].y;
}
}
}
function collision() {
var headX = snake[0].x;
var headY = snake[0].y;
if (headX >= myCanvas.width || headY >= myCanvas.height || headY <= myCanvas.height - 610 || headX <= myCanvas.width - 610) {
ctx.fillText("GAME OVER. You hit the wall. Poor snaky.", 120, 300);
stopGame(gameInterval);//stop the game
gameOver = true;
} else {
snakeBodyCollision();
}
}
function snakeBodyCollision() {
for (var i = 1; i < snake.length; i++)
if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) {
ctx.fillText("Oh, boy. You just bit yourself. GAME OVER.", 120, 300);
stopGame(gameInterval);//stop the game
gameOver = true;
}
}
function eatApple() {
if (snake[0].x == appleLocation.x && snake[0].y == appleLocation.y) {
appleLocation.x = Math.floor(Math.random() * 50) * 10;
appleLocation.y = Math.floor(Math.random() * 50) * 10;
var snakeTail = snake[snake.length - 1];
snake.push({
x: snakeTail.x,
y: snakeTail.y
});
score++;
}
}
function drawScore() {
ctx.font = "16px Arial";
ctx.fillstyle = "#0095DD";
ctx.fillText("Score: " + score, 8, 20);
}
function handleMouseClick(evt) {
if (gameOver) {
startGame();
//document.location.reload();
}
}
function stopGame(interval) {
clearInterval(gameInterval); // Needed for Chrome to end game
}
var gameInterval;
startGame();
Also see: Tab Triggers