<script type="text/javascript">

// Variables to use in the game
var score=0; 
var lives=3; 

// Game Objects
function Enemy(x,y,speed){
    this.x = x;
    this.y = y;
    this.speed = speed;
    this.sprite = 'images/enemy-bug.png';
}

// Update the enemy's position
Enemy.prototype.update = function(dt) {
    this.x += this.speed * dt;
    if (this.x > 500) {
        this.x = -100;
        this.speed = 100 + Math.floor(Math.random() * 500);
    }

    // Collision detection
    if (player.x < this.x + 50 &&
        player.x + 50 > this.x &&
        player.y < this.y + 50 &&
        50 + player.y > this.y) {
        lives--;
        if(lives === 0){
            alert('Game Over!');
            document.location.reload();
        }
        player.x = 200;
        player.y = 400;
    }
};

// Draw the enemy on the screen
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

// Player 
function Player(x,y){
    this.x = x;
    this.y = y;
    this.sprite = 'images/char-boy.png';
}

// Update the players position
Player.prototype.update = function(){
    if (this.y > 380 ) {
        this.y = 380;
    }

    if (this.x > 400 ) {
        this.x = 400;
    }

    if (this.x < 0) {
        this.x = 0;
    }

    // Win the game
    if (this.y < 0) {
        this.x = 200;
        this.y = 380;
        score++;
        lives++;
        alert('You Won!');
    }
};

// Draw the player on the screen
Player.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

// Handle input from the player
Player.prototype.handleInput = function(keyPress) {
    switch (keyPress) {
        case 'left':
            this.x -= 100;
            break;
        case 'up':
            this.y -= 80;
            break;
        case 'right':
            this.x += 100;
            break;
        case 'down':
            this.y += 80;
            break;
    }
};

// Instantiate objects
var allEnemies = [];

// Place all enemy objects in an array called allEnemies
// Place the player object in a variable called player
var enemyPosition = [60, 140, 220];
var player = new Player(200, 400);
var enemy;

enemyPosition.forEach(function(posY) {
    enemy = new Enemy(0, posY, 100 + Math.floor(Math.random() * 500));
    allEnemies.push(enemy);
});

// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener('keyup', function(e) {
    var allowedKeys = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down'
    };

    player.handleInput(allowedKeys[e.keyCode]);
});

</script>
HTML Game: Avoid the Bugs and Reach the Top!

原文地址: https://www.cveoy.top/t/topic/lmbj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录