Prank on snake game using HTML,CSS AND JS.

 Tittle : Prank on snake game


            It is a very basic project for the beginners using HTML, CSS and JavaScript

                           HTML  - Hypertext Markup Language 

                                CSS - Cascading Style Sheet

                                     JS  -  Java Script


ABSTRACT

This project is designed for fun (prank). This also include gaming things, where as SNAKE PRANK GAME is designed with following languages: HTML, CSS, JS. Snake is the common name for a video game concept where the player maneuvers a line which grows in length which is snakes body. Where This is most interesting game where a snake eats balls where the moment of snake is operated by user with given UP, DOWN, RIGHT_SIDE, LEFT_SIDE buttons, here the game is played by the user and we have to give a range of number in the code itself, the range is used for number of balls that snake eats, when the range exceeds a prank video is displayed (‘PRANK ON YOU’ ). User can use it to prank and scare their friends easily.


You can run it on any platform like sublime text, visual studio code etc..

* Go to my GitHub profile to download the zip file . click here to download the project. Or copy the code below(👇) in your specific IDE.

               Before You Try it Watch the Output Video 👇:


     


HTML CODE:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="fontawesome/all.css">
    <link rel="stylesheet" href="fontawesome/fontawesome.css">
    <title>Classic Snake Game</title>
</head>
<body>
    <div id="overlay">
        <div id="gif">
            <video id="myVideo" style="display:none">
            <source id="mp4_src" src="snake.mp4" type="video/mp4">
            Your browser does not support the video tag.
      </video>
        </div>
    </div>
    <div class="main-container">
        <div class="result-container">
            <div class="name"><h2>
               Classic Snake Game
            </h2></div>
            <div class="score">Score: <span id="score__text">0</span></div>
           <!--  <div class="speed">Speed: <span id="speed__text">0</span>x </div> -->
        </div>
        <div class="game-container">           
        </div>
        
    
    <div class="controls-container">
        <div class="start"><div id="startGame">Start</div></div>
        <div class="controls">
            <div class="up" id="up"><i id="up" class="fas fa-chevron-circle-up fa-2x"></i></div>
            <div class="horizontal"><i id="left" class="fas fa-chevron-circle-left fa-2x"></i><i id="right" class="fas fa-chevron-circle-right fa-2x"></i></div>
            <div class="down" id="down"><i id="down" class="fas fa-chevron-circle-down fa-2x"></i></div>
        </div>
    </div>
</div>

<!-- Modal -->

<div class="modal-div">
    <div class="modal-container">
        <p><span id="modal--over__text">Game Over!!!</span> Score: <span id="modal__score">0</span></p>
    </div>
</div>



    <script src="script.js"></script>
</body>
</html>









CSS CODE:

:root{
    --main-outline: 1px solid black;
    --tile-border: 1px solid rgba(5, 196, 107,0.4);
    --tile-width: calc(100% / 16);
    --tile-height: calc(100% / 16);
    --side-bg-color: rgba(24, 44, 97,1.0);
}

@font-face {
    font-family: "CustomFont";
    src:url('fonts/BalsamiqSans-Regular.ttf');
}

html{
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    font-size: 10px;
    font-family: 'CustomFont';   
    background-image: url('bg_main.jpg');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    /* background: linear-gradient(to right, rgba(249, 127, 81,1.0), rgba(234, 181, 67,1.0)); */
}

body{
    width: 80%;
    height: 100%;
    margin: 0;
    padding: 0;
    margin-left: auto;
    margin-right: auto;
    overflow: hidden;
}

.main-container{
    width: 80%;
    height: 60%; 
    box-sizing: border-box;
    margin-top: 10vh;
    margin-left: auto;
    margin-right: auto;
    border:1px solid black;
    box-shadow: 0 0 5px rgba(68, 189, 50,1.0);
    border-radius: 5px;
    display: flex;
    flex-direction: row;
}

#overlay {
  position: fixed;
  display: none;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.8);
  z-index: 2;
  cursor: pointer;
}

#myVideo{
  position: absolute;
  top:0;
  left:0;
  width:100%;
  height:100%;
  }


/* game container */

.main-container .game-container{
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    height: 100%;
    outline: var(--testing-outline);
    background: linear-gradient(to right, #34e7e4,#0be881);

}

.main-container .game-container .tile{
    box-sizing: border-box;
    border-right: var(--tile-border);
    border-bottom: var(--tile-border);
    height: var(--tile-height);
    width: var(--tile-width);
    font-size: 1.3rem;
    font-weight: 500;
    background-color: transparent;
}

.main-container .game-container .tile .move__right{
    background-color: #000;
    width: 0%;
    height: 100%;
    display: block;
    
    animation-name: move__right;
    animation-duration: 500ms;
    animation-iteration-count: 1;
    animation-timing-function: linear;     
}


.main-container .game-container .tile.active{
    background-color: rgba(24, 44, 97,1.0);
}
.main-container .game-container .tile .active{
    background-color: #000;
    width: 100%;
    height: 100%;
    display: block;
}


/* game container */

/* result container */
.result-container{
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    
    width: 20%;
    font-size: 2rem;
    background-color: var(--side-bg-color);
    color: white;
    box-sizing: border-box;
    text-align: center;
}

.result-container *{
    margin: 0;
    padding: 0;
}

/* result container */



/* contorls container */

.controls-container{
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    width: 20%;
    background-color: var(--side-bg-color);
    color:white;
    box-sizing: border-box;

}

.controls-container .start{
    align-self: center;
    font-size: 2rem;
    font-weight: 500;
    width: 100%;
    height: 60%;
    text-align: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.controls-container .start #startGame{
    border: 1px solid white;
    border-radius: 10rem;
    width: 80%;
    height: 10rem;
    margin-left: auto;
    margin-right: auto;
    text-align: center;
    vertical-align: middle;
    line-height: 10rem;
    border-radius: 50%;
}

.controls-container .start #startGame:hover{
    background-color: rgba(255,255,255,1.0);
    color: var(--side-bg-color);
    font-weight: 600;

}
.controls-container .controls{
    
    margin-left: auto;
    margin-right: auto;
    width: 30%;
    text-align: center;
    margin-top: 5%;
    font-size: 2rem;    
    width: 90%;
}

.controls div{
    margin-bottom: 5%;
}


.controls .up:hover, #left:hover, #right:hover, .down:hover{
    cursor: pointer;
    font-weight: 600;
}    

.controls .up:hover, #left:hover, #right:hover, .down:hover i{
    color: green;
}
.controls .horizontal{
    display: flex;
    flex-direction: row;
    justify-content: space-evenly;
}


/* contorls container*/

/* media queries */

@media only screen and (max-width: 600px) {
    html{
        background: url('bg.jpg');
        object-fit: cover;
    }
    body{
        width: 100%;
        height: 90%;
    }

    .main-container{
        width: 95%;
        height: 90%;
        flex-direction: column;
    }

    body .main-container .result-container{
        height: 15%;
        display: flex;
        flex-direction: row;
        justify-content: space-around;
        width: 100%;        
        text-align: center;
        font-size: 1.5rem;
        align-items: center;
    }

    body .main-container .result-container div{
        flex:1;
        
    }

    .controls-container{
        display: flex;
        flex-direction: row;
        justify-content: space-evenly;
        width: 100%;
    }
    .controls-container .controls{
        width: 48%;
    }
    .controls-container .controls div{
        margin-bottom: 2%;
    }
    .controls-container .start #startGame{
        width: 60%;
        height: 8rem;
        line-height: 8rem;
    }

    .controls-container .start{
        width: 50%;
    }



    body .modal-div .modal-container{
        width: 80%;
        font-size: 2rem;
        left: 10%;
    }

  }
/* media queries */


@keyframes move__right {
    0% {
      width: 0%;
    }
    25% {
      width: 25%;
    }
    50% {
      width: 50%;
    }
    75% {
      width: 75%;
    }    
    100% {
        width: 100%;
    }
  }
@keyframes fill__out {
    0% {
      width: 100%;
    }
    25% {
      width: 75%;
    }
    50% {
      width: 50%;
    }
    75% {
      width: 25%;
    }    
    100% {
        width: 0%;
    }
  }


/* modal */
 .modal-div{
    display: block;
    visibility: hidden;
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: rgba(149, 175, 192,0.2);
    top: 0;
    left: 0;
    opacity: 0;
    transition: visibility 0s, opacity 0.5s ease-in-out;
    
}


 .modal-div .modal-container{
    position: absolute;
    top: 20%;
    height: 10%;
    left: 30%;
    width: 40%;
    border-radius: 1rem;
    background-color: rgba(235, 77, 75,1.0);
    font-size: 3rem;
    display: flex;
    flex-direction: column;
    justify-content: center;
    
}

 .modal-div .modal-container p{
    margin: 0;
    text-align: center;
    color: #fff;
}
/* modal */









Java Script Code:

//root variables
let gridSize=60;
const speedLevels=5;
const speedChanger = 1;
let speedStart = 80;
var gameSpeed = speedStart;
let speedLimit = 60;
var gameGrid = document.querySelector('.game-container');
let incDirRight=1;
let incDirDown=gridSize;
let incDirLeft=-1;
let incDirUp=-gridSize;
var moveTrain;
var gameStatus = 'stale';
var vid = document.getElementById("myVideo"); 

//root variables

//main

document.addEventListener('DOMContentLoaded',()=>{
    let favs = document.getElementsByTagName('i');    
    
    if (window.matchMedia("(max-width: 600px)").matches) {
        Array.from(favs).forEach(element => {
            element.classList.add('fa-lg');
        });
      } else {
        Array.from(favs).forEach(element => {
            element.classList.add('fa-2x');
        });
      }
});

createGrid(gridSize);
//numberTheGrids();
var startButton = document.querySelector('#startGame');
startButton.addEventListener('click',(event)=>{
    
    //stop the game
    if(event.currentTarget.textContent=='Stop'){
        event.currentTarget.textContent='Start';
        clearInterval(moveTrain);
        gameStatus='stale';
        bringModal(document.querySelector('#score__text').textContent,"Game Stopped!!!");

    }else{
        event.currentTarget.textContent='Stop';
        document.querySelector('#score__text').textContent=0;
        // document.querySelector('#speed__text').textContent=0;
        clearTheGrid();
        gameSpeed = speedStart;
        callGame();
        gameStatus='running';
    }
    
    
});



//main

// init functions

function numberTheGrids(){
    var tiles = document.getElementsByClassName('tile');
    Array.from(tiles).forEach(element => {
        element.childNodes[0].innerHTML = element.getAttribute('id').toString();
    });
}

function createGrid(rows){
    
    for (let i = 0; i < rows*rows; i++) {
        let divElement = document.createElement('div');
        divElement.className='tile';
        divElement.style.width=`calc(100% / ${gridSize})`;
        divElement.style.height=`calc(100% / ${gridSize})`;
        divElement.id=i.toString();
        //divElement.innerHTML='<span></span>';
        gameGrid.appendChild(divElement);
    }    
}

function clearTheGrid(){
    let allTiles = document.getElementsByClassName('tile');
    Array.from(allTiles).forEach(element => element.classList.remove('active'));
}



// init functions

//------------------------Game---------------------------------------

function callGame(){
    startGame();
}

function startGame(){

var startTile=0;
var tileIndex=startTile;
var tileIncrement = 1;
var trainArray = [startTile];
var direction = 'right';

//generate stations for the train
generateRandomStation();

async function moveTrainFunc() {  
    await ifCorner(tileIndex);
    tileIndex+=tileIncrement;
    if(await collided(tileIndex)){
        //game over
        // alert('game over');
        bringModal(document.querySelector('#score__text').textContent,'Collision!!!');
        clearInterval(moveTrain);
        gameStatus='stale';
        document.querySelector('#startGame').textContent='Start';
        return;
    };
    trainArray.push(tileIndex);    
    var isActive = await checkIfClassNameIsTitle(tileIndex);
    await addClassName(trainArray[trainArray.length-1]);
    await clearClassName(trainArray[0]);        
    if(isActive){
        await generateRandomStation();
        increaseScore();
    }
    else{
        trainArray.shift();
    }
    // tileIndex+=tileIncrement;   
    
    //if corner
    // await ifCorner(tileIndex);
}

moveTrain = setInterval(moveTrainFunc, gameSpeed);

async function clearClassName(index){
    let remtile = gameGrid.querySelector(`#${CSS.escape(index)}`);
    remtile.classList.remove('active');
}
async function addClassName(index){
    let remtile = gameGrid.querySelector(`#${CSS.escape(index)}`);
    remtile.classList.add('active');
}

async function checkIfClassNameIsTitle(index){
    let remtile = gameGrid.querySelector(`#${CSS.escape(index)}`);
    return remtile.classList.contains('active');
}

async function generateRandomStation(){

    var rNumber = Math.floor((Math.random())*(gridSize*gridSize));
    if(trainArray.includes(rNumber)){
        generateRandomStation();
    }
    else {
        let station = gameGrid.querySelector(`#${CSS.escape(rNumber)}`);
        station.classList.add('active');
    }
}

async function increaseScore(){
    console.log(gameSpeed);
    let presentScore=document.querySelector('#score__text');
    presentScore.textContent=parseInt(presentScore.textContent)+1;
    let x = presentScore.textContent;

    if (x==5){
        console.log(x);
        document.getElementById("overlay").style.display = "block";
        vid.style.display = "block";
        vid.play();
    }


    //increase speed
    // let fSfromHTML = await fetchSpeedLevelHTML();
    // if(fSfromHTML < (speedLevels)){
    //     if((presentScore.textContent)%speedChanger==0){
    //         increaseSpeed();
    //         increaseSpeedLevelHTML();
    //         clearInterval(moveTrain);
    //         moveTrain = setInterval(moveTrainFunc, gameSpeed);
    //     }
    // }
}


// async function fetchSpeedLevelHTML(){
//     return (document.querySelector('#speed__text').textContent);
// }
// async function increaseSpeedLevelHTML(){
//     let cP=  document.querySelector('#speed__text');
//     cP.textContent = parseInt(cP.textContent) +1;
// }

// async function increaseSpeed(){
//     let addSpeed = (speedStart-speedLimit)/speedLevels;
//     if(gameSpeed>speedLimit){
//         gameSpeed=gameSpeed-addSpeed;
//     }
// }

async function ifCorner(index){
    if (direction=='right' && (index+1)%gridSize==0) {
        tileIndex=index-gridSize;
    }
    else
    if (direction=='left' && (index)%gridSize==0) {
        tileIndex=index+gridSize;
    }else
    if (direction=='down' && (index)<(gridSize*gridSize) && (index)>=(gridSize*(gridSize-1))) {
        tileIndex=(index-(gridSize*(gridSize-1)))+(gridSize)*(-1);
    }else
    if (direction=='up' && (index)<gridSize) {
        tileIndex=(gridSize*gridSize)+(index);        
    }
}

async function collided(index){
    return trainArray.includes(index);
}

async function changeDirection(dir){
    if (dir=='right') {
        tileIncrement=1;
        direction=dir;
    }
    if (dir=='left') {
        tileIncrement=-1;
        direction=dir;
    }
    if (dir=='down') {
        direction=dir;
        tileIncrement=gridSize;
    }
    if (dir=='up') {
        direction=dir;
        tileIncrement=-gridSize;
    }
    
}

//event listener on controls
var controls = document.querySelector('.controls');
controls.addEventListener('click',(event)=>{
    try {
        if(gameStatus=='stale') return false;    
        let dir = event.target.getAttribute('id').toString();
        changeDirection(dir)
        direction=dir;
    } catch (error) {
        console.log("error from controls function: " + error);
        return false;
    }
});

//keystrokes
document.addEventListener('keydown',event=>{
    let map = {
        37:'left',
        38:'up',
        39:'right',
        40:'down'
    }
    if(map.hasOwnProperty(event.keyCode)){
        try {
            if(gameStatus=='stale') return false;                
            changeDirection(map[event.keyCode]);
            direction=map[event.keyCode];
        } catch (error) {
            console.log("error from controls function: " + error);
            return false;
        }
    }
    else{
        return false;

    }
});

//dirction change on mouse click
gameGrid.addEventListener('click', async function(event) {
    try {
        if(gameStatus=='stale') return false;             
        console.log(event.target.attributes);   
        let currID = event.target.getAttribute('id');
        let isInLine =await onClick__isInLine(currID);
        if(isInLine == 0){
            await onClick__changeDir(currID);
        }
    } catch (error) {
        console.log("error- mouse click: " + error);
        return false;
    }
});

async function onClick__isInLine(index){
    let quot = Math.floor(tileIndex/gridSize);
    //for left right
    if ((direction=='left' || direction=='right') && index != null) {
        try {
            let upperLimit = (quot+1) * (gridSize);
        let lowerLimit = quot * gridSize;
        if(index < upperLimit && index >= lowerLimit && index != null)
        {
            console.log("left-right: inline - ", index);
            return 1;
        }
        else{
            // console.log("not in line");
            return 0;
    }
        } catch (error) {
            return 2;
        }
    }else
    //for up down
    if ((direction=='up' || direction=='down') && index!=null) {
        try {
            if(index%gridSize==tileIndex%gridSize)
            {
                console.log("up-down: inline - ", index);
                return 1;
            }
            else
            return 0;
        } catch (error) {
            // console.log("UD: not in line");
            return 2;
        }        
    }

}

async function onClick__changeDir(clickedIndex){
    let mapOnClike ={
        right:['up','down'],
        left: ['up','down'],
        up:['left','right'],
        down:['left','right']        
    }
    // console.log("map right",mapOnClike['right']);
    if(direction == 'left' || direction=='right'){
        // console.log(clickedIndex,tileIndex,direction);
        if(clickedIndex < tileIndex){
            await changeDirection('up');
            direction='up';
        }
        else if(clickedIndex > tileIndex){
            await changeDirection('down');
            // console.log('from inside');
            direction='down';
        }
        return true;
    }
    if(direction == 'up' || direction=='down'){
        var mod = clickedIndex%gridSize;
        var modTile = tileIndex%gridSize;
        if(mod < modTile){
            await changeDirection('left');
            direction='left';
        }
        else if(mod > modTile){
            await changeDirection('right');
            direction='right';
        }
        return true;
    }
}


//closing bracket for function
}

//modal
async function bringModal(score,reason){
    let modaldiv = document.querySelector('.modal-div');
    modaldiv.style.visibility='visible';
    modaldiv.style.opacity='1';
    if(score!=null){
        document.querySelector('#modal__score').textContent = score;
        document.querySelector('#modal--over__text').textContent = reason;
    }else
    {
        document.querySelector('#modal__score').textContent = 0;
    }
    
    modaldiv.addEventListener('click',()=>{
        modaldiv.style.visibility='hidden';
        modaldiv.style.opacity='0';        
    })
}

//modal

//------------------------Game---------------------------------------










Videos:

Snake mp4:



Snakes.mp4:






<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1389870630580192"

     crossorigin="anonymous"></script>







Comments

Popular posts from this blog

Task Management

Todo List