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.
<body>
<!-- GAME BODY -->
<div id="screen">
<div id="gameBoardStyleWrapper">
<div id="gameBoard">
<div id="snakeGrid"></div>
</div>
</div>
<div id="game-setttings">
<div id="scoreBoard" class="game-pane tile">
<p id="score">Welcome!</p>
<p id="high-score"></p>
</div>
<div id="game-controls" class="game-pane tile">
<button class="btn fuchsia" id="do-play" onclick="handleToggleGamePlay()">Play Game</button>
<div class="sub-option">
<p>Game Speed:</p>
<button class="btn blue" id="game-speed" onClick="handleChangeGameSpeed()">Medium</button>
</div>
</div>
</div>
</div>
</body>
/* CSS VARIABLES */
:root {
/* These colors taken from http://clrs.cc/ */
--fuchsia: #F012BE;
--blue: #0074D9;
--navy: #001f3f;
--black: #111111;
--green: #2ECC40;
--yellow: #FFDC00;
--gold: goldenrod;
--red: #FF4136;
--white: #FFFFFF;
}
/* GENERAL CSS */
body {
background-color: var(--black);
}
#screen {
height: 100%;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
#gameBoard {
position: relative;
height: 600px;
width: 900px;
}
.tile {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
margin: 1em;
font-family: "Arial";
font-size: 1.25em;
}
.btn {
font-size: 1em;
border: none;
padding: 0.25em 0.5em .25em .5em;
cursor: pointer;
transition: background-color .1s;
}
.blue {
background-color: var(--blue);
color: var(--white);
}
.fuchsia {
background-color: var(--fuchsia);
color: var(--white);
}
.red {
background-color: var(--red);
color: var(--white);
}
/* GAME OPTIONS CSS */
.game-pane {
padding: 1em;
background-color: var(--navy);
color: white;
text-align: center;
}
.sub-option {
font-size: .75em;
}
/* MAIN GAME GRID CSS */
#snakeGrid {
position: absolute;
top: 0;
left: 0;
/* These three move the gameboard to the exact top-left corner */
height: 600px;
width: 900px;
background-image: url("https://images.pexels.com/photos/110854/pexels-photo-110854.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb");
background-size: cover;
z-index: 100;
/*Gives precedence as to what will be shown in the forefront*/
}
div.snake {
position: absolute;
top: 0;
left: 0;
/* We'll be overriding the top and left. */
height: 15px;
width: 15px;
z-index: 300;
background-color: var(--fuchsia);
/*border-radius: 50%;*/
}
div.food {
position: absolute;
top: 0;
left: 0;
background-color: var(--gold);
height: 15px;
width: 15px;
border-radius: 50%;
z-index: 200;
}
// <!-- GAME JAVASCRIPT -->
// <!-- Follows is the game state -->
// Environment variables.
// This code is only executed once.
var GRID_HEIGHT = 40; // = 600 / 15
var GRID_WIDTH = 60; // = 900 / 15
var BLOCK_SIZE = 15;
// Accesses the correct COL_CHANGE and ROW_CHANGE
var DIRECTIONS = {
up: 0,
right: 1,
down: 2,
left: 3
}
/*
0
3 1
2
*/
var COL_CHANGE = [0, 1, 0, -1];
var ROW_CHANGE = [-1, 0, 1, 0];
//slow, med, fast
var GAME_SPEEDS = [
{name: "Slow", speed: 200},
{name: "Medium", speed: 140},
{name: "Fast", speed: 80}
];
var SNAKE_DIRECTION = DIRECTIONS["up"];
var IS_DYING = false;
var IS_EATING = false;
var CURRENT_GAME_SPEED = GAME_SPEEDS[1]; // Set to Medium
var HIGH_SCORE = 0;
var PLAY_GAME = false;
var PAUSE_FOR_DEATH = false;
var GAME_LOOP;
var gameScore = 0;
// Get the snakeGrid and other elements so we can
// dynamically change them throughout the game.
var gameGrid = document.getElementById("snakeGrid");
var scoreText = document.getElementById("score");
var playButton = document.getElementById("do-play");
var highScoreText = document.getElementById("high-score");
var gameSpeedButton = document.getElementById("game-speed");
// Handle user input
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '38') {
// up arrow
SNAKE_DIRECTION = DIRECTIONS["up"];
} else if (e.keyCode == '40') {
// down arrow
SNAKE_DIRECTION = DIRECTIONS["down"];
} else if (e.keyCode == '37') {
// left arrow
SNAKE_DIRECTION = DIRECTIONS["left"];
} else if (e.keyCode == '39') {
// right arrow
SNAKE_DIRECTION = DIRECTIONS["right"];
}
}
var snake = [];
var snakeHead = new SnakePiece(20, 30);
snake.push(new SnakePiece(20, 31));
snake.push(new SnakePiece(20, 32));
snake.push(new SnakePiece(20, 33));
snake.push(new SnakePiece(20, 34));
var foods = [];
foods.push(new FoodPiece());
foods.push(new FoodPiece());
foods.push(new FoodPiece());
// the shift() and unshift() functions let you use a javascript array as a queue.
snake.push(snakeHead);
// Will execute function() every CURRENT_GAME_SPEED.speed milliseconds
function play() {
GAME_LOOP = setInterval(function () {
///////////////////////// Main Game Loop //////////////////////
// Move the snake one space in it's current direction.
snake.unshift(new SnakePiece(snake[0].row + ROW_CHANGE[SNAKE_DIRECTION], snake[0].col + COL_CHANGE[SNAKE_DIRECTION]));
IS_EATING = isEating();
if (IS_EATING) {
gameScore = gameScore + 1;
console.log("YOU ATE A FOOD");
}
// move tail of snake
if (!IS_EATING) {
gameGrid.removeChild(snake.pop().el);
}
IS_DYING = isDying();
if (IS_DYING) {
// The snake collided with a wall or with itself.
PLAY_GAME = false;
handleDeath();
console.log("YOU'VE DIED");
}
// End of cycle logic.
IS_EATING = false;
IS_DYING = false;
console.log(SNAKE_DIRECTION);
// console.log(foods);
scoreText.innerText = "Your Score: " + gameScore;
if(!PAUSE_FOR_DEATH) {
playButton.innerText = PLAY_GAME ? "End Game" : "Play Game";
}
// Spawn more foods if they're all gone.
if (foods.length < 1) {
foods.push(new FoodPiece());
foods.push(new FoodPiece());
foods.push(new FoodPiece());
}
}, CURRENT_GAME_SPEED.speed);
}
/*
* EVENT HANDLER FUNCTIONS
*/
function handleToggleGamePlay() {
PLAY_GAME = !PLAY_GAME;
console.log("PLAY_GAME ?: ",PLAY_GAME);
if(PLAY_GAME) {
play();
} else {
clearInterval(GAME_LOOP);
}
}
function handleChangeGameSpeed() {
if (!PLAY_GAME) {
// We can only change the game speed while a game is not going
var currentSpeedIndex = GAME_SPEEDS.indexOf(CURRENT_GAME_SPEED);
var nextSpeedIndex = (currentSpeedIndex < GAME_SPEEDS.length - 1) ? (currentSpeedIndex + 1) : 0;
CURRENT_GAME_SPEED = GAME_SPEEDS[nextSpeedIndex];
console.log("updated game speed:",CURRENT_GAME_SPEED)
gameSpeedButton.innerText = GAME_SPEEDS[nextSpeedIndex].name;
}
}
function handleDeath() {
// Stop the game loop and reset/update the scores
clearInterval(GAME_LOOP);
var highScore = Math.max(HIGH_SCORE, gameScore);
highScoreText.innerText = "Your High Score: " + highScore;
gameScore = 0;
// Show the death message
playButton.classList.remove('fuchsia');
playButton.classList.add('red');
PAUSE_FOR_DEATH = true;
playButton.innerText = "You Have Died";
// Delete the current snake
while(snake[0]) {
gameGrid.removeChild(snake.pop().el);
}
// Wait for a second, then reinitialize the snake
setTimeout(function(){
playButton.innerText = "Play Game";
playButton.classList.remove('red');
playButton.classList.add('fuchsia');
// Initialize a new snake
snakeHead = new SnakePiece(20, 30);
snake.push(new SnakePiece(20, 31));
snake.push(new SnakePiece(20, 32));
snake.push(new SnakePiece(20, 33));
snake.push(new SnakePiece(20, 34));
snake.push(snakeHead);
PAUSE_FOR_DEATH = false;
},1500);
}
/*
CONSTRUCTOR FUNCTIONS
*/
// Constructor for a new snake piece.
function SnakePiece(row, col) {
var mySnakePieceElement = document.createElement("div");
mySnakePieceElement.className = "snake";
mySnakePieceElement.style.top = (row * BLOCK_SIZE) + "px";
mySnakePieceElement.style.left = (col * BLOCK_SIZE) + "px";
gameGrid.appendChild(mySnakePieceElement);
// curRow and curCol are declared inside the function,
// so the calling code can't use it. It's javascript's
// version of a private variable.
//var curRow = row;
//var curCol = col;
this.col = col;
this.row = row;
this.el = mySnakePieceElement;
//this.movePiece = function() {
// this.col += COL_CHANGE[SNAKE_DIRECTION];
// this.row += ROW_CHANGE[SNAKE_DIRECTION];
// this.el.style.top = (this.row * BLOCK_SIZE) + "px";
// this.el.style.left = (this.col * BLOCK_SIZE) + "px";
//}
}
// Constructor for a new food piece.
function FoodPiece() {
var col = getRandomInt(0, GRID_WIDTH - 1);
var row = getRandomInt(0, GRID_HEIGHT - 1);
var myFoodElement = document.createElement("div");
myFoodElement.className = "food";
myFoodElement.style.top = (row * BLOCK_SIZE) + "px";
myFoodElement.style.left = (col * BLOCK_SIZE) + "px";
gameGrid.appendChild(myFoodElement);
this.col = col;
this.row = row;
this.el = myFoodElement;
}
function isDying() {
// hits wall
var head = snake[0];
if (head.row < 0 || head.row >= GRID_HEIGHT || head.col < 0 || head.col >= GRID_WIDTH) {
return true;
}
// collides with self
var i;
for (i = 1; i < snake.length; i++) {
var curPiece = snake[i];
// === is more explicit. It demands that datatypes be the same.
// == would return true with '1' == 1, for example.
if (head.row === curPiece.row && head.col === curPiece.col) {
return true;
}
}
return false;
}
function isEating() {
// eats food
var head = snake[0];
var i;
for (i = 0; i < foods.length; i++) {
var curPiece = foods[i];
if (head.row === curPiece.row && head.col === curPiece.col) {
// Gets rid of food i (since its been eaten)
foods.splice(i, 1);
gameGrid.removeChild(curPiece.el);
return true;
}
}
return false;
}
/*
UTILITY FUNCTIONS
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Also see: Tab Triggers