Game Loop locking up my game

Started by
7 comments, last by Nicholas Kong 11 years ago

Code is in Java and I am using the javaxswing library.

I have an issue where my game loop is preventing several things from happening:

1) My health system does not show up. Instead, there is a graphical residue from the main menu system of the game that replaces where the health system should be.

2) My ship cannot move using arrow keys anymore.

3) Application cannot close even if I press the x button. No matter how many times I click the x button, the game window does not disappear.

The reason why I know the problem is coming from the game loop is because when I do not execute game loop which is the Game class run method. My health system does show up and I can close the game. The Game constructor loads all the game object beforehand and the game loop does several things: draw update and wait .

I like to also mention the program looks for main method in the main class which is loads the menu system. Once the user clicks on new game(this is when the game loads the game object from the constructor and runs the game loop. this is where the problems mentioned above start to happen.

The code that is suppose to close the x button is in the GameMenuSystem class(which is not included in the post) I thought I point this out.

Nested Class Code from the Main Menu System Class


 
// a nested button class for the game menu class
private class NewGameButton extends JButton implements MouseListener{
 
public NewGameButton(String text){
 
// initialize the JButton
super();
setText(text);
/* 
* important to add mouselistener once you
* implement the mouselistener interface
*/
addMouseListener(this);
}
@Override
public void mouseClicked(MouseEvent e) {
// remove the art label from menuPanel
// menuPanel.removeAll();
// remove all the button from the buttonPanel
// buttonPanel.removeAll();
 
getGamePanel().remove(menuPanel);
getGamePanel().remove(buttonPanel);
 
stopMenuMusic();
 
 
 
// redraw the panel after removing panels
// from the gamePanel
 
 
// you need to repaint the gamePanel once you make
// chances to it like removing panels from it to
// see the new changes! 
getGamePanel().repaint();
 
/* add the game to the gamePanel
* once the user presses the new game button
* the Game Class will setup the scene for the
* the game
*/
Game.getInstance().run();
 
 
 
}
 

Code from the Game Class. Constructor loads objects beforehand, game loop does the draw, update and wait and performs object management:


 
// Singleton pattern get instance
public static Game getInstance(){
 
if (instance == null){
instance = new Game();
 
}
return instance;
 
}
 
private Game(){
 
// make the singleton pattern play nice
// without instance = this causes the game not 
// to be able to set up
instance = this;
 
// add ship to game
double ship_SpawnPosition_X = 230;
double ship_SpawnPosition_Y = 380;
ship = new Ship(ship_SpawnPosition_X, ship_SpawnPosition_Y);
 
 
 
shipHealthSystem = new ShipHealthSystem(ship);
 
// set up ship health system
shipHealthSystem.setUpShipHealthSystem();
 
// move and resize the canvas
setBounds(0,0,width,height);
 
// add canvas to panel
GameMenuSystem.gamePanel.add(this,BorderLayout.CENTER);
 
 
/*
* this is important! Even though we pack
* once for the game menu if you add
* a new panel like for example the game's
* health system you need to pack it again 
* otherwise the health system does not show up
* important 
* 
* add everything in the JPanel before packing!
*/
GameMenuSystem.container.pack();
 
// manually control repainting the screen
setIgnoreRepaint(true);
 
 
// create the buffer strategy from the canvas class
// one is for the drawing off-screen
// and the other is for drawing on screen
createBufferStrategy(2);
// get the buffer strategy
strategy = getBufferStrategy();
// run the game
isRunning = true;
 
// the moment in time when the game scene is created
lastTick = System.currentTimeMillis();
 
// this will track all the gameComponent objects that need updating and drawn
gameObjects = new ArrayList<GameComponent>();
 
// track the dynamic objects so we don't invalid  our list iterator
objectsToAdd = new ArrayList<GameComponent>();
 
objectsToRemove = new ArrayList<GameComponent>();
 
// loads background music
loadMusic();
 
add(ship);
 
 
 
int offSet = 135;
// create a row of ghosts
for(int row = 0;row < getWidth() ;row += offSet  )
{
Ghost ghost = new Ghost(row,0);
add(ghost);
 
}
 
 
 
 
addKeyListener(this);
 
// this might be needed
GameMenuSystem.getGamePanel().repaint();
 
}
 


public void run(){
 
// loop background music
playLoopedBackgroundMusic();
 
// basic game loop that keeps looping
while(!isLooping)
{
 
// the state of the game can be paused pressing P and un-paused
// pressing U
if(isRunning){
 
 
// calculate the time since the last loop
 
// the difference is the current time
// the current time - the previous time is the current time
long milliseconds = System.currentTimeMillis() - lastTick;
lastTick = System.currentTimeMillis();
 
// set the focus to the panel
gamePanel.requestFocus();
 
// get graphics context
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
clearBuffer(g);
 
// update all game items
for(GameComponent component : gameObjects){
component.update(milliseconds);
 
}
 
// handle the dynamic objects
addNewGameComponents();
removeOldGameComponents();
 
// draw all game items
for(GameComponent component: gameObjects){
component.draw(g);
}
 
// collision detection checks of the game
for(GameComponent component: gameObjects){
if(component instanceof Laser)
{
((Collidable) component).collide(gameObjects);
 
}
if(component instanceof GhostLightningSkill)
{
 
((Collidable) component).collide(gameObjects,shipHealthSystem);
 
}
 
} 
 
flipBuffer(g);
 
// pause for a bit so we don't consume 100% CPU
try 
{ 
Thread.sleep(10);
}
catch (Exception e) 
{
 
}
 
}
 
}
}
 
public void clearBuffer(Graphics2D g){
 
g.setColor(Color.BLACK);
g.fillRect(0,0,getWidth(),getHeight());
}
 
public void flipBuffer(Graphics2D g){
// flip the buffer
g.dispose();
strategy.show();
 
}

Main Menu System

menusystem-1_zps04f28801.png

This called using Game.getInstance().run() in the NewGameButton Class.

Once user clicks New Game, bad stuff happens, the upper graphical residue is same as the one from the main menu, ship cannot move, collision works fine though :

residuePNG_zps2f04cbce.jpg

If I call Game.getInstance() instead of Game.getInstance.run() in the NewGameButton class, my health system shows up which also allows me to close the program because I am only calling the Game constructor:

healthsystem2_zps5b042882.png

Advertisement

Seems you start and set the game running (basically an eternity loop until members isLooping && isRunning is set to false) from the onMouseClick. OnMouseClick is probably called by some thread in Swings complex thred/event handling mechanism and you freeze it with your game loop.

I would suggest that in event callback methods called by Swing you just set flags which hits the Game class what to do and then handle those flags in the main game loop instead.

Seems you start and set the game running (basically an eternity loop until members isLooping && isRunning is set to false) from the onMouseClick. OnMouseClick is probably called by some thread in Swings complex thred/event handling mechanism and you freeze it with your game loop.

I would suggest that in event callback methods called by Swing you just set flags which hits the Game class what to do and then handle those flags in the main game loop instead.

event callback methods? You mean the mouseClicked method? Am I suppose to removeMouseListener of the buttons when the game is looping too? Is calling getInstance() in the mouseClicked wrong by any chance?

Have you tried implementing game states as I recommended before? I am sure it will fix all, if not most of your problems, and will result in a much cleaner code. Essentially, your game will be divided into different states. Your menu will be one state, and your game another state. Each state will have its own set of input, logic, and render functions. Your main game loop will exist outside of these states and will perform input, logic, and render functions of the active state. Your game will start by performing the game loop functions of the menu state, and when you click "new game", it will switch to the game loop functions of the game state.

You'll have to look up some tutorials on how to implement game states in Java.

Have you tried implementing game states as I recommended before? I am sure it will fix all, if not most of your problems, and will result in a much cleaner code. Essentially, your game will be divided into different states. Your menu will be one state, and your game another state. Each state will have its own set of input, logic, and render functions. Your main game loop will exist outside of these states and will perform input, logic, and render functions of the active state. Your game will start by performing the game loop functions of the menu state, and when you click "new game", it will switch to the game loop functions of the game state.

You'll have to look up some tutorials on how to implement game states in Java.

I'm confused as to why you mention a game loop functions in the menu state because in the menu, the menu class and the buttons themselves have mouse-listeners which mean asynchronous events. Having a loop with mouse listeners looks a bit out of place.

'm confused as to why you mention a game loop functions in the menu state because in the menu, the menu class and the buttons themselves have mouse-listeners which mean asynchronous events. Having a loop with mouse listeners looks a bit out of place.

Yes, it probably doesn't make much sense since the "menu state" isn't doing much that would occur in a game loop. But what if you wanted to add animation to the menu screen, or make something happen after the player waited a certain length of time? You would have to update the screen and logic the same way the loop for the game state does. When you're using a state machine, each state needs to function the same way in the game loop.

In any case, this is only if you wish to implement game states to your game, which as I mentioned, would solve a lot of problems you're having (since your problems seem to stem from switching from one screen to another). You may not need to add game states if your game is small, but they become important (and even necessary) for larger games that have multiple states such as an intro screen, title screen, stage select, game screen, credits, etc.

'm confused as to why you mention a game loop functions in the menu state because in the menu, the menu class and the buttons themselves have mouse-listeners which mean asynchronous events. Having a loop with mouse listeners looks a bit out of place.

Yes, it probably doesn't make much sense since the "menu state" isn't doing much that would occur in a game loop. But what if you wanted to add animation to the menu screen, or make something happen after the player waited a certain length of time? You would have to update the screen and logic the same way the loop for the game state does. When you're using a state machine, each state needs to function the same way in the game loop.

In any case, this is only if you wish to implement game states to your game, which as I mentioned, would solve a lot of problems you're having (since your problems seem to stem from switching from one screen to another). You may not need to add game states if your game is small, but they become important (and even necessary) for larger games that have multiple states such as an intro screen, title screen, stage select, game screen, credits, etc.

I see I will do research on game states. Thanks.

Have you looked at these:

http://www.gamedev.net/page/resources/_/technical/general-programming/java-games-active-rendering-r2418

http://www.gamedev.net/page/resources/_/technical/general-programming/java-games-keyboard-and-mouse-r2439

I think, therefore I am. I think? - "George Carlin"
My Website: Indie Game Programming

My Twitter: https://twitter.com/indieprogram

My Book: http://amzn.com/1305076532

Have you looked at these:

http://www.gamedev.net/page/resources/_/technical/general-programming/java-games-active-rendering-r2418

http://www.gamedev.net/page/resources/_/technical/general-programming/java-games-keyboard-and-mouse-r2439

Thanks Glass-Knife! Great resources. I will use it as leverage.

This topic is closed to new replies.

Advertisement