我创建了一个菜单,其中包含一些可供选择的选项。其中一个选项是启动游戏的“玩电脑”。
JButton ai = new JButton("Play with computer");
ai.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
GameBoard play = new GameBoard();
hi.dispose(); //jframe
}
});
然后是游戏板:
@SuppressWarnings("serial")
public class GameBoard extends Canvas {
private Image dbi;
private Graphics db;
private JFrame okno;
Rectangle aiPaddle = new Rectangle(10, 590, 10, 50);
Rectangle pPaddle = new Rectangle(10, 100, 10, 50);
Rectangle ball = new Rectangle(560, 10, 10, 10);
Player p = new Player(this);
Ai a = new Ai(this);
Ball b = new Ball(this);
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) {
dbi = createImage(10, 50);
db = dbi.getGraphics();
paint(db);
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);
g.drawRect(a.getX(), a.getY(), 10, 50);
g.fillRect(a.getX(), a.getY(), 10, 50);
}
@Override
public void paint(Graphics g) {
pPaddle = new Rectangle(p.getX(), p.getY(), 10, 50);
aiPaddle = new Rectangle(a.getX(), a.getY(), 10, 50);
ball = new Rectangle(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);
g.drawRect(a.getX(), a.getY(), 10, 50);
g.fillRect(a.getX(), a.getY(), 10, 50);
}
}
我确信它应该工作,但它没有。我得到黑屏,没有任何矩形或椭圆形。其他课程的线程正在工作,因为我仍然输掉了比赛。:)