import java.awt.*; import java.awt.event.*; import java.util.Timer; import javax.swing.*; public class gameone { Frame frame = new Frame(); //桌面宽高 private final int table_width = 300; private final int table_hight = 400; //球拍宽高 private final int racket_width = 300; private final int racket_hight = 400; //小球大小 private final int ball_size = 16; //小球位置 private int ballX = 120; private int ballY = 20; //小球速度 private int speedX = 10; private int speedY = 5; //球拍位置 private int racketX = 120; private final int racketY = 340; private boolean isOver = false; private Timer timer; private class MyCanvas extends Canvas{ @Override public void paint(Graphics g) { if(isOver){ g.setColor(Color.BLUE); g.setFont(new Font("Times",Font.BOLD,30)); g.drawString("Game Over!",50,200); } else{ g.setColor(Color.RED); g.fillOval(ballX,ballY,ball_size,ball_size); g.setColor(Color.PINK); g.fillRect(racketX,racketY,racket_width,racket_hight); } } } MyCanvas drawArea = new MyCanvas(); public void init(){ KeyListener listener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if(keyCode == KeyEvent.VK_LEFT){ if(racketX > 0){ racketX -= 10; } } if(keyCode == KeyEvent.VK_RIGHT){ if(racketX < (table_width - racket_width)) racketX += 10; } } }; frame.addKeyListener(listener); drawArea.addKeyListener(listener); ActionListener task = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(ballX <= 0 || ballX >= (table_width - ball_size)) speedX = -speedX; if(ballY <= 0 || ballY >= racketY - ball_size && ballX > racketX && ballX <racketX +racket_width){ speedY = -speedY; } if(ballY > racketY - ball_size && (ballX < racketX || ballX > racketX + racket_width)) { timer.stop(); isOver = true; drawArea.repaint(); } ballX += speedX; ballY += speedY; drawArea.repaint(); } }; timer = new Timer(100,task); timer.start(); drawArea.setPreferredSize(new Dimension(table_width,table_hight)); frame.add(drawArea); frame.pack(); frame.setVisible(true); } public static void main(String[] args){ new gameone().init(); } }哪里错了
时间: 2023-06-09 08:05:08 浏览: 211
飞机大战java教程.docx
我明白您在问一个Java代码段。这是一个简单的Java游戏,包括一个球和一个球拍。在这个游戏中,你可以使用键盘控制球拍的位置和移动方向。这个游戏有一个定时器,它定期移动球的位置。当球松开时,球会反弹回来。当球撞击球拍时,球会反弹回去,如果球没有被击中,则游戏结束。看起来这是一个不完整的代码段,还有部分代码被截去了。我希望我的解释可以帮助你更好地理解这个Java代码段。
阅读全文