// Simple Breakout Game for ImageJ Macro

width = 500;
height = 375;
paddleWidth = 60;
paddleHeight = 8;
paddleY = height - 20;
ballX = width/2;
ballY = height/2;
ballVX = 2;
ballVY = -2;
ballSize = 6;
rows = 5;
cols = 10;
brickW = width/cols;
brickH = 15;

// Brick array (1 = alive, 0 = destroyed)
bricks = newArray(rows * cols);

for (i=0; i<bricks.length; i++) bricks[i] = 1;

// Create image

newImage("Breakout", "8-bit black", width, height, 1);

function drawGame(paddleX) {
    setColor(0);
    fillRect(0,0,width,height);

    // Draw bricks
   brickCount = 0;
   setColor(200);
   for (r=0; r<rows; r++) {
        for (c=0; c<cols; c++) {
            idx = r*cols + c;
             if (bricks[idx] == 1) {
                x = c * brickW;
                y = r * brickH + 20;
                fillRect(x, y, brickW-2, brickH-2);
            }
         }
    }

    // Draw paddle
    setColor(255); 
    fillRect(paddleX, paddleY, paddleWidth, paddleHeight);

    // Draw ball
    fillOval(ballX, ballY, ballSize, ballSize);
}

paddleX = width/2 - paddleWidth/2;

 autoUpdate(false); // disable automatic display updates
 while (true) {

    // Mouse controls paddle

    getCursorLoc(x, y, z, flags);

    paddleX = x - paddleWidth/2;

    if (paddleX < 0) paddleX = 0;

    if (paddleX > width - paddleWidth) paddleX = width - paddleWidth;

    // Move ball

    ballX += ballVX;

    ballY += ballVY;

    // Wall collisions

    if (ballX <= 0 || ballX >= width-ballSize) ballVX *= -1;

    if (ballY <= 0) ballVY *= -1;

    // Paddle collision

    if (ballY + ballSize >= paddleY &&

        ballX + ballSize >= paddleX &&

        ballX <= paddleX + paddleWidth) {

        ballVY *= -1;

        ballY = paddleY - ballSize;

    }

    // Brick collision

    for (r=0; r<rows; r++) {

        for (c=0; c<cols; c++) {

            idx = r*cols + c;

            if (bricks[idx] == 1) {

                bx = c * brickW;

                by = r * brickH + 20;

                if (ballX + ballSize > bx && ballX < bx + brickW &&

                    ballY + ballSize > by && ballY < by + brickH) {

                    bricks[idx] = 0;

                    ballVY *= -1;

                }

            }

        }

    }

    // Game over
    if (ballY > height) {
        showMessage("Game Over");
        break;
    }
    drawGame(paddleX);
    updateDisplay();
    wait(15);
    // Game won
    brickCount = 0;
    for (i=0; i<bricks.length; i++) {
       if (bricks[i]==1)
          brickCount++;;
    }
    if (brickCount==0) {
        showMessage("Congratulations!!");
        exit;
    }

}
