我是Java的新手,我正在尝试创建类似乒乓球的游戏。我创建了一个暂停功能,当玩家点击空格键时停止游戏运行。我非常坚持如何做到这一点。现在,当我击中太空时,球停止,但是当我取消暂停时,球比以前快得多。我也非常确定这种做法只是不起作用。如何做任何帮助将非常感激。
这是我的图形类
public class GraphicRender extends JPanel implements ActionListener {
//Object for Random
Random random = new Random();
//Timer on 5ms clock
Timer timer = new Timer(5, this);
//Variables for the coordinates of the player and enemy
public static int paddleLX = 12, paddleLY = 400, paddleLW = 5, paddleLH = 70, paddleLXV, paddleLYV;
public static int ballX = 400, ballY = 400, ballXV, ballYV;
public static boolean gamePaused = false;
//Constructor to initialise objects
public GraphicRender() {
timer.start();
this.setFocusable(true);
this.requestFocusInWindow(true);
//Adds the keyListener
addKeyListener(new GetKeyStroke());
}
//Graphic rendering
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.BLACK);
draw(g);
}
public void draw(Graphics g) {
g.setColor(Color.GRAY);
//Walls
g.fillRect(0, 1, 8, 800);
g.fillRect(0, 1, 800, 8);
g.fillRect(0, 755, 800, 8);
g.fillRect(777, 1, 8, 800);
//Ball
g.setColor(Color.WHITE);
g.fillRect(ballX, ballY, 5, 5);
//Left Paddle
g.fillRect(paddleLX, paddleLY, paddleLW, paddleLH);
}
public void startBall() {
ballXV = -1;
ballX += ballXV;
ballY += ballYV;
repaint();
}
public void startGame() {
gamePaused = false;
startBall();
}
public static void pauseGame() {
gamePaused = true;
}
public void actionPerformed(ActionEvent e) {
if(!gamePaused)
startGame();
if(gamePaused)
pauseGame();
}
}
这是Key Bindings类
package game.util;
import game.render.GraphicRender;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class GetKeyStroke extends KeyAdapter{
public void keyPressed(KeyEvent e) {
GraphicRender gRndObj = new GraphicRender();
if(e.getKeyCode() == KeyEvent.VK_SPACE) {
if(!GraphicRender.gamePaused) {
System.out.println("Game is not paused");
GraphicRender.pauseGame();
}else{
System.out.println("Game is paused");
gRndObj.startGame();
}
}
}
}
我知道这段代码非常混乱,很遗憾
答案 0 :(得分:0)
gamePaused()
方法不应该是静态的。使它成为一个实例变量。stop()
,在Timer对象上调用了start()
。要将一个类的引用传递给另一个类,只需使用诸如构造函数参数之类的参数。例如,
class MyBar {
private MyFoo myFoo;
public MyBar(MyFoo myFoo) {
this.myFoo = myFoo;
}
public void someMethod() {
if (!myFoo.isBazz()) {
myFoo.setBazz(true);
} else {
myFoo.startBazzer();
}
}
}