Java Video Game Programming: Game Logic

CodeSpells, an immersive, first-person player video game designed to teach students in elementary to high school how to program in the popular Java language, has been developed by University of California, San Diegocomputer scientists.

In simple video games, there is usually some object in the game that does most of the “thinking” with respect to the game’s rules. In a game like Pong or Breakout, the ball does most of the “thinking”. The paddles move according to user input, but they don’t really need to know if they’ve collided with anything in the game (their own logic keeps them from moving off the playfield.) The bricks don’t need to know anything about what’s going on, they just need to hang around, then disappear when something tells them to, and perhaps return some information about what score they’re worth, if there are different scores for hitting different bricks.

The ball, however, is a more active participant in the game. It needs to know about collisions, respond to the other objects in the game, and generally know what’s going on. In other words, it is the object that keeps track of most of the game rules. In a video game, this is referred to as the game logic.

A bouncing ball in the simple Java video game kernel program.

This simple kernel improves on the original. Turn it into your own Pong, Breakout, or Tank clone.

In the example below I’ve made a Ball class. This is where most of the game’s logic will reside. Here it is in the ball’s move() method. Since the ball will need access to inside information about the playfield and the objects on it, I’ve made it an inner class of the playfield’s class (VGKernel.) As an inner class, it has access to all of VGKernel’s members and methods as if it owned them itself. This simplifies the program a lot.

Here is the modified version of the video game kernel. Changes from the original have been highlighted:

Now the ball not only is its own class, it has a more sophisticated means of keeping track of its direction of movement (xVel and yVel, tracking velocity as a positive or negative value, as opposed to the simple right and down booleans in the original.) This means that logic in the game could vary the velocity of the ball easily, as well as change its direction of movement.