Generating Action with Tasks
So far everything in our game server has been reactive. A client sends a message, the server handles that message with an appropriate response. This works fine for certain games like card games or board games where user action is the only thing that changes the state of the game. However, in many types of games, the game itself modifies the game state as time passes, even in the absence of user input. For example, in a space simulation, the spaceships, asteroids and aliens all have velocities. As time passes, all of these things move, regardless of whether the clients have sent commands or not. Furthermore, in these action oriented games, the state of the game world is sent back to the client periodically (usually 30 times per second or so), so that the client can display the evolving game state. These sorts of server-initiated actions are called "tasks" in Darkstar. The application server provides support for easily creating either one-time or periodic tasks. Tasks are used in Darkstar instead of user-created threads. Letting the server manage concurrency allows the server to optimize scheduling and possibly distribute load onto different CPUs or servers.
Creating and Running Tasks
The Task
interface is quite similar to
java.lang.Runnable
. They both require a user to
implement a single run()
method which takes no
parameters. However, there are several important differences between
Task
objects and Runnable
objects.
First, Task
's run method can throw any ...
Get Darkstar: The Java Game Server now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.