I am writing a game for a CS class.
There is a GUI MyDisplay which is an extended KeyListener with a JFrame with a packed JPanel[][] for an instance variable.
MyGame has a private enum called GameState which is either MENU, PLAY, QUIT, or PAUSE. MyGame has the static void main method which has the following construct:
MyGame is as follows:
public class MyGame
{
/* Private instance fields and constructor left out.
Constructor initializes a MyDisplay and state = MENU */
public static void main(String[] args)
{
MyGame g = new MyGame();
while(true)
{
gstate = g.getState();
if(gstate == GameState.PLAY)
g.play();
else if(gstate == GameState.PAUSE)
g.pause();
else if(gstate == GameState.MENU)
g.menu();
}
}
/* implementation of MyGame methods */
}
Where play, pause, and menu invoke various calls to MyDisplay to draw new stuff. The only way the state can change is if the user presses enter. Then, MyDisplay calls a MyGame method called enterPressed which changes the state accordingly.
When I compile this, the game does not behave normally. When I press enter (and print out the state to check), I notice, as it should, that MENU changes to PLAY. But even though the state is in PLAY, g.play() is not being evaluated (I tested whether or not the console printed out a test phrase in an added line of code in play()).
But what really confuses me is that when I enter any call to System.out, such as System.out.print(""); in the while loop of main, everything works fine, and g.play() gets called as it should.
You are hitting a thread starvation case. Because your initial state is
MENUthe loop consumes all the cpu, and the UI doesn’t have the chance to consume your key press event.Try with a small sleep in your while, like:
sleep(10)Here you will find more informations and a lot of alternatives, even a
Timeris much more CPU friendly, but there are better ways, depends on your game logic.