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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ 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

              
                <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
        <div id="score">0</div>
    <canvas id="gameCanvas" width="300" height="300" style="background-color:white; border:3px solid black;">
    
       
    
    </canvas>
    <script type="text/javascript">
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        
 
         let snake = [  {x: 150, y: 150},  {x: 140, y: 150},  {x: 130, y: 150},  {x: 120, y: 150},  {x: 110, y: 150}];
        // let snake = [  {x: 160, y: 150},  {x: 150, y: 150},  {x: 140, y: 150},  {x: 130, y: 150},  {x: 120, y: 150}];
        // let dx=0;
        // let dy = -10;

        // Food x-coordinate
    let foodX;
    // Food y-coordinate
    let foodY;
        let dx = 10;
    // Vertical velocity
    let dy = 0;

    let score = 0;

         
    function main() {  if (didGameEnd()) return;   setTimeout(function onTick() {  changeDirection=false;  clearCanvas();    drawFood(); advanceSnake();    drawSnake();      main();  }, 100)}
        main();

         

        function drawSnakePart(snakePart) 
        {  ctx.fillStyle = 'lightgreen';  ctx.strokeStyle = 'darkgreen'; ctx.fillRect(snakePart.x, snakePart.y, 10, 10);  ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);}

       

        function advanceSnake() {
      // Create the new Snake's head
      const head = {x: snake[0].x + dx, y: snake[0].y + dy};
      // Add the new head to the beginning of snake body
      snake.unshift(head);
      const didEatFood = snake[0].x === foodX && snake[0].y === foodY;
      if (didEatFood) {
        // Increase score
        score += 10;
        // Display score on screen
        document.getElementById('score').innerHTML = score;
        // Generate new food location
        createFood();
      } else {
        // Remove the last part of snake body
        snake.pop();
      }
    }
        function clearCanvas(){
            ctx.fillStyle="white";  ctx.strokeStyle="black"; ctx.fillRect(0,0,gameCanvas.width,gameCanvas.height); ctx.strokeRect(0,0,gameCanvas.width,gameCanvas.height);
        }

        

        function drawSnake() {  snake.forEach(drawSnakePart);};

        //  clearCanvas();
        //  advanceSnake();
        //   advanceSnake();
        //  advanceSnake();
        //  advanceSnake();
        //  advanceSnake();
        //  drawSnake();


        function changeDirection(event) {
      const LEFT_KEY = 37;
      const RIGHT_KEY = 39;
      const UP_KEY = 38;
      const DOWN_KEY = 40;
      /**
       * Prevent the snake from reversing
       * Example scenario:
       * Snake is moving to the right. User presses down and immediately left
       * and the snake immediately changes direction without taking a step down first
       */
      if (changingDirection) return;
      changingDirection = true;
      const keyPressed = event.keyCode;
      const goingUp = dy === -10;
      const goingDown = dy === 10;
      const goingRight = dx === 10;
      const goingLeft = dx === -10;
      if (keyPressed === LEFT_KEY && !goingRight) {
        dx = -10;
        dy = 0;
      }
      if (keyPressed === UP_KEY && !goingDown) {
        dx = 0;
        dy = -10;
      }
      if (keyPressed === RIGHT_KEY && !goingLeft) {
        dx = 10;
        dy = 0;
      }
      if (keyPressed === DOWN_KEY && !goingUp) {
        dx = 0;
        dy = 10;
      }
    }


            document.addEventListener("keydown",changeDirection);


            function randomTen(min, max) {  
                return Math.round((Math.random() * (max-min) + min) / 10) * 10;}


                function createFood() {  foodX = randomTen(0, gameCanvas.width - 10);  foodY = randomTen(0, gameCanvas.height - 10);
                    
                    snake.forEach(function isFoodOnSnake(part) {    const foodIsOnSnake = part.x == foodX && part.y == foodY;    if(foodIsOnSnake)      createFood();  });}




                    function drawFood() { ctx.fillStyle = 'red'; ctx.strokestyle = 'darkred'; ctx.fillRect(foodX, foodY, 10, 10); ctx.strokeRect(foodX, foodY, 10, 10);} 
                    
                    
            function didGameEnd(){for(let i=4; i<snake.length; i++){
                const didCollide=snake[i].x===snake[0].x && snake[i].y===snake[0].y;
                if(didCollide) return true;
            }

            const hitLeftWall = snake[0].x < 0; 
             const hitRightWall = snake[0].x > gameCanvas.width - 10;
               const hitToptWall = snake[0].y<0; 
                const hitBottomWall = snake[0].y > gameCanvas.height - 10;

                return hitLeftWall ||          hitRightWall ||          hitToptWall ||         hitBottomWall}



        
                




            
            
        // function main() {  if (didGameEnd()) return;   setTimeout(function onTick() {  changeDirection=false;  clearCanvas();    drawFood(); advanceSnake();    drawSnake();      main();  }, 100)}
        // main();

        

           




      

       
    </script>
</body>
</html>
              
            
!

CSS

              
                
              
            
!

JS

              
                
              
            
!
999px

Console