简体   繁体   English

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

[英]How to reset bricks in 2D Canvas game

I'm new to Javascript, so this might be an easy fix, but I can't figure out a way to reset the bricks inside the canvas. 我是Java的新手,因此这可能很容易解决,但是我无法找到一种方法来重置画布中的积木。 I'm using the function redraw() Full Code is at https://codepen.io/Jacob-Bruce/pen/mQgbXa 我正在使用功能redraw()完整代码位于https://codepen.io/Jacob-Bruce/pen/mQgbXa

I've tried re-calling the drawBricks but I realize now I need to get the array to work. 我试过重新调用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();
} 

I want the bricks to reappear and completely reset the game, but it currently just resets the ball and paddle. 我希望砖块重新出现并完全重置游戏,但是目前它只是重置了球和桨。

I think you need to do something like this.. 我认为您需要做这样的事情。

// 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 };
  }
}

Change to 改成

// 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();

Then call resetBricks() in your code when you want to.. 然后,根据需要在代码中调用resetBricks()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM