我遇到的问题是让程序遍历为Breakout游戏创建的积木。

我已经通过调用createBrick()方法尝试了几种不同的方法,但是没有用。有人可以告诉我即时消息是否走对头吗?这是我的BreakoutPanel类的以下代码。

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;

public class BreakoutPanel extends JPanel implements ActionListener, KeyListener {

static final long serialVersionUID = 2L;

private boolean gameRunning = true;
private int livesLeft = 3;
private String screenMessage = "";
private Ball ball;
private Paddle paddle;
private Brick[] bricks;
private int xVelocity;

public BreakoutPanel(Breakout game) {

    addKeyListener(this);
    setFocusable(true);

    Timer timer = new Timer(5, this);
    timer.start();

    ball = new Ball();                                                              // Creates ball object with appropriate variable
    paddle = new Paddle();                                                          // Creates paddle object with appropriate variable
    bricks = new Brick [Settings.TOTAL_BRICKS];                                     // Creates brick array

    createBricks(null);                                                             // Call the createBricks() method

}
private void createBricks(Graphics g) {
    int counter = 0;
    int x_space = 0;
    int y_space = 0;
    for(int x = 0; x < 4; x++) {
        for(int y = 0; y < 5; y++) {
            bricks[counter] = new Brick((x * Settings.BRICK_WIDTH) + Settings.BRICK_HORI_PADDING + x_space, (y * Settings.BRICK_HEIGHT) + Settings.BRICK_VERT_PADDING + y_space);
            counter++;
            y_space++;
        }
        x_space++;
        y_space = 0;
    }
}
private void paintBricks(Graphics g) {
    paintComponent(g);
    // TODO: Loop through the bricks and call the paint() method

    paint(g);
}


我需要的结果是我的程序打印出我的积木,但目前无法弄清楚如何遍历我的积木。如果这是一个不好的问题,很抱歉,我一直在查看google和youtube,但只能在程序中找到其具有砖块物理图片且尚未实际创建的版本。我希望这是有道理的。

最佳答案

如我所见
私人砖[]砖;我假设您只想循环访问Brick类的数组(名为Bricks)。

那么简单:

for (int i=0;i< bricks.length;i++)
{

    //do things with bricks[i] as example bricks[i].draw() or myMethod(bricks[i]); ...
}

10-04 12:23