7 Replies Latest reply: Feb 25, 2011 10:19 AM by 841284 RSS

    Java Game Development Problem.

    841284
      When I run my project, it does 2 frames of a animation and then it just freezes. I don't know what's wrong and I would like help. Here are the peices of code I have:
      The core:
      import java.awt.*;
      
      public abstract class CoreClass {
           
           private static DisplayMode modes[] = {
                new DisplayMode(1366,768,32,0),
                new DisplayMode(1366,768,24,0),
                new DisplayMode(1366,768,16,0),
                new DisplayMode(800,600,32,0),
                new DisplayMode(800,600,24,0),
                new DisplayMode(800,600,16,0),
                new DisplayMode(640,400,32,0),
                new DisplayMode(640,400,24,0),
                new DisplayMode(640,400,16,0),
                
           };
           private boolean running;
           protected ScreenManager s;
           
           //stop method
           public void stop(){
                running = false;
           }
           
           //call init and gameloop
           public void run(){
                try{
                     init();
                     Creating();
                     gameLoop();
                }finally{
                     s.restoreScreen();
                }
           }
           
           //set to full screen
           public void init(){
                s = new ScreenManager();
                DisplayMode dm = s.findFirstCompatibleMode(modes);
                s.setFullScreen(dm);
                
                Window w = s.getFullScreenWindow();
                w.setFont(new Font("Arial", Font.PLAIN,20));
                w.setBackground(Color.GREEN);
                w.setForeground(Color.WHITE);
                running = true;
           }
           
           //main gameLoop
           public void gameLoop(){
                long cumTime = System.currentTimeMillis();
                
                while(running){
                     long timePassed = System.currentTimeMillis();
                     cumTime += timePassed;
                     
                     update(timePassed);
                     
                     Graphics2D g = s.getGraphics();
                     draw(g);
                     g.dispose();
                     s.update();
                     
                     try{
                          Thread.sleep(20);
                     }catch(Exception ex){
                          System.out.print("Error...");
                     }
                }
           }
           
           //update animation
           public void update(long timePassed){
           }
           
           //draws to screen
           public abstract void draw(Graphics2D g);
           
           public void Creating(){
                Thread creator = new Thread(new Creator());
                creator.run();
           }
      }
      The runner of the core:
      import java.awt.Graphics2D;
      
      public class Runner extends CoreClass implements KeyListener{
           
           public static void main(String[] args){
                new Runner().run();
           }
           
           public void init(){
                super.init();
                Window w = s.getFullScreenWindow();
                w.setFocusTraversalKeysEnabled(false);
                w.addKeyListener(this);
           }
      
           //draw
           public synchronized void draw(Graphics2D g){
                Window w = s.getFullScreenWindow();
                g.setColor(w.getBackground());
                g.fillRect(0, 0, s.getWidth(), s.getHeight());
           }
      
           public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                if(keyCode == KeyEvent.VK_ESCAPE){
                     stop();
                }else{
                     e.consume();
                }
           }
      
           public void keyReleased(KeyEvent e) {
                e.consume();
           }
      
           public void keyTyped(KeyEvent e) {
                e.consume();
           }
           
      }
      The screen maker:
      import java.awt.*;
      import java.awt.image.BufferStrategy;
      import java.awt.image.BufferedImage;
      import javax.swing.JFrame;
      
      public class ScreenManager {
           
           private GraphicsDevice vc;
           
           //give VC access to monitor screen
           public ScreenManager(){
                GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
                vc = e.getDefaultScreenDevice();
           }
           
           //get all compatible DM
           public DisplayMode[] getCompatibleDisplayModes(){
                return vc.getDisplayModes();
           }
           
           //compares DM passed in to VC DM and see if they match
           public DisplayMode findFirstCompatibleMode(DisplayMode modes[]){
                DisplayMode goodModes[] = vc.getDisplayModes();
                for(int x=0;x<modes.length;x++){
                     for(int y=0;y<goodModes.length;y++){
                          if(displayModesMatch(modes[x], goodModes[y])){
                               return modes[x];
                          }
                     }
                }
                return null;
           }
           
           //get current DM
           public DisplayMode getCurrentDisplayMode(){
                return vc.getDisplayMode();
           }
           
           //check if two modes match each other
           public boolean displayModesMatch(DisplayMode m1, DisplayMode m2){
                if(m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight()){
                     return false;
                }
                if(m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth()){
                     return false;
                }
                if(m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate()){
                     return false;
                }
                return true;
                     
           }
           
           //make frame full screen
           public void setFullScreen(DisplayMode dm){
                JFrame f = new JFrame();
                f.setUndecorated(true);
                f.setIgnoreRepaint(true);
                f.setResizable(true);
                vc.setFullScreenWindow(f);
                
                if(dm != null && vc.isDisplayChangeSupported()){
                     try{
                          vc.setDisplayMode(dm);
                     }catch(Exception ex){
                          System.out.print("Error");
                     }
                }
                f.createBufferStrategy(2);
           }
           
           //we will set Graphics object = to this
           public Graphics2D getGraphics(){
                Window w = vc.getFullScreenWindow();
                if(w != null){
                     BufferStrategy s = w.getBufferStrategy();
                     return(Graphics2D)s.getDrawGraphics();
                }else{
                     return null;
                }
           }
           
           //updates display
           public void update(){
                Window w = vc.getFullScreenWindow();
                if(w != null){
                     BufferStrategy s = w.getBufferStrategy();
                     if(!s.contentsLost()){
                          s.show();
                     }
                }
           }
           
           //returns full screen window
           public Window getFullScreenWindow(){
                return vc.getFullScreenWindow();
           }
           
           //get width of window
           public int getWidth(){
                Window w = vc.getFullScreenWindow();
                if(w != null){
                     return w.getWidth();
                }else{
                     return 0;
                }
           }
           
           //get height of window
           public int getHeight(){
                Window w = vc.getFullScreenWindow();
                if(w != null){
                     return w.getHeight();
                }else{
                     return 0;
                }
           }
           
           //get out of full screen
           public void restoreScreen(){
                Window w = vc.getFullScreenWindow();
                if(w != null){
                     w.dispose();
                }
                vc.setFullScreenWindow(null);
           }
           
           //create image compatible with monitor
           public BufferedImage createCompatibleImage(int w, int h, int t){
                Window win = vc.getFullScreenWindow();
                if (win != null){
                     GraphicsConfiguration gc = win.getGraphicsConfiguration();
                     return gc.createCompatibleImage(w,h,t);
                }
                return null;
           }
           
           
      }
      The creator:
      public class Creator implements Runnable {
           
           ScreenManager s = new ScreenManager();
           
           public void creator(String what){
                if (what.equalsIgnoreCase("human")){
                     Human human = new Human();
                     human.create(s.getCurrentDisplayMode(), 600, 500);
                }else if (what.equalsIgnoreCase("zombie")){
                     Zombie zombie = new Zombie();
                     zombie.create(s.getCurrentDisplayMode(), 124, 246);
                }else{
                     System.out.println("error");
                }
           }
      
           public void run() {
                creator("human");
                creator("zombie");
           }
      
      }
      The human(The zombie is basicly a copy of the human):
      import java.awt.*;
      import javax.swing.ImageIcon;
      
      public class Human {
           
           int y;
           int x;
           private ScreenManager s = new ScreenManager();
           private HumanAnimation animation = new HumanAnimation();
           public void loadpics(){
                Image human1 = new ImageIcon("C:\\Users\\Rick new\\Desktop\\Zombie Attack! images\\human.1.png").getImage();
                Image human2 = new ImageIcon("C:\\Users\\Rick new\\Desktop\\Zombie Attack! images\\human.2.png").getImage();
                
                animation.addScene(human1, 250);
                animation.addScene(human2, 250);
           }
           
           //main movie loop
           public void movieLoop(){
                long cumTime = System.currentTimeMillis();
                
                while(true){
                     long timePassed = System.currentTimeMillis() - cumTime;
                     animation.update(timePassed);
                     Graphics g = s.getFullScreenWindow().getGraphics();
                     draw(g);
                     g.dispose();
                }
           }
           
           //draw method
           public void draw(Graphics g){
                g.drawImage(animation.getImage(),this.y,this.x,null);
           }
           
           //main engine to run
           public void create(DisplayMode dm,int x,int y){
                loadpics();
                movieLoop();
                this.x = x;
                this.y = y;
           }
           
      }
      And finally the human animation(again the zombie animation is the samish thing):
      import java.awt.Image;
      import java.util.ArrayList;
      
      public class HumanAnimation {
           
           private ArrayList<OneScene> scenes;
           private int sceneIndex;
           private long totalTime;
           private long movieTime;
           
           //Constructor
           public HumanAnimation(){
                scenes = new ArrayList<OneScene>();
                totalTime = 0;
                start();
           }
           
           //add scene to ArrayList and set time for each scene
           public synchronized void addScene(Image image, long time){
                totalTime += time;
                scenes.add(new OneScene(image, totalTime));
           }
           
           //start animation from beginning
           public synchronized void start(){
                movieTime = 0;
                sceneIndex = 0;
           }
           
           //change scenes
           public synchronized void update(long timePassed){
                if (scenes.size()>1){
                     movieTime += timePassed;
                     if(movieTime >= totalTime){
                          movieTime = 0;
                          sceneIndex = 0;
                     }
                     while(movieTime > getScene(sceneIndex).endTime){
                          sceneIndex++;
                     }
                }
           }
           
           //get animations current scene(AKA image)
           public synchronized Image getImage(){
                if(scenes.size() == 0){
                     return null;
                }else{
                     return getScene(sceneIndex).pic;
                }
           }
           
           //get scene
           private OneScene getScene(int x){
                return (OneScene)scenes.get(x);
           }
           
           //private inner class
           private class OneScene{
                Image pic;
                long endTime;
                
                public OneScene(Image pic, long endTime){
                     this.pic = pic;
                     this.endTime = endTime;
                }
           }
      }
      Hopefully you can help me with this issue. Thanks! If you have any requests/questions, just ask me.

      Edited by: user13573131 on Feb 24, 2011 1:35 PM
        • 1. Re: Java Game Development Problem.
          gimbal2
          Classic debugging trick then: pepper the code with System.out.println() statements to see what is being invoked and what not. From there you can start to reason WHY the code is not doing what you are expecting.


          Btw: why are you using a thread? Your program is now basically doing this:

          THREAD 1: wait for THREAD 2 to finish
          THREAD 2: game logic


          EDIT: I'm mistaken, you are not using a thread at all.
          creator.run();
          That will not start a new Thread; Thread.start() does.
          • 2. Re: Java Game Development Problem.
            841284
            Thank you. I will try it out.

            The thread stuff was just made by me messing around with the program trying to fix it.

            EDIT: I found out that the code just goes to the movieloop animation and just stays there forever. I had a feeling this would happen and that's why I tried adding a thread.

            Edited by: user13573131 on Feb 24, 2011 10:03 AM
            • 3. Re: Java Game Development Problem.
              jduprez
              EDIT: I found out that the code just goes to the movieloop animation and just stays there forever
              Yes. Have you found out why?

              You're using a while(condition), so the loop will only exit if the condition holds false, or if the loop body executes a break; .
              Now, inspect your condition expression :o)
              • 4. Re: Java Game Development Problem.
                jduprez
                Please use {noformat}
                {noformat} tags when posting code, as explained in the sticky post at the top of this forum's topic listing.
                That makes the code formatted and readable:
                class FormattedCode extends Code implements Readable {
                ...
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
                • 5. Re: Java Game Development Problem.
                  841284
                  I know what the while loop does. I need it to keep my animation running.

                  I will tag my code with
                   right now...
                  
                  EDIT: Added the code stuff.
                  
                  Edited by: user13573131 on Feb 24, 2011 1:40 PM                                                                                                                                                                                                                                                                                                                                                                                                                
                  • 6. Re: Java Game Development Problem.
                    gimbal2
                    user13573131 wrote:
                    The thread stuff was just made by me messing around with the program trying to fix it.
                    Then the next time please make the effort to take it out again before posting. Explain your problem as clearly as possible; leaving in dummy code is the complete opposite wouldn't you agree?
                    • 7. Re: Java Game Development Problem.
                      841284
                      Yes, that's true. Well so I think your looking for a explanation of what the code does and what is the problem but I'm not sure if that's what you where asking.

                      So, I will start with the problem because that's all I can remeber ATM. It does the code all right and then it goes and makes the animation forever and ever. It needs to do another task but it just stays in the while loop which I need for doing my animation.

                      My code starts by doing stuff that just need to be done(init) and then creates a human. My code makes a human appear on the screen and do a walking animation. There it stays and after that is supposed to make a green background and if you press escape it should close.