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>
<h2 id="header">Javascript Retro Galactic Snake Game</h2>
<!--The scoreContainer represents the div that displays the game's score-->
<div id="scoreContainer">
<div class="scoreBoard">Food: <span id="pointsEarned">0</span></div>
<div class="scoreBoard" style="display:none;" ;>Blocks: <span id="blocksTravelled">0</span></div>
</div>
<!-- The #gameContainer is used as the game's canvas-->
<div id="gameContainer"></div>
</body>
<a style="all:unset;font-family: Roboto, arial, sans-serif;font-size: 20px;width: 100%;text-align: center;display: block;background: linear-gradient(135deg,#001634 10%,#2e143e);line-height: 50px;color: white;position: absolute;top: 0;left: 0;right: 0;text-decoration: none;cursor:pointer;z-index: 9999;" target="_blank" href="https://appcode.app/how-to-build-a-javascript-retro-galactic-snake-game/">Made With ❤️ Click this banner to checkout the snake game tutorial --></a>
body {
text-align: center;
background: #ffd079;
font-family: Arial;
}
#header {
text-align: center;
color: black;
font-weight: bold;
}
/* The game's board style starts here */
#gameContainer {
width: 40vw;
height: 40vw;
margin: 0 auto 2vw auto;
background-color: #0c1021;
border: solid 10px slategrey;
border-radius: 10px;
-webkit-box-shadow: 0px 0px 20px 3px rgb(0 0 0 / 60%);
-moz-box-shadow: 0px 0px 20px 3px rgba(0, 0, 0, 0.6);
box-shadow: 0px 0px 20px 3px rgb(0 0 0 / 60%);
overflow: hidden;
transform: scale(0.75);
}
.gameBoardPixel {
/* background-color: grey; */
/*
The 1vw used here represents 1% of the entire viewpoint height and width. It
is also used in a calculation line in a javascript code below
*/
width: 1vw;
height: 1vw;
border-radius: 3px;
float: left;
}
/* The game canva style ends here */
/* The snake style starts here */
.snakeBodyPixel {
background-color: white;
}
/* The snake style ends here */
/* The food style starts here */
.food {
border-radius: 20px;
}
.food1 {
background-color: #0077ff;
transform: scale(1.2);
}
.food2 {
background-color: red;
transform: scale(2);
}
.food3 {
background-color: orange;
transform: scale(0.75);
}
.blackhole {
box-shadow: 0 0 32px 15px #fff, /* inner white */ 0 0 64px 15px #f0f,
/* middle magenta */ 0 0 61px 15px #0ff;
}
/* The food style ends here */
/* The game's score style */
#scoreContainer {
width: 25vw;
display: flex;
margin: auto;
justify-content: space-around;
}
.scoreBoard {
color: black;
background-color: orange;
display: inline-block;
padding: 1vw;
width: 40%;
font-size: 20px;
position: absolute;
top: 0;
left: 0;
width: 100px;
}
/* The game's score style ends here */
// This is the pixels on vertical or horizonal axis of the game itself in (SQUARE)
const GAME_PIXEL_COUNT = 40;
const SQUARE_OF_GAME_PIXEL_COUNT = Math.pow(GAME_PIXEL_COUNT, 2);
let totalFoodAte = 0;
let totalDistanceTravelled = 0;
/// Here's the game canva function
const gameContainer = document.getElementById("gameContainer");
const createGameBoardPixels = () => {
// Populate the [#gameContainer] div with small div's representing game pixels
for (let i = 1; i <= SQUARE_OF_GAME_PIXEL_COUNT; ++i) {
gameContainer.innerHTML = `${gameContainer.innerHTML} <div class="gameBoardPixel" id="pixel${i}"></div>`;
}
};
// This variable always holds the updated array of game pixels created by createGameBoardPixels() :
const gameBoardPixels = document.getElementsByClassName("gameBoardPixel");
/// THE FOOD:
let currentFoodPostion = 0;
let foodArray = ["food1", "food2", "food3"];
const createFood = (position) => {
// Remove previous food;
gameBoardPixels[position].classList.remove("food");
gameBoardPixels[position].classList.remove("food1");
gameBoardPixels[position].classList.remove("food2");
gameBoardPixels[position].classList.remove("food3");
// Create new food
currentFoodPostion = Math.random();
currentFoodPostion = Math.floor(
currentFoodPostion * SQUARE_OF_GAME_PIXEL_COUNT
);
gameBoardPixels[currentFoodPostion].classList.add("food");
let randomFood = foodArray[Math.floor(Math.random() * foodArray.length)];
gameBoardPixels[currentFoodPostion].classList.add(randomFood.toString());
let foo = Math.random() * 100;
if (foo < 40) {
// 0-79 {
blackhole();
}
};
const blackhole = () => {
// Create new food
currentFoodPostion = Math.random();
currentFoodPostion = Math.floor(
currentFoodPostion * SQUARE_OF_GAME_PIXEL_COUNT
);
gameBoardPixels[currentFoodPostion].classList.add("food");
let randomFood = foodArray[Math.floor(Math.random() * foodArray.length)];
gameBoardPixels[currentFoodPostion].classList.add("blackhole");
};
/// THE FOOD:
let currentFoodPostionPlot = 0;
const createFoodPlot = () => {
// Create new food
for (let i = 0; i < 10; i++) {
let currentFoodPostionPlot = 0;
currentFoodPostionPlot = Math.random();
currentFoodPostionPlot = Math.floor(
currentFoodPostionPlot * SQUARE_OF_GAME_PIXEL_COUNT
);
let randomFood = foodArray[Math.floor(Math.random() * foodArray.length)];
gameBoardPixels[currentFoodPostionPlot].classList.add("food");
gameBoardPixels[currentFoodPostionPlot].classList.add(
randomFood.toString()
);
let foo = Math.random() * 100;
if (foo < 40) {
// 0-79 {
blackhole();
}
}
};
/// THE SNAKE:
// Direction codes (Keyboard key codes for arrow keys):
const LEFT_DIR = 37;
const UP_DIR = 38;
const RIGHT_DIR = 39;
const DOWN_DIR = 40;
// Set snake direction initially to right
let snakeCurrentDirection = RIGHT_DIR;
const changeDirection = (newDirectionCode) => {
// Change the direction of the snake
if (newDirectionCode == snakeCurrentDirection) return;
if (newDirectionCode == LEFT_DIR && snakeCurrentDirection != RIGHT_DIR) {
snakeCurrentDirection = newDirectionCode;
} else if (newDirectionCode == UP_DIR && snakeCurrentDirection != DOWN_DIR) {
snakeCurrentDirection = newDirectionCode;
} else if (
newDirectionCode == RIGHT_DIR &&
snakeCurrentDirection != LEFT_DIR
) {
snakeCurrentDirection = newDirectionCode;
} else if (newDirectionCode == DOWN_DIR && snakeCurrentDirection != UP_DIR) {
snakeCurrentDirection = newDirectionCode;
}
};
// Let the starting position of the snake be at the middle of game board
let currentSnakeHeadPosition = SQUARE_OF_GAME_PIXEL_COUNT / 1;
// Initial snake length
let snakeLength = 1000;
// This will keep moving the snake constantly by calling this function repeatedly :
const moveSnake = () => {
switch (snakeCurrentDirection) {
case LEFT_DIR:
--currentSnakeHeadPosition;
const isSnakeHeadAtLastGameBoardPixelTowardsLeft =
currentSnakeHeadPosition % GAME_PIXEL_COUNT == GAME_PIXEL_COUNT - 1 ||
currentSnakeHeadPosition < 0;
if (isSnakeHeadAtLastGameBoardPixelTowardsLeft) {
currentSnakeHeadPosition = currentSnakeHeadPosition + GAME_PIXEL_COUNT;
}
break;
case UP_DIR:
currentSnakeHeadPosition = currentSnakeHeadPosition - GAME_PIXEL_COUNT;
const isSnakeHeadAtLastGameBoardPixelTowardsUp =
currentSnakeHeadPosition < 0;
if (isSnakeHeadAtLastGameBoardPixelTowardsUp) {
currentSnakeHeadPosition =
currentSnakeHeadPosition + SQUARE_OF_GAME_PIXEL_COUNT;
}
break;
case RIGHT_DIR:
++currentSnakeHeadPosition;
const isSnakeHeadAtLastGameBoardPixelTowardsRight =
currentSnakeHeadPosition % GAME_PIXEL_COUNT == 0;
if (isSnakeHeadAtLastGameBoardPixelTowardsRight) {
currentSnakeHeadPosition = currentSnakeHeadPosition - GAME_PIXEL_COUNT;
}
break;
case DOWN_DIR:
currentSnakeHeadPosition = currentSnakeHeadPosition + GAME_PIXEL_COUNT;
const isSnakeHeadAtLastGameBoardPixelTowardsDown =
currentSnakeHeadPosition > SQUARE_OF_GAME_PIXEL_COUNT - 1;
if (isSnakeHeadAtLastGameBoardPixelTowardsDown) {
currentSnakeHeadPosition =
currentSnakeHeadPosition - SQUARE_OF_GAME_PIXEL_COUNT;
}
break;
default:
break;
}
let nextSnakeHeadPixel = gameBoardPixels[currentSnakeHeadPosition];
// Kill snake if it bites itself:
if (nextSnakeHeadPixel.classList.contains("snakeBodyPixel")) {
// Stop moving the snake
clearInterval(moveSnakeInterval);
if (!alert(`GAME OVER! Your Final Score is ${totalFoodAte}`))
window.location.reload();
}
let blackHole = gameBoardPixels[currentSnakeHeadPosition].classList.contains(
"blackhole"
);
if (blackHole) {
// Stop moving the snake
clearInterval(moveSnakeInterval);
if (
!alert(
`You've been swallowed by a Black Hole!! GAME OVER! Your Final Score is ${totalFoodAte}`
)
)
window.location.reload();
}
nextSnakeHeadPixel.classList.add("snakeBodyPixel");
setTimeout(() => {
nextSnakeHeadPixel.classList.remove("snakeBodyPixel");
}, snakeLength);
// Update total distance travelled
totalDistanceTravelled++;
// Update in UI:
document.getElementById("blocksTravelled").innerHTML = totalDistanceTravelled;
let hasFood = gameBoardPixels[currentSnakeHeadPosition].classList.contains(
"food"
);
if (hasFood) {
// Update total food ate
totalFoodAte++;
// Update in UI:
document.getElementById("pointsEarned").innerHTML = totalFoodAte;
// Increase Snake length:
snakeLength = snakeLength + 100;
createFood(currentSnakeHeadPosition);
}
};
/// CALL THE FOLLOWING FUNCTIONS TO RUN THE GAME:
// Create game board pixels:
createGameBoardPixels();
// Create initial food:
createFoodPlot();
// Move snake:
var moveSnakeInterval = setInterval(moveSnake, 100);
// Call change direction function on keyboard key-down event:
addEventListener("keydown", (e) => changeDirection(e.keyCode));
Also see: Tab Triggers