我正在制作一个简单的游戏,您可以控制球,并尽可能长时间避开其他移动障碍物,
这个想法是会有一个计时器,它将从0开始,大约10秒后,它将增加移动到另一个级别,更多的移动障碍。
我在创建计时器方面遇到一些问题,这会启动计数,我尝试使用这样做:
public static void timer(){
int count = 0;
while (count<10) {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
count++;
}
System.out.println(count);}}
计时器启动,但由于某种原因,程序不喜欢“线程睡眠”部分,所有图形都从JFrame中分离出来。游戏仍在落后。是否有更好的方法可以做我想做的事情?
更新:下面是我的游戏课程,没有我的计时器attmept:p
public class Game extends JPanel implements ActionListener {
Timer mainT;
User user;
int Obstaclesnum = 5;
int levelnumber = 1;
static ArrayList<Obstacles> obstacles = new ArrayList<Obstacles>();
Random rand = new Random();
public Game() {
setFocusable(true);
user = new User(270,250);
addKeyListener(new Key(user));
mainT = new Timer (10,this);
mainT.start();
startgame();
for (int i=0;i<Obstaclesnum;i++){
addObstacles(new Obstacles(rand.nextInt(600),rand.nextInt(600)));
}}
public void paint(Graphics g){
//paint method
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
user.draw(g2d);
//for obstacles
for (int i=0;i<obstacles.size();i++){
Obstacles obst= obstacles.get(i);
obst.draw(g2d);
}
}
public void actionPerformed(ActionEvent arg0) {
// Action Listener
user.update();
for(int i=0; i <obstacles.size();i++){
Obstacles obst = obstacles.get(i);
obst.update();
}
repaint();
}
public void addObstacles(Obstacles ob){
obstacles.add(ob);
}
public static ArrayList<Obstacles> getObstacles(){
return obstacles;
}
public static void gameOver() {
System.out.println("Game Over!");
System.exit(0);
}
public void startgame () {
Obstaclesnum= levelnumber *1;
for (int i=0;i<Obstaclesnum;i++){
addObstacles(new Obstacles(rand.nextInt(100),rand.nextInt(600)));
}}}
答案 0 :(得分:0)
我不确定这是否对您有所帮助,但在这里您有一个简单的可运行计时器。
public class Timer implements Runnable {
private final int sec;
public Timer(int sec) {
this.sec = sec;
run();
}
@Override
public void run() {
int count = sec;
while (count > 0) {
System.out.println(count);
//here you can put your method to start the game.
count--;
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
答案 1 :(得分:0)
是的,您可以在计时器功能中添加一个标志变量。如果你只是试图延迟某事的动作,请在你的actionPerformed中尝试这样的事情
if (counter != 0) {
counter++;
if (counter == 10) { // count to 10ms
counter = 1;
// whatever action you want done after the delay
}
} else {
counter = 0;
}