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
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 :
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: