Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

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.

+ add another resource

Packages

Add Packages

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.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="pause">Pause</div>

    <div id="myConfirm">
        <div class="main">
            <div class="main-text">
                <div class="head-text">
                    <h4 class="header">Play again?</h4>
                </div>
                <div class="desc-text">
                    <input id="agree" type="button" value="PLAY">
                    <input id="desagree" type="button" value="EXIT">
                </div>
            </div>
        </div>
    </div>

    <div id="mainBlock">
        <input id="playBtn" type="button" value="PLAY">
        <div id="snakeBlock"></div>
        <div id="appleBlock"></div>
    </div>
  
    <div class="scoreBlock">
        Score:
        <span id="score">0</span>
    </div>
              
            
!

CSS

              
                * {
    overflow: hidden;
    outline: none;
    margin: 0;
    padding: 0;
    font-family: arial, sans-serif;
    font-size: 16px;
    text-align: center;
    color: #333;
}
h1 {
    font-family: comic sans ms;
    font-size: 48px;
    margin-top: 25px;
}
#mainBlock {
    height: 500px;
    width: 500px;
    background: #fff;
    outline: 2px solid #000;
    box-shadow: 1px 3px 36px 5px rgba(0,0,0,0.3);
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
#playBtn {
    position: absolute;
    width: 200px;
    height: 50px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-weight: bold;
    border: 1px solid #000;
    border-radius: 3px;
    background: #f7f7f7;
    transition: all .3s ease 0s;
}
#playBtn:hover {
    border: 1px solid #000;
    background: #e9e9e9;
    cursor: pointer;
}
#appleBlock {
    display: none;
    height: 20px;
    width: 20px;
    background: red;
    position: absolute;
}
#snakeBlock,
.snakeBlock {
    display: none;
    height: 20px;
    width: 20px;
    background: green;
    position: absolute;
}
#myConfirm {
    position: absolute;
    display: none;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 9;
}
.main {
    position: absolute;
    height: auto;
    width: 350px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    align-items: center;
    justify-content: center;
    background: #e9e9e9;
    padding: 50px 0 50px 0;
    border-radius: 10px;
    box-shadow: 0 0 30px rgba(0,0,0,0.3);
}
.header {
    font-size: 24px;
    margin-bottom: 20px;
}
#agree,
#desagree {
    width: 100px;
    height: 40px;
    margin: 0 5px;
    font-weight: bold;
    border: 1px solid #000;
    border-radius: 3px;
    background: #f7f7f7;
    transition: all .3s ease 0s;
}
#agree:hover,
#desagree:hover {
    border: 1px solid #000;
    background: #e9e9e9;
    cursor: pointer;
}
.scoreBlock {
    display: none;
    position: absolute;
    top: 86%;
    left: 34%;
    font-size: 24px;
}
#score {
    font-size: 24px;
    color: red;
    font-weight: bold;
}

.pause {
    position: absolute;
    top: 0;
    left: 0;
    display: none;
    justify-content: center;
    align-items: center;
    background: rgba(0,0,0,0.5);
    width: 100%;
    height: 100%;
    font-size: 48px;
    text-transform: uppercase;
    color: #fff;
    z-index: 999;
}
              
            
!

JS

              
                var mainBlock = document.getElementById("mainBlock"), // Игровая область
    snakeBlock = document.getElementById("snakeBlock"), // Голова змейки
    snakeBody = document.getElementsByClassName("snakeBlock"), // Тело змейки
    appleBlock = document.getElementById("appleBlock"), // Область яблока
    scoreBlock = document.getElementsByClassName("scoreBlock")[0], // Блок очков
    score = document.getElementById("score"), // Набранные очки
    scoreValue = Number(score.innerHTML), // Отображение набранных очков
    playBtn = document.getElementById("playBtn"), // Кнопка PLAY
    myConfirm = document.getElementById("myConfirm"), // Свое окно Confirm
    okeyBtn = document.getElementById("agree"), // Кнопка OK(PLAY в confirm)
    exitBtn = document.getElementById("desagree"), // Кнопка EXIT
    exitBtn = document.getElementById("desagree"), // Кнопка EXIT
    pauseBlock = document.getElementsByClassName("pause")[0], // Блок паузы
    snakeX = mainBlock.offsetWidth / 2 - 10, // Начальные координаты головы змейки по X, центр
    snakeY = mainBlock.offsetHeight / 2 - 10, // Начальные координаты головы змейки по Y, центр
    snakePrevX, snakePrevY,// Предыдущие координаты головы змейки по X/Y
    tailPrevX, tailPrevY,// Предыдущие координаты хвоста змейки по X/Y
    appleX, appleY, // Координаты яблока по X/Y(зададим позже)
    t, // Переменная для будущей установки/сброса setInterval, который в свою очередь запускает движение змейки
    activeGame = false, // Активность игры(не запущена по умолчанию)
    spaceActive = false, // Активность пробела
    activeDir, // Переменная для отслеживания направления и запрета двигатся в противоположную сторону, true - если кубик двигается вверх/вниз, false - если влево/вправо
    eatCost = 10, // Цена одного яблока
    maxX = mainBlock.clientWidth - 20, // 20px - ширина головы змейки
    maxY = mainBlock.clientHeight - 20; // 20px - высота головы змейки

// Ф-ция удаления элементов тела змейки
function delBody() {
    while(snakeBody.length > 0){
        snakeBody[0].parentNode.removeChild(snakeBody[0]);
    }
}

// Ф-ция удаления элементов тела змейки при столкновении ее головы с телом 
function delBodyDest() {
    if (snakeBody.length > 0) {
        tailPrevX = snakeBody[snakeBody.length - 1].style.left;
        tailPrevY = snakeBody[snakeBody.length - 1].style.top;
    }
    for (var i = 0; i < snakeBody.length; i++) {
        if(snakeBlock.style.top == snakeBody[i].style.top && snakeBlock.style.left == snakeBody[i].style.left){
            delBody();
            myConfirmDisplay();
        }
    } 
}

function moveUp() {
    if (snakeY > 0) {
        snakePrevX = snakeX;
        snakePrevY = snakeY;
        delBodyDest();
        snakeY -= 20;
        snakeBlock.style.top = snakeY + "px";
        eat();
        bodyMove();
    } else {
        delBody();
        myConfirmDisplay();
    }
}

function moveDown() {
    if (snakeY < maxY) {
        snakePrevX = snakeX;
        snakePrevY = snakeY;
        delBodyDest();
        snakeY += 20;
        snakeBlock.style.top = snakeY + "px";
        eat();
        bodyMove(); 
    } else {
        delBody();
        myConfirmDisplay();
    }
}

function moveLeft() {
    if (snakeX > 0) {
        snakePrevX = snakeX;
        snakePrevY = snakeY;
        delBodyDest();
        snakeX -= 20;
        snakeBlock.style.left = snakeX + "px";
        eat();
        bodyMove();
    } else {
        delBody();
        myConfirmDisplay();
    }
}

function moveRight() {
    if (snakeX < maxX) {
        snakePrevX = snakeX;
        snakePrevY = snakeY;
        delBodyDest();
        snakeX += 20;
        snakeBlock.style.left = snakeX + "px";
        eat();
        bodyMove();
    } else {
        delBody();
        myConfirmDisplay();
    }
}

playBtn.addEventListener('click', startGame);

// Pause
window.addEventListener('keydown', function (e) {
    if (e.keyCode == 32 && spaceActive == false) {
        activeGame = false;
        clearInterval(t);
        pauseBlock.style.display = 'flex';
        spaceActive = true;
    } else if (e.keyCode == 32 && spaceActive == true){
        activeGame = true;
        pauseBlock.style.display = 'none';
        spaceActive = false;
    }
});

window.addEventListener('keydown', function (e) {
    if (e.keyCode == 37 && activeDir !== false && activeGame == true) {
        clearInterval(t);
        t = setInterval(moveLeft, 70);
        activeDir = false;
    }
    else if (e.keyCode == 38 && activeDir !== true && activeGame == true) {
        clearInterval(t);
        t = setInterval(moveUp, 70);
        activeDir = true;
    }
    else if (e.keyCode == 39 && activeDir !== false && activeGame == true) {
        clearInterval(t);
        t = setInterval(moveRight, 70);
        activeDir = false;
    }
    else if (e.keyCode == 40 && activeDir !== true && activeGame == true) {
        clearInterval(t);
        t = setInterval(moveDown, 70);
        activeDir = true;
    }
});

function startGame() {

    resetParams();
    createEat();

    activeGame = true;
    
    playBtn.style.display = 'none'; // Скрытие кнопки PLAY
    snakeBlock.style.display = 'block'; // Отображение змейки
    scoreBlock.style.display = 'block'; // Отображение очков
}

function resetParams() {
    activeDir = '';
    spaceActive = false;
    snakeX = mainBlock.offsetWidth/2 - 10,
    snakeY = mainBlock.offsetHeight/2 - 10,
    snakeBlock.style.top = snakeY + 'px';
    snakeBlock.style.left = snakeX + 'px';
    delBody();
    if (t !== undefined){
        clearInterval(t);
    }
}

function myConfirmDisplay(){
    activeGame = false;
    resetParams();
    myConfirm.style.display = 'flex';
    snakeBlock.style.display = 'none'; // Скрытие змейки
    appleBlock.style.display = 'none'; // Скрытие яблока
    delBody();
    okeyBtn.addEventListener('click', function(){
        startGame();
        myConfirm.style.display = 'none';
        score.innerHTML = 0;
        scoreValue = Number(score.innerHTML);
    });
    exitBtn.addEventListener('click', function(){
        playBtn.style.display = 'block'; // Отображение кнопки PLAY
        scoreBlock.style.display = 'none'; // Скрытие очков
        myConfirm.style.display = 'none'; // Скрытие окна выбора
        score.innerHTML = 0;
        scoreValue = Number(score.innerHTML);
    });
    window.addEventListener('keydown', function (e) {
        if (e.keyCode == 13 && activeGame == false) {
            startGame();
            myConfirm.style.display = 'none';
            score.innerHTML = 0;
            scoreValue = Number(score.innerHTML);
        } else if (e.keyCode == 27 && activeGame == false) {
            playBtn.style.display = 'block'; // Отображение кнопки PLAY
            scoreBlock.style.display = 'none'; // Скрытие очков
            myConfirm.style.display = 'none'; // Скрытие окна выбора
            score.innerHTML = 0;
            scoreValue = Number(score.innerHTML);
        }
    });
}

function createEat(){
    appleBlock.style.display = 'block';
    appleX = Math.floor(Math.floor(Math.random()*(480 + 1)) / 20) * 20;
    appleY = Math.floor(Math.floor(Math.random()*(480 + 1)) / 20) * 20; // Координаты яблока(промежуток от 0 до 500(ширина и высота игровой области))
    appleBlock.style.top = appleY + 'px';
    appleBlock.style.left = appleX + 'px';
}

function eat() {
    if(snakeX == appleX && snakeY == appleY){
        var div = document.createElement('div');
        div.className = "snakeBlock";
        mainBlock.appendChild(div);
        snakeBody = document.getElementsByClassName("snakeBlock"); // Змейка(белый квадрат)
        for(var i = 0; i < snakeBody.length; i++) {
            snakeBody[i].style.display = 'block'; // Отображение змейки
        }
        for(var i = 0; i < snakeBody.length; i++){
            if(i > 0){
                snakeBody[snakeBody.length - 1].style.left = tailPrevX;
                snakeBody[snakeBody.length - 1].style.top = tailPrevY;
            } else {
                snakeBody[i].style.left = snakePrevX + 'px';
                snakeBody[i].style.top = snakePrevY + 'px';
            }
        }
        scoreValue += eatCost;
        score.innerHTML = scoreValue;
        appleBlock.style.display = 'none';
        createEat();
    }
}

function bodyMove(){
    snakeBody = document.getElementsByClassName("snakeBlock"); // Змейка(белый квадрат)
    for(var i = 0; i < snakeBody.length; i++){
        if(i > 0){
            snakeBody[i - 1].style.top = snakeBody[i].style.top;
            snakeBody[i - 1].style.left = snakeBody[i].style.left;
        }
        snakeBody[i].style.left = snakePrevX + 'px';
        snakeBody[i].style.top = snakePrevY + 'px';
    }
}
              
            
!
999px

Console