首页 > 解决方案 > 如何使按钮(Easy、Hard、Impossible)影响球阵列的出现间隔?

问题描述

我是 html 新手,我今年 13 岁,所以希望我有点缺乏经验。我从我制作的一个较旧的游戏(Pong)中制作了一个游戏“小行星游戏”,然后我放了四个按钮。首先是重新开​​始游戏。第二种是重新开始游戏,但让球每 7 秒出现一次。第三个按钮使它们每 5 秒出现一次,第四个按钮使它们每 2 秒出现一次。

var canvas;
var canvasContext;
// var ball = { };
// ball.x = 780;
// ball.y = 200;
// ball.speedX = -1.25;
// ball.speedY = 0;
var balls = [];
//var ball.x = 780s;
//var ball.y = 200;
//var ball.speedX = -1.25;
//var ball.speedY = 0;
var canvasTop = 0;
var canvasBorderColor = 'blue';
var paddle1Y = 200;
var paddle2Y = 0; //ball.y;
const PADDLE_HEIGHT = 15;
const PADDLE_THICKNESS = 25;
var Paddle2YCenter = paddle2Y + (PADDLE_HEIGHT / 2)
var gameon = false;
var player1Score = 0
var player2Score = 0
// from here **
var playerHighScore = player1Score 
var appearinterval = 7 * 1000; 

function btnRefresh_onClick() {
  restartGame();
} 
function easy_onClick() {
  restartGame();
  appearinterval = 7000;
} 
function hard_onClick() {
  restartGame();
  appearinterval = 5 * 1000;
} 


function impossible_onClick() {
  restartGame();
  appearinterval = 2000;
} 
// to here
function calculateMousePos(evt) {
  var rect = canvas.getBoundingClientRect();
  var root = document.documentElement;
  var mouseX = evt.clientX - rect.left - root.scrollLeft;
  var mouseY = evt.clientY - rect.top - root.scrollTop;
  return {
    x: mouseX,
    y: mouseY
  };
}

window.onload = function() {
  canvas = document.getElementById('GameCanvas');
  canvasContext = canvas.getContext('2d');
  gameon = false;
  var framesPerSecond = 3000000000000000000000;
  setInterval(function() {
    moveEverything();
    drawEverything();
  }, 300000000 / framesPerSecond);

  setInterval(function() {
    if (gameon == true) {
      addBall();
    }
  }, appearinterval);



  // Create listener 
  document.addEventListener('keydown',
    function(evt) {
      console.log('test');
      if (evt.keyCode == 38) {
        paddle1Y = paddle1Y - 7.5
      }
      if (evt.keyCode == 87) {
        paddle1Y = paddle1Y - 7.5
      }
      if (evt.keyCode == 40) {
        paddle1Y = paddle1Y + 7.5
      }
      if (evt.keyCode == 83) {
        paddle1Y = paddle1Y + 7.5
      }
      //alert( "arrowkey pressed" );
    });


  canvas.addEventListener('mousemove',
    function(evt) {
      var mousePos = calculateMousePos(evt);
      paddle1Y = mousePos.y - (PADDLE_HEIGHT / 2);
    });
}


function ballReset(ball) {
  ball.speedX = ball.speedX + -0.033;
  ball.x = canvas.width - 20;
  ball.y = Math.random() * canvas.height;
  //BallZ = Math.random () *canvas.height;

}

// function computerMovement() {
//     var Paddle2YCenter = paddle2Y + (PADDLE_HEIGHT/2);
//     if(Paddle2YCenter < ball.y - 35) {
//             paddle2Y += 0.8;
//     } else if(Paddle2YCenter > ball.y + 35) {
//             paddle2Y -= 0.8;
//     }
// }


// remove ball 
function removeBall() {
  balls.pop();

}

// remove all balls
function removeAllBalls() {
  for (var i = balls.length - 1; i >= 0; i--) {
    removeBall();
  }
}


function moveBall(ball) {
  ball.x += ball.speedX;
  ball.y += ball.speedY;

  // // right paddle
  // if(ball.x > canvas.width - 20) {
  //         if(ball.y > paddle2Y &&
  //            ball.y < paddle2Y+PADDLE_HEIGHT) {
  //                 ball.speedX = -ball.speedX - 0.015;

  //             var deltaY = ball.y
  //                     -(paddle2Y+PADDLE_HEIGHT/2);
  //             ball.speedY = deltaY * 0.03;
  //         } else {
  //                 ballReset()
  //                // player1Score++;
  //         }

  // }

  // left paddle
  if (ball.x < 163 && ball.x > 85) {
    if (ball.y > paddle1Y - 10 &&
      ball.y < paddle1Y + PADDLE_HEIGHT + 10) {

      // endgame
      stopGame();
      setTimer(function() {

      }, 0.5 * 1000);

      player1score = 0;
      removeAllBalls();




      //     ball.speedX = -ball.speedX;

      //     var deltaY = ball.y
      //             -(paddle1Y+PADDLE_HEIGHT/2);
      //     ball.speedY = deltaY * 0.03;
    } else {

      //player2Score++;
    }



  }
  if (ball.x < 5) {
    ballReset(ball);
    (player1Score++);
    //addBall();
  }


  // bottom
  if (ball.y > canvas.height - 10) {
    ball.speedY = -ball.speedY - 0.0002;
  }

  // top
  if (ball.y < 10) {
    ball.speedY = -ball.speedY + 0.0002;
  }



}


function moveEverything() {
  //computerMovement();
  for (var i = 0; i < balls.length; i++) {
    moveBall(balls[i]);
  }

  if (player1Score > playerHighScore) {
    playerHighScore = player1Score
  }

}

function drawEverything() {
  // outside canvas
  canvasContext.fillStyle = canvasBorderColor;
  canvasContext.fillRect(0, canvasTop, canvas.width, canvas.height);

  // inside canvas
  canvasContext.fillStyle = 'black';
  canvasContext.fillRect(5, canvasTop + 5, canvas.width - 10, canvas.height - canvasTop - 10);

  // the body
  canvasContext.fillStyle = 'gray';
  canvasContext.fillRect(100, paddle1Y, PADDLE_THICKNESS, PADDLE_HEIGHT);

  // the window
  colorCircle(120, paddle1Y + 7.5, 5, 'black');

  // the nose
  canvasContext.beginPath();
  canvasContext.moveTo(125, paddle1Y);
  canvasContext.lineTo(PADDLE_THICKNESS + 135, paddle1Y + 7.5);
  canvasContext.lineTo(125, paddle1Y + 15);
  canvasContext.closePath();
  canvasContext.fillStyle = "grey";
  canvasContext.fill();

  // the top fin
  canvasContext.beginPath();
  canvasContext.moveTo(100, paddle1Y);
  canvasContext.lineTo(112.5 - PADDLE_THICKNESS, paddle1Y);
  canvasContext.lineTo(100, paddle1Y + 7.5);
  canvasContext.closePath();
  canvasContext.fillStyle = "grey";
  canvasContext.fill();

  // the bottom fin
  canvasContext.beginPath();
  canvasContext.moveTo(100, paddle1Y + 7.5);
  canvasContext.lineTo(112.5 - PADDLE_THICKNESS, paddle1Y + 15);
  canvasContext.lineTo(100, paddle1Y + 15);
  canvasContext.closePath();
  canvasContext.fillStyle = "grey";
  canvasContext.fill();

  // the orange rocket
  canvasContext.beginPath();
  canvasContext.moveTo(112.5 - PADDLE_THICKNESS, paddle1Y + 3.75);
  canvasContext.lineTo(100, paddle1Y + 7.5);
  canvasContext.lineTo(112.5 - PADDLE_THICKNESS, paddle1Y + 11.25);
  canvasContext.closePath();
  canvasContext.fillStyle = "orange";
  canvasContext.fill();
  canvasContext.beginPath();
  canvasContext.moveTo(113 - PADDLE_THICKNESS, paddle1Y + 3.75);
  canvasContext.lineTo(75, paddle1Y + 7.5);
  canvasContext.lineTo(113 - PADDLE_THICKNESS, paddle1Y + 11.25);
  canvasContext.closePath();
  canvasContext.fillStyle = "orange";
  canvasContext.fill();

  // right comuter paddle
  canvasContext.fillStyle = 'grey';
  canvasContext.fillRect(105, paddle1Y, 2, PADDLE_HEIGHT);

  // ball
  for (var i = 0; i < balls.length; i++) {
    var ball = balls[i];
    colorCircle(ball.x, canvasTop + ball.y, ball.radius, 'red');
    canvasContext.fillStyle = ('green'); // ball
  }


  // if(player1Score < 10 &&
  //    player2Score < 10) {
  canvasContext.font = "20px Arial";
  //       canvasContext.fillText(player2Score, canvas.width-100,canvasTop+300);
  canvasContext.fillText(player1Score, 75, canvasTop + 26);
  canvasContext.fillText('Score:', 10, canvasTop + 25);


  canvasContext.font = "20px Arial";
  canvasContext.fillText(playerHighScore, canvas.width - 40, canvasTop + 26);
  canvasContext.fillText('High Score:', canvas.width - 150, canvasTop + 25);
  //        canvasContext.fillText('Play to 10!', 400-25,100);
  //}
  // if(player1Score > 9) {
  //             canvasContext.fillText('You Won!', 380,300);
  //           //  stopGame();
  //             canvasContext.fillText(player1Score, 400-10,350);
  //             canvasContext.fillText(player2Score, 400+30,350);
  //         }
  //         if(player2Score > 9) {
  //             canvasContext.fillText('You Lost!', 380,300);
  //          //   stopGame();
  //             canvasContext.fillText(player1Score, 400-10,350);
  //             canvasContext.fillText(player2Score, 400+30,350);
  //         }
}



function stopGame() {
  // change the balls
  for (var i = 0; i < balls.length; i++) {
    var ball = balls[i];
    ball.radius = 50;
    ball.speedY = 0;
    ball.speedX = 0;
    //ball.x = 415
    //ball.y = 315


  }

  // set canvas properties
  canvasBorderColor = 'red';
  gameon = false;
  paddle1Y = 0
  paddle1Y = mousePos.y - (PADDLE_HEIGHT / 2);
}

function restartGame() {
  balls = [];
  addBall();
  canvasBorderColor = 'blue';
  gameon = true;

  //     ball.speedX = -1.25;
  //     ball.speedY = 0;
  player1Score = 0;
  player2Score = 0;
  //     ball.x = 415
  //     ball.y = 315
}

function addBall() {
  var b = {};
  b.x = canvas.width - 20;
  b.y = Math.random() * canvas.height;
  b.speedX = -1.25;
  b.speedY = 0;
  b.radius = 15;
  balls.push(b);
}

function colorCircle(centerX, centerY, radius, drawColor) {
  canvasContext.fillStyle = drawColor;
  canvasContext.beginPath();
  canvasContext.arc(centerX, centerY, radius, 0, Math.PI * 2, true);
  canvasContext.fill();
}

/*
function colorRect(leftX,topY, width,height, drawColor) {
canvasContext.fillStyle = drawColor;
canvasContext.fillRect(0,100,canvas.width,canvas.height);
}
*/
<h1>Asteroid!</h1>

You have now entered the asteroid belt. Dodge the asteroids to protect your ship!

<br><br>

<button id="btnRefresh" type="button" onClick="btnRefresh_onClick();">`Play game`</button>
<button id="easy" type="button" onClick="easy_onClick();">`Easy`</button>
<button id="hard" type="button" onClick="hard_onClick();">`Hard`</button>
<button id="impossible" type="button" onClick="impossible_onClick();">`Impossible`</button><br/><br>
<canvas id="GameCanvas" width="800" height="600"></canvas>

标签: javascripthtmlbuttonintervals

解决方案


我做了一些改变:

我将您的 setInterval 移到了 restartGame 中。

在您的关卡按钮中,我将restartGame 移到了更改间隔的下方。

然后在 restartGame 我有 setInterval 但首先我检查间隔是否存在,如果存在则清除它。我也在顶部声明间隔。

这些更改的原因是您可以清除间隔,并使用新的间隔值创建一个新的间隔。

var canvas;
var canvasContext;
var interval;
// var ball = { };
// ball.x = 780;
// ball.y = 200;
// ball.speedX = -1.25;
// ball.speedY = 0;
var balls = [];
//var ball.x = 780s;
//var ball.y = 200;
//var ball.speedX = -1.25;
//var ball.speedY = 0;
var canvasTop = 0;
var canvasBorderColor = 'blue';
var paddle1Y = 200;
var paddle2Y = 0; //ball.y;
const PADDLE_HEIGHT = 15;
const PADDLE_THICKNESS = 25;
var Paddle2YCenter = paddle2Y + (PADDLE_HEIGHT / 2)
var gameon = false;
var player1Score = 0
var player2Score = 0
// from here **
var playerHighScore = player1Score 
var appearinterval = 7 * 1000; 

function btnRefresh_onClick() {
  restartGame();
} 
function easy_onClick() {
  appearinterval = 7000;
  restartGame();
  
} 
function hard_onClick() {
  appearinterval = 5 * 1000;
  restartGame();
} 


function impossible_onClick() {
  appearinterval = 2000;
  restartGame();
} 
// to here
function calculateMousePos(evt) {
  var rect = canvas.getBoundingClientRect();
  var root = document.documentElement;
  var mouseX = evt.clientX - rect.left - root.scrollLeft;
  var mouseY = evt.clientY - rect.top - root.scrollTop;
  return {
    x: mouseX,
    y: mouseY
  };
}

window.onload = function() {
  canvas = document.getElementById('GameCanvas');
  canvasContext = canvas.getContext('2d');
  gameon = false;
  var framesPerSecond = 3000000000000000000000;
  setInterval(function() {
    moveEverything();
    drawEverything();
  }, 300000000 / framesPerSecond);


  // Create listener 
  document.addEventListener('keydown',
    function(evt) {
      console.log('test');
      if (evt.keyCode == 38) {
        paddle1Y = paddle1Y - 7.5
      }
      if (evt.keyCode == 87) {
        paddle1Y = paddle1Y - 7.5
      }
      if (evt.keyCode == 40) {
        paddle1Y = paddle1Y + 7.5
      }
      if (evt.keyCode == 83) {
        paddle1Y = paddle1Y + 7.5
      }
      //alert( "arrowkey pressed" );
    });


  canvas.addEventListener('mousemove',
    function(evt) {
      var mousePos = calculateMousePos(evt);
      paddle1Y = mousePos.y - (PADDLE_HEIGHT / 2);
    });
}


function ballReset(ball) {
  ball.speedX = ball.speedX + -0.033;
  ball.x = canvas.width - 20;
  ball.y = Math.random() * canvas.height;
  //BallZ = Math.random () *canvas.height;

}

// function computerMovement() {
//     var Paddle2YCenter = paddle2Y + (PADDLE_HEIGHT/2);
//     if(Paddle2YCenter < ball.y - 35) {
//             paddle2Y += 0.8;
//     } else if(Paddle2YCenter > ball.y + 35) {
//             paddle2Y -= 0.8;
//     }
// }


// remove ball 
function removeBall() {
  balls.pop();

}

// remove all balls
function removeAllBalls() {
  for (var i = balls.length - 1; i >= 0; i--) {
    removeBall();
  }
}


function moveBall(ball) {
  ball.x += ball.speedX;
  ball.y += ball.speedY;

  // // right paddle
  // if(ball.x > canvas.width - 20) {
  //         if(ball.y > paddle2Y &&
  //            ball.y < paddle2Y+PADDLE_HEIGHT) {
  //                 ball.speedX = -ball.speedX - 0.015;

  //             var deltaY = ball.y
  //                     -(paddle2Y+PADDLE_HEIGHT/2);
  //             ball.speedY = deltaY * 0.03;
  //         } else {
  //                 ballReset()
  //                // player1Score++;
  //         }

  // }

  // left paddle
  if (ball.x < 163 && ball.x > 85) {
    if (ball.y > paddle1Y - 10 &&
      ball.y < paddle1Y + PADDLE_HEIGHT + 10) {

      // endgame
      stopGame();
      setTimer(function() {

      }, 0.5 * 1000);

      player1score = 0;
      removeAllBalls();




      //     ball.speedX = -ball.speedX;

      //     var deltaY = ball.y
      //             -(paddle1Y+PADDLE_HEIGHT/2);
      //     ball.speedY = deltaY * 0.03;
    } else {

      //player2Score++;
    }



  }
  if (ball.x < 5) {
    ballReset(ball);
    (player1Score++);
    //addBall();
  }


  // bottom
  if (ball.y > canvas.height - 10) {
    ball.speedY = -ball.speedY - 0.0002;
  }

  // top
  if (ball.y < 10) {
    ball.speedY = -ball.speedY + 0.0002;
  }



}


function moveEverything() {
  //computerMovement();
  for (var i = 0; i < balls.length; i++) {
    moveBall(balls[i]);
  }

  if (player1Score > playerHighScore) {
    playerHighScore = player1Score
  }

}

function drawEverything() {
  // outside canvas
  canvasContext.fillStyle = canvasBorderColor;
  canvasContext.fillRect(0, canvasTop, canvas.width, canvas.height);

  // inside canvas
  canvasContext.fillStyle = 'black';
  canvasContext.fillRect(5, canvasTop + 5, canvas.width - 10, canvas.height - canvasTop - 10);

  // the body
  canvasContext.fillStyle = 'gray';
  canvasContext.fillRect(100, paddle1Y, PADDLE_THICKNESS, PADDLE_HEIGHT);

  // the window
  colorCircle(120, paddle1Y + 7.5, 5, 'black');

  // the nose
  canvasContext.beginPath();
  canvasContext.moveTo(125, paddle1Y);
  canvasContext.lineTo(PADDLE_THICKNESS + 135, paddle1Y + 7.5);
  canvasContext.lineTo(125, paddle1Y + 15);
  canvasContext.closePath();
  canvasContext.fillStyle = "grey";
  canvasContext.fill();

  // the top fin
  canvasContext.beginPath();
  canvasContext.moveTo(100, paddle1Y);
  canvasContext.lineTo(112.5 - PADDLE_THICKNESS, paddle1Y);
  canvasContext.lineTo(100, paddle1Y + 7.5);
  canvasContext.closePath();
  canvasContext.fillStyle = "grey";
  canvasContext.fill();

  // the bottom fin
  canvasContext.beginPath();
  canvasContext.moveTo(100, paddle1Y + 7.5);
  canvasContext.lineTo(112.5 - PADDLE_THICKNESS, paddle1Y + 15);
  canvasContext.lineTo(100, paddle1Y + 15);
  canvasContext.closePath();
  canvasContext.fillStyle = "grey";
  canvasContext.fill();

  // the orange rocket
  canvasContext.beginPath();
  canvasContext.moveTo(112.5 - PADDLE_THICKNESS, paddle1Y + 3.75);
  canvasContext.lineTo(100, paddle1Y + 7.5);
  canvasContext.lineTo(112.5 - PADDLE_THICKNESS, paddle1Y + 11.25);
  canvasContext.closePath();
  canvasContext.fillStyle = "orange";
  canvasContext.fill();
  canvasContext.beginPath();
  canvasContext.moveTo(113 - PADDLE_THICKNESS, paddle1Y + 3.75);
  canvasContext.lineTo(75, paddle1Y + 7.5);
  canvasContext.lineTo(113 - PADDLE_THICKNESS, paddle1Y + 11.25);
  canvasContext.closePath();
  canvasContext.fillStyle = "orange";
  canvasContext.fill();

  // right comuter paddle
  canvasContext.fillStyle = 'grey';
  canvasContext.fillRect(105, paddle1Y, 2, PADDLE_HEIGHT);

  // ball
  for (var i = 0; i < balls.length; i++) {
    var ball = balls[i];
    colorCircle(ball.x, canvasTop + ball.y, ball.radius, 'red');
    canvasContext.fillStyle = ('green'); // ball
  }


  // if(player1Score < 10 &&
  //    player2Score < 10) {
  canvasContext.font = "20px Arial";
  //       canvasContext.fillText(player2Score, canvas.width-100,canvasTop+300);
  canvasContext.fillText(player1Score, 75, canvasTop + 26);
  canvasContext.fillText('Score:', 10, canvasTop + 25);


  canvasContext.font = "20px Arial";
  canvasContext.fillText(playerHighScore, canvas.width - 40, canvasTop + 26);
  canvasContext.fillText('High Score:', canvas.width - 150, canvasTop + 25);
  //        canvasContext.fillText('Play to 10!', 400-25,100);
  //}
  // if(player1Score > 9) {
  //             canvasContext.fillText('You Won!', 380,300);
  //           //  stopGame();
  //             canvasContext.fillText(player1Score, 400-10,350);
  //             canvasContext.fillText(player2Score, 400+30,350);
  //         }
  //         if(player2Score > 9) {
  //             canvasContext.fillText('You Lost!', 380,300);
  //          //   stopGame();
  //             canvasContext.fillText(player1Score, 400-10,350);
  //             canvasContext.fillText(player2Score, 400+30,350);
  //         }
}



function stopGame() {
  // change the balls
  for (var i = 0; i < balls.length; i++) {
    var ball = balls[i];
    ball.radius = 50;
    ball.speedY = 0;
    ball.speedX = 0;
    //ball.x = 415
    //ball.y = 315


  }

  // set canvas properties
  canvasBorderColor = 'red';
  gameon = false;
  paddle1Y = 0
  paddle1Y = mousePos.y - (PADDLE_HEIGHT / 2);
}

function restartGame() {
  balls = [];
  addBall();
  canvasBorderColor = 'blue';
  gameon = true;

  //     ball.speedX = -1.25;
  //     ball.speedY = 0;
  player1Score = 0;
  player2Score = 0;
  //     ball.x = 415
  //     ball.y = 315

  if(interval){

    clearInterval(interval)
  }
  
   interval = setInterval(function() {
    if (gameon == true) {
      addBall();
    }
  }, appearinterval);
}

function addBall() {
  var b = {};
  b.x = canvas.width - 20;
  b.y = Math.random() * canvas.height;
  b.speedX = -1.25;
  b.speedY = 0;
  b.radius = 15;
  balls.push(b);
}

function colorCircle(centerX, centerY, radius, drawColor) {
  canvasContext.fillStyle = drawColor;
  canvasContext.beginPath();
  canvasContext.arc(centerX, centerY, radius, 0, Math.PI * 2, true);
  canvasContext.fill();
}

/*
function colorRect(leftX,topY, width,height, drawColor) {
canvasContext.fillStyle = drawColor;
canvasContext.fillRect(0,100,canvas.width,canvas.height);
}
*/
<h1>Asteroid!</h1>

You have now entered the asteroid belt. Dodge the asteroids to protect your ship!

<br><br>

<button id="btnRefresh" type="button" onClick="btnRefresh_onClick();">`Play game`</button>
<button id="easy" type="button" onClick="easy_onClick();">`Easy`</button>
<button id="hard" type="button" onClick="hard_onClick();">`Hard`</button>
<button id="impossible" type="button" onClick="impossible_onClick();">`Impossible`</button><br/><br>
<canvas id="GameCanvas" width="800" height="600"></canvas>


推荐阅读