Ball.java
public class Ball {
int x = 500, y = 10, speed = 1;
GameBoard board;
boolean keepRunning = true;
Thread thread;
Ball(GameBoard board) {
this.board = board;
new Thread(r1).start();
}
public int getX() {
return x;
}
public int getY() {
return y;
}
Runnable r1 = new Runnable() {
public void run() {
try {
while (true) {
if (board.ball.intersects(board.pPaddle)) {
speed = -speed;
} else {
System.out.println(board.ball + " z " + board.pPaddle);
}
x -= speed;
board.repaint();
Thread.sleep(10L);
}
} catch (InterruptedException iex) {
}
}
};
}
游戏板.java
@SuppressWarnings("serial")
public class GameBoard extends Canvas {
Image dbi;
Graphics db;
JFrame okno;
Player p = new Player(this);
Ball b = new Ball(this);
Ai a = new Ai(this);
Rectangle aiPaddle = new Rectangle(10, 590, 10, 50);
Rectangle pPaddle = new Rectangle(10, 100, 10, 50);
Rectangle ball = new Rectangle(500, 10, 10, 10);
GameBoard() {
okno = new JFrame();
okno.setTitle("Pink Ponk");
okno.setSize(600, 300);
okno.getContentPane().setBackground(Color.black);
okno.setResizable(false);
okno.setVisible(true);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(p);
}
public static void main(String[] args) {
GameBoard gra = new GameBoard();
gra.okno.add(gra);
}
@Override
public void update(Graphics g) {
pPaddle.setBounds(p.getX(), p.getY(), 10, 50);
aiPaddle.setBounds(a.getX(), a.getY(), 10, 50);
ball.setBounds(b.getX(), b.getY(), 10, 10);
dbi = createImage(10, 50);
db = dbi.getGraphics();
paint(db);
g.clearRect(0, 0, 600, 300);
g.drawRect(p.getX(), p.getY(), 10, 50);
g.fillRect(p.getX(), p.getY(), 10, 50);
g.drawOval(b.getX(), b.getY(), 10, 10);
g.fillOval(b.getX(), b.getY(), 10, 10);
}
@Override
public void paint(Graphics g) {
pPaddle.setBounds(p.getX(), p.getY(), 10, 50);
aiPaddle.setBounds(a.getX(), a.getY(), 10, 50);
ball.setBounds(b.getX(), b.getY(), 10, 10);
g.clearRect(0, 0, 600, 300);
g.setColor(Color.white);
g.drawRect(p.getX(), p.getY(), 10, 50);
g.fillRect(p.getX(), p.getY(), 10, 50);
g.drawOval(b.getX(), b.getY(), 10, 10);
g.fillOval(b.getX(), b.getY(), 10, 10);
}
}
它一直有效,直到我编写了这行代码(Ball.java 中的 24 行):
if (board.ball.intersects(board.pPaddle))
我收到错误:
线程“Thread-0”中的异常 java.lang.NullPointerException at Ball$1.run(Ball.java:24) at java.lang.Thread.run(Unknown Source)
我确定 GameBoard.java 中的矩形不是空的。我不知道该怎么办。