如何在2D Canvas游戏中重置积木

时间:2019-01-24 19:24:41

标签: javascript function canvas

我是Java的新手,所以这可能很容易解决,但是我想不出一种方法来重置画布中的积木。我正在使用函数redraw()的完整代码位于https://codepen.io/Jacob-Bruce/pen/mQgbXa

我尝试重新调用drawBricks,但是我意识到现在我需要使数组起作用。

// brick layout
var bricks = [];
for(var c=0; c<brickColumnCount; c++) {
  bricks[c] = [];
  for(var r=0; r<brickRowCount; r++) {
    bricks[c][r] = { x: 0, y: 0, status: 1 };
  }
}
// draw bricks
function drawBricks() {
  for(var c=0; c<brickColumnCount; c++) {
    for(var r=0; r<brickRowCount; r++) {
      if(bricks[c][r].status == 1) {
        var brickX = (r*(brickWidth+brickPadding))+brickOffsetLeft;
        var brickY = (c*(brickHeight+brickPadding))+brickOffsetTop;
        bricks[c][r].x = brickX;
        bricks[c][r].y = brickY;
        ctx.beginPath();
        ctx.rect(brickX, brickY, brickWidth, brickHeight);
        ctx.fillStyle = "#0095DD";
        ctx.fill();
        ctx.closePath();
      }
    }
  }
}
// redraw function -- used to reset when selecting mode
function redraw() {
  score = 0
  x = canvas.width/2;
  y = canvas.height-30;
  paddleX = (canvas.width-paddleWidth)/2
  // find how to make bricks reappear
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawBricks();
  drawBall();
  drawPaddle();
  drawScore();
  drawLives();
  collisionDetection();
} 

我希望砖块重新出现并完全重置游戏,但是目前它只是重置了球和桨。

1 个答案:

答案 0 :(得分:0)

我认为您需要做这样的事情。

// brick layout
var bricks = [];
for(var c=0; c<brickColumnCount; c++) {
  bricks[c] = [];
  for(var r=0; r<brickRowCount; r++) {
    bricks[c][r] = { x: 0, y: 0, status: 1 };
  }
}

更改为

// brick layout
var bricks = [];
function resetBricks() {
    for(var c=0; c<brickColumnCount; c++) {
      bricks[c] = [];
      for(var r=0; r<brickRowCount; r++) {
        bricks[c][r] = { x: 0, y: 0, status: 1 };
      }
   }
}
resetBricks();

然后根据需要在代码中调用resetBricks()。