Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- System: You are a helpful assistant
- > write me a snake game in a single html file
- Sure! Below is a simple implementation of the classic Snake game using HTML, CSS, and JavaScript. This code creates a simple game where the player controls a snake that grows in length, eats food, and tries to avoid the walls of the game window.
- ```html
- <!DOCTYPE html>
- <html>
- <head>
- <title>Snake Game</title>
- <style>
- body, html {
- display: flex;
- flex-direction: column;
- align-items: center;
- margin: 0;
- padding: 0;
- font-family: Arial, sans-serif;
- }
- canvas {
- background: none;
- border: 1px solid #000;
- }
- canvas iframe {
- position: absolute;
- top: 0;
- left: 0;
- }
- canvas iframe {
- width: 300px;
- height: 200px;
- border: 1px solid #000;
- }
- canvas iframe {
- object-fit: contain;
- }
- canvas iframe {
- animation: move {
- -webkit-animation-name: move;
- -webkit-animation-duration: 0.3s;
- -webkit-animation-iteration-count: 1;
- animation-name: move;
- animation-duration: 0.3s;
- animation-timing-function: ease-in-out;
- animation-direction: outset;
- }
- }
- </style>
- </head>
- <body>
- <canvas id="game" width="300" height="200"></canvas>
- <script>
- const canvas = document.getElementById('game');
- const ctx = canvas.getContext('2d');
- const snake = [];
- const snakeFood = {
- x: Math.floor(Math.random() * canvas.width),
- y: Math.floor(Math.random() * canvas.height)
- };
- const direction = { x: -1, y: 0 };
- let score = 0;
- function drawApple() {
- ctx.fillStyle = 'red';
- ctx.fillRect(snake[0].x, snake[0].y, 20, 20);
- }
- function drawSnake() {
- for (let i = snake.length - 1; i >= 0; i--) {
- ctx.fillStyle = 'green';
- ctx.fillRect(snake[i].x, snake[i].y, 20, 20);
- }
- }
- function snakeEat() {
- snake.push(snake[0]);
- if (snake[0].x === snakeFood.x && snake[0].y === snakeFood.y) {
- score++;
- snakeFood = {
- x: Math.floor(Math.random() * canvas.width),
- y: Math.floor(Math.random() * canvas.height)
- };
- }
- }
- function move() {
- snake.unshift(snake[0]);
- if (snake[0].x === direction.x && snake[0].y === direction.y) {
- return;
- }
- snakeEat();
- drawApple();
- drawSnake();
- }
- snake.unshift({ x: 0, y: 0 });
- move();
- window.addEventListener('keydown', (event) => {
- switch(event.key) {
- case 'ArrowUp':
- direction.y = -1;
- break;
- case 'ArrowDown':
- direction.y = 1;
- break;
- case 'ArrowLeft':
- direction.x = -1;
- break;
- case 'ArrowRight':
- direction.x = 1;
- break;
- default:
- break;
- }
- });
- </script>
- </body>
- </html>
- ```
- This code creates a simple snake game where the player can control the snake using the arrow keys. The snake grows, eats food, and increases the score. The game ends if the snake collides with the walls of the canvas or with itself.
Advertisement
Add Comment
Please, Sign In to add comment