Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· OpenAIAi2 WildChat-4.8M (AI2)

Напиши код игры на джава скрипт на подобии гугл динозаврика

  1. User

    Напиши код игры на джава скрипт на подобии гугл динозаврика

  2. Assistant

    Создать игру, подобную Google Chrome Dino Game, представляет собой достаточно обширный проект, поэтому я предоставлю упрощенную версию игры на JavaScript. Игра будет использовать HTML5 Canvas для отрисовки и интерпретации очень базовых элементов игры: игрока (динозаврика), препятствия и землю. Ниже приведен пример кода, который можно развивать и улучшать.

    HTML файл (index.html):

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dino Game</title>
    <style>
        canvas {
            border: 2px solid black;
            display: block;
            margin: auto;
        }
    </style>
    </head>
    <body>
    <canvas id="gameCanvas" width="800" height="200"></canvas>
    <script src="game.js"></script>
    </body>
    </html>
    

    JavaScript файл (game.js):

    const canvas = document.getElementById("gameCanvas");
    const ctx = canvas.getContext("2d");
    
    const dino = {
        x: 10,
        y: 140,
        width: 40,
        height: 40,
        jumping: false,
        velocity: 0
    };
    
    const gravity = 1;
    const obstacles = [];
    const obstacleWidth = 20;
    const obstacleHeight = 40;
    const jumpHeight = -15;
    let score = 0;
    let gameSpeed = 3;
    
    function addObstacle() {
        obstacles.push({
            x: canvas.width,
            y: canvas.height - obstacleHeight,
            width: obstacleWidth,
            height: obstacleHeight
        });
    }
    
    function update() {
        // Очистка холста
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // Рисование динозаврика
        ctx.fillStyle = "green";
        ctx.fillRect(dino.x, dino.y, dino.width, dino.height);
    
        // Движение динозаврика
        if (dino.jumping) {
            dino.y += dino.velocity;
            dino.velocity += gravity;
            if (dino.y > 140) {
                dino.jumping = false;
                dino.y = 140;
                dino.velocity = 0;
            }
        }
    
        // Рисование препятствий
        ctx.fillStyle = "red";
        obstacles.forEach((obstacle, index) => {
            obstacle.x -= gameSpeed;
            ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
            
            // Проверяем столкновения
            if (dino.x < obstacle.x + obstacle.width &&
                dino.x + dino.width > obstacle.x &&
                dino.y < obstacle.y + obstacle.height &&
                dino.y + dino.height > obstacle.y) {
                ctx.font = "30px Arial";
                ctx.fillText("Game Over!", 150, 90);
                return;
            }
    
            // Удаляем препятствия, которые вышли за пределы экрана
            if(obstacle.x + obstacle.width < 0) {
                obstacles.splice(index, 1);
                score++;
            }
        });
    
        // Рисование земли
        ctx.fillStyle = "black";
        ctx.fillRect(0, canvas.height - 10, canvas.width, 10);
        
        // Счет игры
        ctx.font = "20px Arial";
        ctx.fillStyle = "black";
        ctx.fillText("Score: " + score, canvas.width - 120, 30);
        
        // Добавляем препятствия
        if (score % 10 === 0) {
            addObstacle();
        }
        
        // Запрос на следующий кадр игры
        requestAnimationFrame(update);
    }
    
    // Отслеживаем нажатие клавиш для прыжка
    document.addEventListener("keydown", function(e) {
        if (e.code === "Space" && !dino.jumping) {
            dino.jumping = true;
            dino.velocity = jumpHeight;
        }
    });
    
    // Старт игры
    addObstacle();
    update();
    

    Этот код создает игру, где динозаврик должен прыгать через приближающиеся препятствия. Клавиша "пробел" используется для того, чтобы заставить динозаврика прыгнуть. Счет увеличивается на одно очко каждый раз, когда препятствие уходит за левый край экрана. Игра заканчивается при столкновении с препятствием, и отображается сообщение "Game Over". Игра получилась очень базовой и её можно усовершенствовать, добавив анимацию, звук и более сложные элементы управления и геймплея.