📄 gamethread.java
字号:
第二章
/*线程类Thread的使用
游戏中仅仅涉及了线程类Thread的最简单应用,在这个最简单的例子中,有几点是需要特别说明的。
本例中,随时发起一个新线程是很必要的。例如游戏的背景动画,即使玩家没有触发任何按钮,它也一直处于移动状态,所以程序必须必须有一个循环逻辑来一直不停重复刷新屏幕,直到游戏结束。游戏设计的逻辑是不能让这个显示循环线程作为主线程,因为主线程必须是系统管理软件可以调用来控制游戏运行或者退出。在对决状态时测试游戏,我发现如果我用循环显示线程做主线程,对手就很难对按键做出及时反应。当然,通常当你计划进入一个将在代码运行整个生命周期做重复展示的循环时,发起一个新线程是一个很好的方法。
请看我的Thread子类的运行逻辑:一旦线程被发起,立刻进入主循环(while代码块)中。
第一个步骤是检查Jump类是否在上一次循环后调用了requestStop(),如果是,循环中断,返回运行run()方法。
否则,如果玩家没有暂停游戏,你要激发GameCanvas响应玩家的击键事件,接着继续游戏的动画效果,这时你需要循环线程一毫秒的暂停。这事实上会引起一帧画面在下一帧展示前会暂时停滞(1毫秒),但这可以使击键事件轮巡任务正常进行。
如上提及,玩家击键信息将被另一个线程修改,所以游戏显示循环需要设置一个短暂的等待,确保这个修改线程排队进入,有机会在极短的一瞬修改按键的状态值。这可以保证玩家按下键盘时得到迅速的响应,这就是游戏设计中常用到的1毫秒的把戏。
Listing 2 是GameThread.java源码。
Listing 2. GameThread.java*/
package net.frog_parrot.jump;
/**
* This class contains the loop that keeps the game running.
*
* @author Carol Hamer
*/
public class GameThread extends Thread {
//---------------------------------------------------------
// Fields
/**
* Whether the main thread would like this thread
* to pause.
*/
private boolean myShouldPause;
/**
* Whether the main thread would like this thread
* to stop.
*/
private boolean myShouldStop;
/**
* A handle back to the graphical components.
*/
private JumpCanvas myJumpCanvas;
//----------------------------------------------------------
// Initialization
/**
* Standard constructor.
*/
GameThread(JumpCanvas canvas) {
myJumpCanvas = canvas;
}
//----------------------------------------------------------
// Actions
/**
* Pause the game.
*/
void pauseGame() {
myShouldPause = true;
}
/**
* Restart the game after a pause.
*/
synchronized void resumeGame() {
myShouldPause = false;
notify();
}
/**
* Stops the game.
*/
synchronized void requestStop() {
myShouldStop = true;
notify();
}
/**
* Start the game.
*/
public void run() {
// Flush any keystrokes that occurred before the
// game started:
myJumpCanvas.flushKeys();
myShouldStop = false;
myShouldPause = false;
while(true) {
if(myShouldStop) {
break;
}
synchronized(this) {
while(myShouldPause) {
try {
wait();
} catch(Exception e) {}
}
}
myJumpCanvas.checkKeys();
myJumpCanvas.advance();
// You do a short pause to allow the other thread
// to update the information about which keys are pressed:
synchronized(this) {
try {
wait(1);
} catch(Exception e) {}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -