📜  使用 JavaScript 的电晕战斗机游戏

📅  最后修改于: 2021-08-31 07:18:24             🧑  作者: Mango

在本文中,我们将使用 HTML、CSS 和 JavaScript 创建一个 Covid 格斗游戏。在这个游戏中,我们将创建三个对象,第一个对象将代表用户,他们必须跨越几个障碍才能到达最终对象。

方法:我们将首先创建 HTML 布局,使用 CSS 对其进行样式设置,然后在 JavaScript 中编写逻辑。在我们的游戏中,第一个物体代表地球,第二个物体代表冠状病毒,第三个物体代表疫苗。

HTML 代码:我们将使用 HTML 来设计网页结构或布局。创建 ID 为“mycanvas”的 HTML 画布。在 HTML 代码中包含 JavaScript 文件“covid.js”。

HTML


  

      

COVID-19 Fighter Game

                


JavaScript
function load_assets(){
  
    // Enemy object
    enemy_img = new Image();
    enemy_img.src = "Assets/enemy.png";
      
    // Main user
    player_img = new Image();
    player_img.src = "Assets/fighter.png";
      
    // Vaccine
    gem_img = new Image;
    gem_img.src = "Assets/vac.gif";
      
    // Winning sound
    win = new Audio();
    win.src = "Audio/won.wav";
      
    // Losing sound
    lose = new Audio();
    lose.src = "Audio/dead.mp3";
}


JavaScript
function init(){
    cvs = document.getElementById('mycanvas');
  
    // Setting the height and width of canvas
    W = cvs.width = 1252;
    H = cvs.height = 516;
  
    // Getting the context the of canvas
    pen = cvs.getContext('2d');
  
    // Initially setting the variable to false
    game_over = false;
  
    // Creating the enemies object with
    // coordinates x y width(w) height(h)
    // and speed  
  
    e1 = {
        x:200,
        y:50,
        w:80,
        h:80,
        speed:20,
    };
     e2 = {
        x:450,
        y:150,
        w:80,
        h:80,
        speed:35,
    };    
     
     e3 = {
        x:700,
        y:300,
        w:80,
        h:80,
        speed:40,
    };
    e4 = {
        x:900,
        y:100,
        w:80,
        h:80,
        speed:30,
    };
      
    // Array of enemies
    enemy = [e1, e2, e3, e4];
      
    // Creating the player object
    player = {
        x:20,
        y:H/2,
        w:110,
        h:110,
        speed:30,
        health:100,
        moving: "false"
    }
    // Creating the vaccine gem
    gem = {
        x:W-150,
        y:H/2,
        w:150,
        h:150,
    }
  
    // The main part lets move the player
    // using event mouse down and stop 
    //using mouse up
    cvs.addEventListener('mousedown', function(){
        console.log("Mouse Pressed"); 
        player.moving = true;
    });
    cvs.addEventListener('mouseup', function(){
        console.log("Mouse Released"); 
        player.moving = false;
    });
}


JavaScript
function isOverlap(rect1, rect2) {
    if (rect1.x < rect2.x + rect2.w &&
        rect1.x + rect1.w > rect2.x &&
        rect1.y < rect2.y + rect2.h &&
        rect1.y + rect1.h > rect2.y) {
            return true;
    }
    return false;
}


JavaScript
function draw() {
  
    // Drawing the images
    for(let i = 0; i < enemy.length; i++) {
        pen.drawImage(enemy_img, enemy[i].x, 
          enemy[i].y, enemy[i].w, enemy[i].h);
    }
  
    // Draw the player
    pen.drawImage(player_img, player.x, 
        player.y, player.w, player.h);
  
    // Draw the vaccine
    pen.drawImage(gem_img, gem.x, 
        gem.y, gem.w, gem.h);
  
    // Displaying score
    pen.fillStyle = "white";
    pen.font = "30px Roboto";
    pen.fillText("Score " + 
        player.health, 30, 30);
}


JavaScript
function update() {
  
    // If player is moving
    if(game_over){
        return;
    }
    if(player.moving == true){
        player.x += player.speed;
        player.health += 20;
    }
  
    // Checking collision of player
    // with all enemies
    for(let i = 0; i < enemy.length; i++){
        if(isOverlap(enemy[i], player)){
            lose.play();
            player.health -= 50;
            if(player.health < 0){
                draw();
                lose.play();
                alert("You Lose ");
                game_over = true;
                return;
            }
        }
    }
  
    // checking the player and vaccine
    // collision for the win.
    if(isOverlap(player, gem)){
        win.play();
        alert("You Won " + player.health);
        game_over = true;
        return;
    }
  
    // Adjusting the speed and positions
    // of enemy
    for(let i = 0; i H-enemy[i].h || enemy[i].y <= 0){
            enemy[i].speed *= -1;
        }
    }
}


JavaScript
function gameloop(){
    if(game_over){
        clearInterval(f);
    }
    draw();
    update();
}


JavaScript
load_assets();
init();
var f = setInterval(gameloop, 100);


CSS 代码: CSS 用于提供一般样式并使其更具视觉吸引力。为整个页面提供一般样式,如颜色、对齐方式和背景颜色。我们使用flex将画布居中,并将背景图像设置为我们游戏的背景。在上面的 HTML 代码中,在代码头部样式部分包含以下内容。

body {
    text-align: center;
    color: #ffff;
    background: #000;
}
#mycanvas{
    display: flex;
    align-items: center;
    justify-content: center;
    background-image: url(Assets/bg.gif)
    background-size: cover;
}

输出: HTML 布局和 CSS 样式的结果如下所示。

结果输出看起来不像所需的输出,但我们将使用 JavaScript 调整画布的高度和宽度。

逻辑:主要逻辑部分使用 JavaScript 实现。

  • 根据我们的逻辑,当地球物体与冠状病毒(第二个物体)碰撞时,我们会降低玩家 50 点的生命值。
  • 玩家的初始生命值为 100。
  • 当玩家的生命值 <= 0 时,我们的游戏就会结束。
  • 当玩家到达第三个对象时,玩家获胜。
  • 我们的游戏基本上分为基本的六大功能。
function load_assets(){
}
function init(){
}
function isOverlap(rect1, rect2){
}
function draw(){
}
function update(){
}
function gameloop(){
}

步骤1:

  • 最初,我们将加载所有必需的资产。我们将需要一个敌人,一个玩家,获胜的声音,失败的声音和第三个对象,即疫苗。
  • 我们将创建函数load_assets()它将加载所有必需的资产。

JavaScript

function load_assets(){
  
    // Enemy object
    enemy_img = new Image();
    enemy_img.src = "Assets/enemy.png";
      
    // Main user
    player_img = new Image();
    player_img.src = "Assets/fighter.png";
      
    // Vaccine
    gem_img = new Image;
    gem_img.src = "Assets/vac.gif";
      
    // Winning sound
    win = new Audio();
    win.src = "Audio/won.wav";
      
    // Losing sound
    lose = new Audio();
    lose.src = "Audio/dead.mp3";
}

第2步:

  • 在这一步中,我们将初始化我们的游戏状态。我们将设置画布的高度和宽度。
  • 我们还将设置第二个对象的数量。我们将通过设置他们的一般位置、速度、高度和宽度来创建五个敌人。
  • 我们还将创建具有位置、高度、宽度、速度健康和移动状态等属性的玩家对象。
  • 创建一个 gem 对象,该对象将使用高度、宽度和位置等属性来表示我们游戏的最终状态。
  • 最后,添加带有mousedownmouseup事件的事件侦听器以移动播放器并停止播放器。
  • 我们已准备好进行初始设置。让我们看看下面的输出。

JavaScript

function init(){
    cvs = document.getElementById('mycanvas');
  
    // Setting the height and width of canvas
    W = cvs.width = 1252;
    H = cvs.height = 516;
  
    // Getting the context the of canvas
    pen = cvs.getContext('2d');
  
    // Initially setting the variable to false
    game_over = false;
  
    // Creating the enemies object with
    // coordinates x y width(w) height(h)
    // and speed  
  
    e1 = {
        x:200,
        y:50,
        w:80,
        h:80,
        speed:20,
    };
     e2 = {
        x:450,
        y:150,
        w:80,
        h:80,
        speed:35,
    };    
     
     e3 = {
        x:700,
        y:300,
        w:80,
        h:80,
        speed:40,
    };
    e4 = {
        x:900,
        y:100,
        w:80,
        h:80,
        speed:30,
    };
      
    // Array of enemies
    enemy = [e1, e2, e3, e4];
      
    // Creating the player object
    player = {
        x:20,
        y:H/2,
        w:110,
        h:110,
        speed:30,
        health:100,
        moving: "false"
    }
    // Creating the vaccine gem
    gem = {
        x:W-150,
        y:H/2,
        w:150,
        h:150,
    }
  
    // The main part lets move the player
    // using event mouse down and stop 
    //using mouse up
    cvs.addEventListener('mousedown', function(){
        console.log("Mouse Pressed"); 
        player.moving = true;
    });
    cvs.addEventListener('mouseup', function(){
        console.log("Mouse Released"); 
        player.moving = false;
    });
}

输出:

第 3 步:

  • 在这一步中,我们将看到重叠函数,我们将使用它来检查我们的玩家是否与其他可能是敌人或宝石(疫苗)的物体发生碰撞。

JavaScript

function isOverlap(rect1, rect2) {
    if (rect1.x < rect2.x + rect2.w &&
        rect1.x + rect1.w > rect2.x &&
        rect1.y < rect2.y + rect2.h &&
        rect1.y + rect1.h > rect2.y) {
            return true;
    }
    return false;
}

第四步:

  • 我们将看到draw()函数,它有助于绘制敌方玩家和宝石在各自位置的图形图像。

JavaScript

function draw() {
  
    // Drawing the images
    for(let i = 0; i < enemy.length; i++) {
        pen.drawImage(enemy_img, enemy[i].x, 
          enemy[i].y, enemy[i].w, enemy[i].h);
    }
  
    // Draw the player
    pen.drawImage(player_img, player.x, 
        player.y, player.w, player.h);
  
    // Draw the vaccine
    pen.drawImage(gem_img, gem.x, 
        gem.y, gem.w, gem.h);
  
    // Displaying score
    pen.fillStyle = "white";
    pen.font = "30px Roboto";
    pen.fillText("Score " + 
        player.health, 30, 30);
}

第 5 步:

  • 下面实现了update()函数。
  • 游戏结束后返回。
  • 如果玩家仍在移动,则会增加玩家的速度和生命值。
  • 如果我们的玩家与任何敌人发生碰撞,它将播放失败的声音并降低 50 点生命值。
  • 如果生命值变为负数或 0,则游戏结束并返回。
  • 如果游戏还没有结束,我们将查看我们的玩家是否与疫苗(宝石)发生碰撞。在这种情况下,游戏结束,播放获胜声音,并提醒得分。
  • 如果游戏还没有结束,它会调整敌人的速度和位置。

JavaScript

function update() {
  
    // If player is moving
    if(game_over){
        return;
    }
    if(player.moving == true){
        player.x += player.speed;
        player.health += 20;
    }
  
    // Checking collision of player
    // with all enemies
    for(let i = 0; i < enemy.length; i++){
        if(isOverlap(enemy[i], player)){
            lose.play();
            player.health -= 50;
            if(player.health < 0){
                draw();
                lose.play();
                alert("You Lose ");
                game_over = true;
                return;
            }
        }
    }
  
    // checking the player and vaccine
    // collision for the win.
    if(isOverlap(player, gem)){
        win.play();
        alert("You Won " + player.health);
        game_over = true;
        return;
    }
  
    // Adjusting the speed and positions
    // of enemy
    for(let i = 0; i H-enemy[i].h || enemy[i].y <= 0){
            enemy[i].speed *= -1;
        }
    }
}

第 6 步:

  • 让我们完成我们将用来运行游戏的gameloop()函数。
  • 如果游戏状态结束,它将清除我们最终调用的整个间隔。
  • 我们将根据用户的操作绘制对象并更新事物。

JavaScript

function gameloop(){
    if(game_over){
        clearInterval(f);
    }
    draw();
    update();
}

第 7 步:

  • 注意:我们将 JavaScript 文件“covid.js”中的所有函数一起调用。
  • 首先,我们将调用load_assets()init()函数。
  • 我们将每隔 100 毫秒调用一次gameloop()函数。

JavaScript

load_assets();
init();
var f = setInterval(gameloop, 100);

输出:

源代码:

https://github.com/Nandini-72/Covid_Fighter_Game