简体   繁体   中英

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. I'm using the function redraw() Full Code is at 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.

// 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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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