• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Nicholas Kong

Game Loop locking up my game

8 posts in this topic

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

[url=http://s33.photobucket.com/user/warnexus/media/menusystem-1_zps04f28801.png.html]menusystem-1_zps04f28801.png[/URL]

 

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 :

[url=http://s33.photobucket.com/user/warnexus/media/residuePNG_zps2f04cbce.jpg.html]residuePNG_zps2f04cbce.jpg[/URL]

 

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:

[url=http://s33.photobucket.com/user/warnexus/media/healthsystem2_zps5b042882.png.html]healthsystem2_zps5b042882.png[/URL]

Edited by warnexus
0

Share this post


Link to post
Share on other sites

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.

1

Share this post


Link to post
Share on other sites

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?

Edited by warnexus
0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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. 

0

Share this post


Link to post
Share on other sites

'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.

0

Share this post


Link to post
Share on other sites

'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.

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0