如何在此功能中添加“开始”按钮?

时间:2017-12-14 15:29:11

标签: javascript jquery button audio

我正在试图弄清楚如何通过替换背景音频来添加一个开始按钮来玩javascript游戏。我遇到了这个游戏,它的工作方式是你加载页面后音乐在后台播放,游戏已经开始。当我删除音频链接时,游戏暂停后,玩家3的生命都在上升,如果我留下音频,那么当3个人生命起来时你可以看到你的积分和弹出消息,有人可以帮我理解这个

这是游戏的链接,因此您可以查看代码并了解我想说的内容:https://jsfiddle.net/74nbrdak/embedded/result/

<div>
<canvas id="canvas" width="1000" height="500"></canvas>
</div>

<audio id="background-music" preload="auto" autoplay loop>
<source 
src="https://dl.dropbox.com/s/5r3iu7kjsl0mx81/Wildfire%20Cut%20Loopable.wav"       type="audio/wav">

 function ShowGamesFinished() {
var message = gamesfinished[Math.floor(Math.random() *     gamesfinished.length)];

 document.getElementById("background-music").pause();

3 个答案:

答案 0 :(得分:1)

  

当我删除音频链接时,游戏暂停后玩家3生命起来,如果我留下音频,那么当3个生命起来时你可以看到你的积分和弹出消息,有人可以请帮助我理解这个

所以,在音频元素在页面上的第二个场景中,游戏就像创作者想要的那样工作 在音频元素不在页面上的第一种情况下,游戏正常工作,直到调用处理游戏结束的功能。造成该函数问题的原因是这一行document.getElementById("background-music").pause();。由于音频元素不存在,因此会引发错误,并且不会绘制游戏在屏幕上。希望这有助于

答案 1 :(得分:0)

如果您使用纯javascript没有任何外部库,您可以初始化您的画布,只需单击该按钮,您就可以开始设置画布动画并开始游戏。 让我知道如果你没有得到答案。

答案 2 :(得分:0)

乍一看,删除音频标签应该对javascript没有任何影响。由于音频标签具有自动播放属性,因此在打开页面时播放音频。

所有javascript代码似乎都在脚本标记内,因此一旦页面打开它也会自动运行。您可以尝试将整个代码从小提琴包装到一个函数中,然后将其绑定到您的按钮。

类似的东西:

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
    h1 {
      font-family: Architects Daughter;
      text-align: center;
      font-size: 48pt;
      margin-top: 50px;
      margin-bottom: 0px;
    }

    h2 {
      font-family: Architects Daughter;
      text-align: center;
      font-size: 28pt;
      margin-top: 0px;
      margin-bottom: 50px;
    }

    span {
      display: block;
      font-family: Arial;
      text-align: center;
      margin-bottom: 2px;
    }

    div {
      display: flex;
      justify-content: space-around;
    }

    canvas {
      border: 2px solid #CC3333;
    }
    </style>
</head> 
<body>
    <div>
      <canvas id="canvas" width="640" height="360"></canvas>
    </div>
    <button id="start_game">Start</button>
    <script>
var run_game = function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
var updateTime = 20; // Milliseconds
var keys = [false, false, false];

var score = 0;
var kills = 0;

// Player Size = 50x18
var playerHealth = 3;
var playerX = WIDTH / 2;
var playerY = HEIGHT - 20;
var playerSpeed = 6;

var lazerSpeed = 16;
var lazerReloadDistance = playerY - 120;
var lazerLoaded = true;
var lazers = [];

var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var maxEnemies = 12;
var enemySpeed = 4;
var enemies = [];

function Clear() {
    ctx.fillStyle = "#404040";
  ctx.fillRect(0, 0, WIDTH, HEIGHT);
}

function DrawHealth(health) {
    ctx.fillStyle = "#E52B50";
  ctx.shadowColor = "#E52B50";
  ctx.shadowBlur = 15;
  ctx.font = "18px Arial";
  ctx.textAlign = "start";

  var hearts = "";

  if (health == 3) {
    hearts = "<3 <3 <3";
  }
  else if (health == 2) {
    hearts = "<3 <3 X";
  }
  else if (health == 1) {
    hearts = "<3 X X";
  }
  else {
    hearts = "X X X";
  }

  ctx.fillText(hearts, 10, 25);
}

function DrawScore() {
    ctx.fillStyle = "#FFFF00";
  ctx.shadowColor = "#FFFF00";
  ctx.shadowBlur = 15;
  ctx.font = "18px Arial";
  ctx.textAlign = "end";
  ctx.fillText(score, WIDTH - 10, 25);
}

function DrawPlayer(x, y) {
    ctx.fillStyle = "#1E90FF";
  ctx.shadowColor = "#1E90FF";
  ctx.shadowBlur = 15;
  ctx.font = "24px Arial";
  ctx.textAlign = "center";
  ctx.fillText("</^\\>", x, y);
}

function Lazer() {
    this.x = playerX;
  this.y = playerY - 38;

  this.draw = function() {
    ctx.fillStyle = "#FFFF00";
    ctx.shadowColor = "#FFFF00";
    ctx.shadowBlur = 15;
    this.y -= lazerSpeed;
    ctx.fillRect(this.x, this.y, 2, 18);
  }
}

function DrawLazers() {
    // Check if the last lazer fired is far enough away to fire another
    if (lazers.length != 0) {
    if (lazers[lazers.length - 1].y <= lazerReloadDistance) {
        lazerLoaded = true;
    }
    }
  else {
    lazerLoaded = true;
  }

    for (var i = 0; i < lazers.length; i++) {
    var currentLazer = lazers[i];

    // Still on screen
    if (currentLazer.y > -20) {
        currentLazer.draw();
    }
    else {
        lazers.splice(i, 1);
    }
  }
}

function Enemy(x) {
    this.x = x;
  this.y = 0;
  this.health = Math.ceil(Math.random() * 4);
  this.speed = enemySpeed / this.health;

  var letterIndex = Math.floor(Math.random() * letters.length);
  this.letter = letters.substr(letterIndex, 1);

  this.size = 24 + (this.health * 4); // Font size based on health
  ctx.font = this.size+"px Arial";

  this.width = ctx.measureText(this.letter).width;
  this.height = this.size * 0.75; // Approximate height;

  this.draw = function() {
    ctx.fillStyle = "#FF0040";
    ctx.shadowColor = "#FF0040";
    ctx.shadowBlur = 15;
    ctx.font = this.size+"px Arial";
    ctx.textAlign = "center";

    this.y += this.speed;

    ctx.fillText(this.letter, this.x, this.y);
  }
}

function DrawEnemies() {
    // Spawn new enemies
    if (Math.random() <= 0.05 && enemies.length < maxEnemies) {
    var randX = 40 + Math.floor(Math.random() * (WIDTH - 80));
    enemies.push(new Enemy(randX));
  }

    for (var i = 0; i < enemies.length; i++) {
    var currentEnemy = enemies[i];

    if (currentEnemy.health <= 0) {
        enemies.splice(i, 1);
      score += 25;
      kills++;
      continue;
    }

    // Put enemies that passed the player back at the top
    if (currentEnemy.y > HEIGHT + currentEnemy.height) {
      currentEnemy.y = 0;
      continue;
    }

    currentEnemy.draw();
  }
}

var gameOverMessages = [
    "You're in a better place",
  "You're Cooked!",
  "You gave it your all",
  "At least you tried",
  "You're Ruined!",
  "You're Finished!"
];
function DrawGameOver() {
    var message = gameOverMessages[Math.floor(Math.random() * gameOverMessages.length)];
// after deleting the audio element, this doesnt work anymore.
// document.getElementById("background-music").pause();

    ctx.fillStyle = "#505050";
  ctx.shadowColor = "#505050";
  ctx.shadowBlur = 15;
  ctx.fillRect(50, (HEIGHT / 2) - 100, WIDTH - 100, 200)

  ctx.fillStyle = "#FFFFFF";
  ctx.shadowColor = "#FFFFFF";
  ctx.shadowBlur = 15;
  ctx.textAlign = "center";
  ctx.font = "36pt Arial";
  ctx.fillText(message, WIDTH / 2, HEIGHT / 2 - 40);

  ctx.textAlign = "end";
  ctx.font = "18pt Arial";
  ctx.fillText("Final Score - ", WIDTH / 2, HEIGHT / 2 + 30);

  ctx.textAlign = "start";
  ctx.fillStyle = "#FFFF00";
  ctx.shadowColor = "#FFFF00";
  ctx.fillText(score, WIDTH / 2, HEIGHT / 2 + 30);

  ctx.fillStyle = "#FFFFFF";
  ctx.shadowColor = "#FFFFFF";
  ctx.textAlign = "end";
  ctx.font = "18pt Arial";
  ctx.fillText("Total Kills - ", WIDTH / 2, HEIGHT / 2 + 60);

  ctx.textAlign = "start";
  ctx.fillStyle = "#FF0040";
  ctx.shadowColor = "#FF0040";
  ctx.fillText(kills, WIDTH / 2, HEIGHT / 2 + 60);
}

////////////////////
// Core Functions //
////////////////////
var collidedEnemyIndex = -1;
function CheckCollision() {
    for (var i = 0; i < enemies.length; i++) {
    var currentEnemy = enemies[i];

    // Check if enemy hits player. The 2 is to account for the text width of the player
    if (
            currentEnemy.x <= playerX - 2 + 25 + (currentEnemy.width / 2) && 
        currentEnemy.x >= playerX - 2 - 25 - (currentEnemy.width / 2) && 
        currentEnemy.y >= playerY - 18 && 
        currentEnemy.y <= playerY + currentEnemy.height && 
        collidedEnemyIndex != enemies.indexOf(currentEnemy)
         )
    {
      collidedEnemyIndex = enemies.indexOf(currentEnemy);
      playerHealth--;
    }

    // Reset the index of the enemy colliding with the player
    if (collidedEnemyIndex == enemies.indexOf(currentEnemy) && currentEnemy.y < HEIGHT / 2) {
        collidedEnemyIndex = -1;
    }

    for (var j = 0; j < lazers.length; j++) {
        var currentLazer = lazers[j];

      if (
         currentLazer.x <= currentEnemy.x + (currentEnemy.width / 2) && 
         currentLazer.x >= currentEnemy.x - (currentEnemy.width / 2) && 
         currentLazer.y <= currentEnemy.y
         )
      {
        currentEnemy.health--;
        score += 10;
        lazers.splice(lazers.indexOf(currentLazer), 1);
      }
    }
  }
}

function HandleInput() {
    if (keys[0] == true && keys[1] == false && playerX <= WIDTH - 30) {
    playerX += playerSpeed;
  }

  if (keys[1] == true && keys[0] == false && playerX >= 30) {
    playerX -= playerSpeed;
  }

  if (keys[2]) {
    if (lazerLoaded) {
      lazers.push(new Lazer());
      lazerLoaded = false;
    }
  }
}

function KeysDown(e) {
    e.preventDefault();

  // Right
    if (e.keyCode == 39) {
    keys[0] = true;
  }
  // Left
  else if (e.keyCode == 37) {
    keys[1] = true;
  }

  // Up/Fire
  if (e.keyCode == 38) {
    keys[2] = true;
  }
}

function KeysUp(e) {
  // Right
    if (e.keyCode == 39) {
    keys[0] = false;
  }
  // Left
  else if (e.keyCode == 37) {
    keys[1] = false;
  }

  // Up/Fire
  if (e.keyCode == 38) {
    keys[2] = false;
  }
}

document.addEventListener("keydown", KeysDown, true);
document.addEventListener("keyup", KeysUp, true);

function Update() {
    Clear();

  HandleInput();

  CheckCollision();

  DrawEnemies();

  DrawLazers();
  DrawPlayer(playerX, playerY);

  DrawHealth(playerHealth);
  DrawScore();

  if (playerHealth <= 0) {
    clearInterval(gameLoop);
    DrawGameOver();
  }
}

var gameLoop = setInterval(Update, updateTime);
};

document.querySelector( '#start_game' ).addEventListener( 'click', run_game );
    </script>
</body>
</html>