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.
<!-- <link rel="stylesheet" href="style.css"> -->
<!-- Idea from -->
<!-- https://dev.to/gscode/10-best-of-javascript-games-3mjj -->
<div class="body">
<div class="box">
<h1 class="title">: High Score :</h1>
<div class="d-flex jcc alc fc">
<div class="d"><h3 class="title t1">Easy: <h3 class="high high1"></h3></h3></div>
<div class="d"><h3 class="title t1">Medium: <h3 class="high high2"></h3></h3></div>
<div class="d"><h3 class="title t1">Hard: <h3 class="high high3"></h3></h3></div>
<div class="d"><h3 class="title t1">Very Hard: <h3 class="high high4"></h3></h3></div>
</div>
<h1 class="title">: Select Level :</h1>
<div class="buttons">
<input type="button" value="Easy" class="sbtn easy" style="--bg:green">
<input type="button" value="Medium" class="sbtn medium" style="--bg:blue">
<input type="button" value="Hard" class="sbtn hard" style="--bg:blueviolet">
<input type="button" value="Very Hard" class="sbtn vhard" style="--bg:red">
</div>
</div>
</div>
<div class="div">
<h1 class="title">Snake Game</h1>
<div class="d-flex">
<h1 class="">Score: </h1>
<h1 class="sc"></h1>
<h1 class="score"></h1>
</div>
<input type="text" name="" id="txt" multiple autofocus>
<div class="container">
</div>
<div class="keyBtns">
<div class="d-flex jcc alc fc">
<div class="d"><input type="button" value="⏫" class="arrowBtns up"></div>
<div class="d">
<input type="button" value="⏪" class="arrowBtns left">
<input type="button" value="⏬" class="arrowBtns down">
<input type="button" value="⏩" class="arrowBtns right">
</div>
</div>
</div>
</div>
<!-- <script src="./script.js"></script> -->
@import url('https://fonts.googleapis.com/css2?family=Raleway:ital,wght@0,100;0,300;0,500;0,700;1,900&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: system-ui, -apple-system, sans-serif;
}
body,.body,.div{
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
background: linear-gradient(to bottom right,#d6bdb9,#eccea7,#eacda8);
position: relative;
}
.body{
width: 100vw;
min-height: 100vh;
}
.div{
background: transparent;
}
.d-flex{
display: flex;
}
.d-none{
display: none;
}
.title,.score{
color:rgb(45, 98, 147);
}
.jcc{
justify-content: center;
}
.alc{
align-items: center;
}
.fc{
flex-direction: column;
}
.container
{
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
width: 75vh;
aspect-ratio: 1/1;
background: rgba(255,255,255,0.2);
box-shadow: 0 0 15px 2px rgb(126, 98, 98);
border-radius: 12px;
}
table{
width: 100%;
aspect-ratio: 1/1;
/* background: white; */
background: rgba(255,255,255,0.1);
animation: filterAnimate 3s infinite;
}
tr{
width: 100%;
}
tr > td{
width: 5%;
height: 5%;
/* border: 1px solid rgb(109, 98, 98); */
/* background: white; */
transition: all 0.2s;
}
.active,.last{
border-radius: 6px;
background: rgb(45, 98, 147) !important;
border: 2px solid rgb(121, 48, 48) !important;
}
.active-first{
border-radius: 6px;
background: darkblue !important;
border: 3px solid rgb(121, 48, 48) !important;
}
#txt{
width: 0%;
border: none;
outline: none;
background: none;
}
.food{
background: rgb(68, 146, 68);
transition: all 0.2s;
animation: animate 0.7s infinite;
border-radius: 15px;
}
@keyframes animate {
0%,100%{
opacity: 0;
border-radius: 12px;
}
50%{
opacity:1;
border-radius: 15px;
}
}
.score{
position: relative;
display: inline-block;
/* color: green */
font-family: Raleway;
}
.effect{
display: inline-block;
position: absolute;
top:15%;
left: 50%;
opacity:0.2;
animation: effect 1.3s;
}
@keyframes effect {
0%{
top:15%;
left: 50%;
opacity: 0.8;
}
90%{
top:0%;
left: 53%;
opacity: 0;
}
}
.box{
z-index:3333;
height: fit-content;
padding: 20px 0px;
width: 40vw;
/* border: 1px solid rgb(45, 98, 147); */
box-shadow: 0 0 13px 1px azure;
background: white;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
border-radius: 14px;
}
.box .title{
margin-bottom: 20px
}
.box input{
padding: 10px 20px;
background: transparent;
border: 1px solid var(--bg);
color: var(--bg);
border-radius: 10px;
font-weight: 600;
font-family: Raleway;
margin-right: 10px;
transition: all 0.6s;
}
.box input:hover{
color: white;
background: var(--bg);
border: 1px solid var(--bg)
}
.t1{
color: black;
opacity: 0.7;
display: inline-block;
}
.high{
display: inline-block;
margin: 10px 25px 10px 10px;
color:blue
}
.keyBtns{
display: none;
}
@media screen and (max-width:708px){
.container,.box{
width:95vw !important;
}
.buttons{
display: flex;
flex-direction: column;
}
.buttons input{
margin: 10px;
}
}
@media screen and (max-width: 576px){
.keyBtns{
display: flex;
}
.keyBtns input{
margin-top: 30px;
background: transparent;
border:none;
outline: none;
font-size: 14vw;
}
#txt{
display: none !important;
}
}
//start game when level is selected
const numOfBlocks = 400;
const mySel = (sel) => document.querySelector(sel);
const mySelAll = (sel) => document.querySelectorAll(sel);
const numOfRow = Math.sqrt(numOfBlocks);
// const randomNum = () => Math.floor(Math.random() * numOfBlocks);
const randomRow = () => Math.floor(Math.random() * numOfRow);
var level = ""
var scoreCounterUpto = 1;
var snakeSpeed;
var score = 0;
if (!localStorage.getItem("snakeEasy")) {
mySel(".high1").innerText = '0';
} else {
mySel(".high1").innerText = localStorage.getItem("snakeEasy");
}
if (!localStorage.getItem("snakeMedium")) {
mySel(".high2").innerText = '0';
} else {
mySel(".high2").innerText = localStorage.getItem("snakeMedium");
}
if (!localStorage.getItem("snakeHard")) {
mySel(".high3").innerText = '0';
} else {
mySel(".high3").innerText = localStorage.getItem("snakeHard");
}
if (!localStorage.getItem("snakeVHard")) {
mySel(".high4").innerText = '0'
} else {
mySel(".high4").innerText = localStorage.getItem("snakeVHard");
}
//default hide the game
mySel(".div").classList.add("d-none");
mySelAll(".sbtn").forEach((btn) => {
btn.addEventListener("click", (e) => {
if (e.target.classList.contains("easy")) {
level = "easy"
scoreCounterUpto = 5;
snakeSpeed = 900;
}
else if (e.target.classList.contains("medium")) {
level = "medium"
scoreCounterUpto = 7;
snakeSpeed = 400;
}
else if (e.target.classList.contains("hard")) {
level = "hard"
scoreCounterUpto = 10;
snakeSpeed = 100;
}
else if (e.target.classList.contains("vhard")) {
level = "vhard"
scoreCounterUpto = 15;
snakeSpeed = 40;
}
startGame()
})
})
function startGame() {
//hide level block and show snake box
mySel(".div").classList.remove("d-none")
mySel(".body").classList.add("d-none")
var foodX = 0;
var foodY = 0;
var scoreCounter = 1;
mySel(".score").innerText += score;
//insert table tr and td
let newBlocks = "<table>";
let count = 0;
for (let i = 0; i < Math.sqrt(numOfBlocks); i++) {
newBlocks += `<tr>`;
for (let j = 0; j < Math.sqrt(numOfBlocks); j++) {
newBlocks += `<td class="r${i} c${j} "></td>`;
count++;
}
newBlocks += `</tr>`;
}
newBlocks += `</table>`;
const container = mySel(".container");
container.innerHTML = newBlocks;
//disable tab key
document.onkeydown = function (t) {
if (t.which == 9)
return false;
}
var width = document.body.clientWidth;
if(width > 576){
//onclick focus
document.onclick = function (e) {
mySel("#txt").focus();
}
}
//checkMove
var curKey = ""
function checkMove() {
document.addEventListener("keydown", (e) => { curKey = e.key })
//for mobile users
mySelAll(".arrowBtns").forEach((btn) => {
btn.addEventListener("click", () => {
if(btn.classList.contains("left")){
curKey = "ArrowLeft"
}
else if(btn.classList.contains("right")){
curKey = "ArrowRight"
}
else if(btn.classList.contains("up")){
curKey = "ArrowUp"
}
else if(btn.classList.contains("down")){
curKey = "ArrowDown"
}
})
})
return curKey;
}
var snake = [[0, 0], [0, 1], [0, 2], [0, 3]];
//remove All Effect (of previous active td(s))
removeAllEfect = () => {
let allTd = mySelAll("td");
allTd.forEach((td) => {
td.classList.remove("active")
})
}
//change the direction
changeDirection = () => {
removeAllEfect()
snake.forEach((cur, index) => {
//if snake eat food
if (snake[snake.length - 1][0] == foodX && snake[snake.length - 1][1] == foodY) {
//increase score
if (scoreCounter == scoreCounterUpto && score != 0) {
score = score + 5
mySel(".sc").innerHTML = `<h1 class="effect">+ 5</h1>`;
setTimeout(() => {
mySel(".sc").innerHTML = ``;
}, 1200)
scoreCounter = 1;
}
else {
++scoreCounter;
++score;
}
//show score
mySel(".score").innerText = score;
// remove old food
mySel("table").children[0].children[parseInt(foodX)].children[parseInt(foodY)].classList.remove("food")
snake.push([foodX, foodY])
food();
// snake.unshift([])
}
//gameover
if (snake[snake.length - 1][0] == numOfRow || snake[snake.length - 1][1] == numOfRow || snake[snake.length - 1][0] == -1 || snake[snake.length - 1][1] == -1) {
gameOver();
}
mySel("table").children[0].children[cur[0]].children[cur[1]].classList.add("active")
})
}
var lastMoves = [""];
const changeMove = setInterval(() => {
let move = checkMove() || "ArrowRight";
//last
let row = snake[snake.length - 1][0];
let col = snake[snake.length - 1][1];
// let len = snake.length;
//insert unique last pressed keys
if (lastMoves[lastMoves.length - 1] != move) {
lastMoves.push(move)
}
// lastMoves[lastMoves.length-2] != "ArrowUp" This is block the unidirectoin move
if (move == "ArrowDown" && lastMoves[lastMoves.length - 2] != "ArrowUp") {
down(row)
}
if (move == "ArrowRight" && lastMoves[lastMoves.length - 2] != "ArrowLeft") {
right(col)
}
if (move == "ArrowUp" && lastMoves[lastMoves.length - 2] != "ArrowDown") {
up(row)
}
if (move == "ArrowLeft" && lastMoves[lastMoves.length - 2] != "ArrowRight") {
left(col)
}
changeDirection()
checkOverride();
}, snakeSpeed)
//movement
function up(row) {
snake[snake.length - 1][0] = row;
snake.push([snake[snake.length - 1][0] - 1, snake[snake.length - 1][1]])
snake.shift();
}
function down(row) {
snake[snake.length - 1][0] = row;
snake.push([snake[snake.length - 1][0] + 1, snake[snake.length - 1][1]])
snake.shift();
}
function right(col) {
snake[snake.length - 1][1] = col;
snake.push([snake[snake.length - 1][0], snake[snake.length - 1][1] + 1])
snake.shift();
}
function left(col) {
snake[snake.length - 1][1] = col;
snake.push([snake[snake.length - 1][0], snake[snake.length - 1][1] - 1])
snake.shift();
}
food()
//generate random food
function food() {
foodX = randomRow();
foodY = randomRow();
//add food at random place
mySel("table").children[0].children[parseInt(foodX)].children[parseInt(foodY)].classList.add("food")
}
function gameOver() {
let ii = 0;
clearInterval(changeMove);
if ((parseInt(localStorage.getItem("snakeEasy")) < score || !localStorage.getItem("snakeEasy")) && level == "easy") {
localStorage.setItem("snakeEasy", score)
alert("Game over!!\n\n congrats\n You did new high score :) ");
ii++;
}
if ((parseInt(localStorage.getItem("snakeMedium")) < score || !localStorage.getItem("snakeMedium")) && level == "medium") {
localStorage.setItem("snakeMedium", score)
ii++;
alert("Game over!!\n\n congrats\n You did new high score :) ");
}
if ((parseInt(localStorage.getItem("snakeHard")) < score || !localStorage.getItem("snakeHard")) && level == "hard") {
localStorage.setItem("snakeHard", score)
ii++;
alert("Game over!!\n\n congrats\n You did new high score :) ");
}
if ((parseInt(localStorage.getItem("snakeVHard")) < score || !localStorage.getItem("snakeVHard")) && level == "vhard") {
localStorage.setItem("snakeVHard", score)
ii++;
alert("Game over!!\n\n congrats\n You did new high score :) ");
}
if (ii == 0){
alert("Game over !!\n\n This is not easy as you imagine :( ")
// window.location.reload()
}
}
//fix override snake
function checkOverride() {
for (let i = 0; i < snake.length - 2; i++) {
if ((snake[i][0] == snake[snake.length - 1][0]) && (snake[i][1] == snake[snake.length - 1][1])) {
gameOver(); i = snake.length-2
}
}
}
}
Also see: Tab Triggers