我正在做一个Snake克隆,在开始新游戏之前一切正常。一切都有效,但一切都是双倍的速度!我想这是因为有两个定时器同时工作相同的功能?我找不到如何处理这个问题的方法。这就是我的计时器看起来像你可以看到的,它是非常凌乱的:/甚至没有试图找出它。我的蛇包括球,大部分代码跟踪他们的运动。
public class Draw extends JPanel implements KeyListener{
static ArrayList x = new ArrayList(); //the x coordinates of balls
static ArrayList y = new ArrayList(); //the y coordinates of balls
static int x_val=15; // movement x-axis
static int y_val=0; // movement y-axis
static boolean ballCoordinatesDone = false; //initialize balls
static int score = 0;
static boolean snakeCrashed = false; //if snake has crashed (stop)
static boolean highscoresOpened = false; //if highscores are opened already (don't repeat)
static int foodx = 0; //food x coordinate
static int foody = 0; //food y coordinate
Timer t = new Timer(150, new ActionListener(){
public void actionPerformed(ActionEvent e){
if(snakeCrashed == false){
if(ballCoordinatesDone == false){
ballCoordinates();
}
ballCoordinatesDone = true;
int lastX = Integer.parseInt((String) x.get(x.size()-1)); //gets x coodinate for first ball
int lastY = Integer.parseInt((String) y.get(y.size()-1)); //gets y coodinate for first ball
int a;
//checks if snake collides with itself
for(a=0; a < x.size(); a++){
if(lastX + x_val == Integer.parseInt((String) x.get(a)) && lastY + y_val == Integer.parseInt((String) y.get(a))){
snakeCrashed = true;
}
}
//checks if snake goes out of bounds
if(lastX + x_val < 5 || lastY + y_val < 50 || lastX + x_val >= 310 || lastY + y_val >= 355 ){
snakeCrashed = true;
}else{
//adds a new ball in direction of movement (new head)
x.add("" + (lastX + x_val));
y.add("" + (lastY + y_val));
}
//checks if you hit a food
if(lastX + x_val == foodx && lastY + y_val == foody){
foodRandomizer();
score+=10;
}else{
//removes the tail
if(snakeCrashed == false){
x.remove(0);
y.remove(0);
}
}
repaint();
//if snakeCrashed == true
}else{
if(highscoresOpened == false){
CreateGUI.highscoreFrame();
highscoresOpened = true;
t.stop();
}
}
}
});
然后CreateGUI.highscoreFrame有一个名为newGame的按钮,如下所示:
JButton newGame = new JButton("New Game");
newGame.setBounds(75,300,100,40);
newGame.setVisible(true);
newGame.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hsFrame.setVisible(false);
hsFrame.dispose();
submitHSFrame.setVisible(false);
submitHSFrame.dispose();
snake.setVisible(false);
snake.dispose();
Draw.snakeCrashed = false;
Draw.highscoresOpened = false;
Draw.x.clear();
Draw.y.clear();
Draw.score = 0;
Draw.x_val=15;
Draw.y_val=0;
Draw.ballCoordinatesDone = false;
Draw.score = 0;
CreateGUI ng = new CreateGUI();
}
});
hsFrame.add(newGame);
答案 0 :(得分:0)
每个Draw对象都会创建一个新计时器,让游戏同时运行n次,但游戏副本共享状态,因为ir存储在静态变量中,因此状态更新速度比它快n-1倍应该。
您可以停止计时器this way,也可以每次使用静态计时器和schedule/cancel the task。