Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

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.

+ 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

Auto Save

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>
<head>
    <title>JavaScript Snake Game</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <canvas id="canvas" width="500" height="400"></canvas>
    <script src="script.js"></script>
</body>
</html>

              
            
!

CSS

              
                #canvas {
    border: 1px solid black;
    margin: 0 auto;
    display: block;
}

              
            
!

JS

              
                // Set up the canvas and score display
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;


// Set up the snake and score
let snake = [{x: 10, y: 10}];
let dx = 10;
let dy = 0;
let food = getRandomFood();
let score = 0;

// Set up the game loop
setInterval(gameLoop, 100);

function gameLoop() {
    clearCanvas();
    moveSnake();
    drawSnake();
    drawFood();
    checkCollision();
    drawScore();
}

function clearCanvas() {
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, canvasWidth, canvasHeight);
}

function drawScore() {
    ctx.fillStyle = 'black';
    ctx.font = '20px Arial';
    ctx.fillText('Score: ' + score, 10, 30);
}

function moveSnake() {
    const head = {x: snake[0].x + dx, y: snake[0].y + dy};
    snake.unshift(head);
    if (!ateFood()) {
        snake.pop();
    } else {
        food = getRandomFood();
        score++;
    }
}

function drawSnake() {
    ctx.fillStyle = 'green';
    snake.forEach((segment) => {
        ctx.fillRect(segment.x, segment.y, 10, 10);
    });
}

function drawFood() {
    ctx.fillStyle = 'red';
    ctx.fillRect(food.x, food.y, 10, 10);
}

function getRandomFood() {
    return {
        x: Math.floor(Math.random() * (canvasWidth / 10)) * 10,
        y: Math.floor(Math.random() * (canvasHeight / 10)) * 10
    }
}

function ateFood() {
    return snake[0].x === food.x && snake[0].y === food.y;
}

function checkCollision() {
    // Check if snake hits the wall
    if (snake[0].x < 0 || snake[0].x >= canvasWidth || snake[0].y < 0 || snake[0].y >= canvasHeight) {
        resetGame();
    }
    
    // Check if snake hits itself
    for (let i = 1; i < snake.length; i++) {
        if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) {
            resetGame();
        }
    }
}


function resetGame() {
    // Reset snake and food positions
    snake = [{x: 10, y: 10}];
    dx = 10;
    dy = 0;
    food = getRandomFood();

    // Display game over message
    console.log('Game over! Your score is ' + score);

    // Refresh the page
    location.reload();
}

// Handle user input
document.addEventListener('keydown', (event) => {
    if (event.keyCode === 65 && dx === 0) {
        dx = -10;
        dy = 0;
    } else if (event.keyCode === 87 && dy === 0) {
        dx = 0;
        dy = -10;
    } else if (event.keyCode === 68 && dx === 0) {
        dx = 10;
        dy = 0;
    } else if (event.keyCode === 83 && dy === 0) {
        dx = 0;
        dy = 10;
    }
});



              
            
!
999px

Console