我正在用 Java 创建一个简单的网络游戏,玩家可以在其中使用键盘键移动块。游戏将在本地服务器上运行,并且有一个基本规则:
Each block will move automatically at 1 FPS rate, but the **user can send several move
commands** in this 1 second interval, thus updating the block position.
代码几乎完成了,但是在服务器和客户端之间同步事情时遇到了麻烦。这是我需要更好地理解的一些代码/描述:
基础班
class Server{
ServerSocket server = new ServerSocket(port);
while (listening) {
Socket client = server.accept();
new Thread(new ClientHandler(client)).start();
}
}
class Game implements Runnable {
public void run() {
while (! gameOver)
tick();
}
}
现在的问题
class ClientHandler implements Runnable
{
Game game;
public ClientHandler(Socket client)
{
this.client = client;
//start game which runs at 1 FPS
long FPS = 1000L;
Timer timer = new Timer();
timer.schedule(new Game(FPS), 0L, FPS);
}
public void run()
{
/** Game is already running, needs to:
*
* 1 - Take any GameInput object from the user and update the game
* 2 - Send a GameState object to the user
* 3 - Client will receive it and render on screen,
* (hopefully in a synch state with the server)
*/
while ( ! game.gameOver)
{
//ObjectInputStream ois = ...;
// Line A
GameInput command = ois.readObject();
// Line B
//GameState state = game.update(command);
//ObjectOutputStream oos = ...;
// Line C
oos.writeObject(state);
}
}
}
我需要更好地理解的是如何处理Line A
,Line B
和Line C
。更准确地说:
1 - 以安全的方式更新游戏线程的好方法是什么?
2 - 我如何处理多个命令?可能是队列?
2 - 如何确保客户端和服务器同步?
我是网络编程的新手,所以感谢您的帮助!