Page 1 of 3 123 LastLast
Results 1 to 20 of 58
  1. #1
    PRW56 is offline Member
    Join Date
    Mar 2012
    Posts
    75
    Rep Power
    0

    Default game engine trouble

    I am attempting to make a game engine, but I am having trouble organizing the methods. I have a way to tell it to update computer player movement every so often, but to do so it has to be in a loop that is running as long as the game is running. Since the game is in this loop it cannot receive the keyEvents that are being fired, so I am wondering where they should go? Do you think starting another thread with the loop thread would stop it, and if so what would make up the thread so it can receive keyboard info? Fram is my window adapter.

    this is the frame that is running the GamePanel:
    Java Code:
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class GameFrame extends Fram implements ActionListener
    {
        Panel top = new Panel();
        GamePanel g = new GamePanel();
        Panel bot = new Panel();
        Button startboc = new Button("Start");
        Button pauseboc = new Button("Pause");
        Thread loop;
        boolean running=false,paused=false;
        GameFrame()
        {
            super("ProtoGame");
            setLayout(new BorderLayout());
            add(top,BorderLayout.NORTH);
            add(g,BorderLayout.CENTER);
            add(bot,BorderLayout.SOUTH);
            top.add(startboc);
            top.add(pauseboc);
            startboc.addActionListener(this);
            pauseboc.addActionListener(this);
            setSize(800,600);
            setVisible(true);
        }
        public void actionPerformed(ActionEvent e)
        {
            Object act = e.getSource();
            if(act==startboc)
            {
                running = !running;
                if(running)
                {
                    startboc.setLabel("Stop");
                    g.setRunning(true);
                    runGameLoop();
                }
                else
                {
                    startboc.setLabel("Start");
                }
            }
            if(act==pauseboc)
            {
                paused = !paused;
                if(paused)
                {
                    pauseboc.setLabel("Pause");
                    loop.resume();
                }
                else
                {
                    pauseboc.setLabel("Unpause");
                    loop.suspend();
                }
            }
        }
        public void runGameLoop()
        {
            loop = new Thread()
            {
                public void run()
                {
                    g.gameLoop();
                }
            };
            loop.start();
        }
        public static void main(String[] args)
        {
            GameFrame a = new GameFrame();
        }
    }
    here is the panel that the game is sort of happening in:
    Java Code:
    import java.awt.*;
    public class GamePanel extends Panel
    {
        ProtoPlayer stickMan = new ProtoPlayer("StickMan","pic/stickman.jpg",50,50,this);
        boolean running=false,paused=false;
        double now, lastUpdateTime;
        GamePanel()
        {
            //lastUpdateTime = (System.nanoTime()/1000000000);
            //gameLoop();
        }
        public void paint(Graphics g)
        {
            Graphics2D g2 = (Graphics2D)g;
            g2.drawImage(stickMan.getImage(),stickMan.getX(),stickMan.getY(),null);
        }
        public void setRunning(boolean t)
        {
            running = t;
        }
        public void setPaused(boolean t)
        {
            paused = t;
        }
        public void gameLoop()
        {
            System.out.println("in loop");
            final double GAME_HERTZ = 30.0;
            final double TIME_BETWEEN_UPDATES = 1000000000 / GAME_HERTZ;
            final int MAX_UPDATES_BEFORE_RENDER = 5;
            lastUpdateTime = System.nanoTime();
            while(running)
            {
                now = System.nanoTime();
                int updateCount = 0;
                if (paused!=true)
                {
                    while( now - lastUpdateTime > TIME_BETWEEN_UPDATES && updateCount < MAX_UPDATES_BEFORE_RENDER )
                    {
                        updateGame();
                        lastUpdateTime += TIME_BETWEEN_UPDATES;
                        updateCount++;
                        System.out.println("position: "+stickMan.getX());
                    }
                    System.out.println("position: "+stickMan.getX());
                }
                else
                {
                    break;
                }
            }
        }
        public void updateGame()
        {
            //add AI players
        }
    }
    this is the class that the player is made of, the key events are here b/c i couldn't really decide any better place to put them...
    Java Code:
    import java.awt.*;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    public class ProtoPlayer extends Sprite implements KeyListener
    {
        private Panel parent;
        ProtoPlayer(String n,String img,int x,int y, Panel p)//arguments are name(idenifier), end of file path for image, intial x and y coordinates, and its parent panel
        {
            super(n,img,x,y);
            parent = p;
        }
        public void keyPressed(KeyEvent evt)
        {
            char key = evt.getKeyChar();
            switch (key)
            {
                case KeyEvent.VK_W:
                    if(yloc>0)
                        yloc-=10;
                    break;
                case KeyEvent.VK_A:
                    if(xloc>0)
                        xloc-=10;
                    break;
                case KeyEvent.VK_S:
                    if(yloc<parent.getWidth())
                        yloc+=10;
                    break;
                case KeyEvent.VK_D:
                    if(xloc<parent.getHeight())
                        xloc+=10;
                    break;
            }
        }
        public void keyReleased(KeyEvent evt)
        {
            //char key = evt.getKeyChar();
        }
        public void keyTyped(KeyEvent evt)
        {
            //char key = evt.getKeyChar();
        }
    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default Re: game engine trouble

    the game is in this loop it cannot receive the keyEvents that are being fired
    What is the problem with getting key events? What thread is the game loop running on? It should have its own thread and not use the JVM's EDT.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    PRW56 is offline Member
    Join Date
    Mar 2012
    Posts
    75
    Rep Power
    0

    Default Re: game engine trouble

    the problem is that the program is in the while loop on line 38 (which i where i mean to place computer AI), so it doesn't receive KeyEvents (as evidenced by the print on line 43). Also i though it was on its own thread (line 61 the loop thread)? If I made a new thread and started it at the same time what would i have to do so that it is able to receive the key events? I mean I thought multiple threads switch between one another every instant, so thats where the idea to use another thread came from, but is that true? and if so how should I make the other thread

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default Re: game engine trouble

    If your loops are are their own threads, the jvm would be able to call the key listener when a key event happened.

    I can't test the code without all the classes.
    Last edited by Norm; 05-31-2012 at 02:49 AM.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    PRW56 is offline Member
    Join Date
    Mar 2012
    Posts
    75
    Rep Power
    0

    Default Re: game engine trouble

    sorry about that here is the sprite class, but how did the new thread look? what was its makeup of the run method, or was it blank? Did it execute even while the loop thread was inside the game while loop on line 32 and/or 38?

    the sprite class:
    Java Code:
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    public class Sprite
    {
        protected BufferedImage face;
        protected String name;
        protected int xloc;
        protected int yloc;
        protected int width;
        protected int height;
        Sprite(String n,String img,int x,int y)
        {
            name = n;
            xloc = x;
            yloc = y;
            System.out.println("loading "+name+"'s image...");
            try
            {
                face = ImageIO.read(getClass().getClassLoader().getResource(img));
            }
            catch(IOException e) {}
            width = face.getWidth();
            height = face.getHeight();
        }
        public void changeX(int deltaX)
        {
            xloc += deltaX;
        }
        public void changeY(int deltaY)
        {
            yloc += deltaY;
        }
        public BufferedImage getImage()
        {
            return face;
        }
        public int getX()
        {
            return xloc;
        }
        public int getY()
        {
            return yloc;
        }
        public int getWidth()
        {
            return width;
        }
        public int getHeight()
        {
            return height;
        }
        public void setX(int x)
        {
            xloc = x;
        }
        public void setY(int y)
        {
            yloc = y;
        }
    }

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default Re: game engine trouble

    Is the keyPressed method ever called? Add a println to see.

    BTW This print out goes too many times:
    System.out.println("position: "+stickMan.getX());

    Change the logic to print only if the value returned by getX() changes.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    PRW56 is offline Member
    Join Date
    Mar 2012
    Posts
    75
    Rep Power
    0

    Default Re: game engine trouble

    hey norm I'm sorry for the delayed response, but I got to thinking what if I wasn't able to write the rest of the game engine besides this? So, since for some reason the pause and start/stop buttons worked (even while in the loop), I decided to go ahead and write the updateGame method. I have done that but have a problem that is mystifying me, the characters (which are only rectangles right now) should change direction every 5 seconds, I have checked with println(), and it goes into the method that changes the direction and actually changes the direction (as evidenced by the println()), but then it goes on to the switch statement that moves it and doesn't change direction. An even weirder thing was, when I used the println(), it only printed once, even though it should have printed 3 times (since it was in a for loop that is cycling through the array that contained the characters). Another odd thing is only one (red or blue) chases the other instead of the two running to each other and stopping, like I want them to.

    [UPDATE] I managed to fix all those problems, now I am wondering two things: first if you draw any image it must be a square, so how do you make parts of said image opaque or translucent (i think those are the correct terms). I have already tried drawing an image with an opaque background in photoshop, but when I draw it in the game it still has a white background, so how should I do it? second I would like to go back to the key listener problem, It turns out I never added a KeyListener to wherever I needed one in the old version, and I was comparing the key char instead of the key code to the key constants, but even after fixing those things (and adding a println to see if it was calling the keyPressed to begin wtih (it wasn't)) it still did not work. Any Idea of how to fix that?
    Last edited by PRW56; 06-06-2012 at 10:47 AM.

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default Re: game engine trouble

    it still did not work.
    What was not working?
    Try debugging by adding printlns to see what the code is doing and what the values of the variables are.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    PRW56 is offline Member
    Join Date
    Mar 2012
    Posts
    75
    Rep Power
    0

    Default Re: game engine trouble

    sorry for being vague, What I mean is I put a println() inside the keyPressed method, and it was not called when I pressed keys.

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default Re: game engine trouble

    Does the component with the key listener have the focus? Thee are methods that will request the focus. Also for debugging add a focus listener to the component and print out messages when focus is gained and lost.

    Using key binding will help work around this problem.
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    PRW56 is offline Member
    Join Date
    Mar 2012
    Posts
    75
    Rep Power
    0

    Default Re: game engine trouble

    I tried requesting focus it still did not work, the mouseListener does for some reason, another problem arose when I tried to add a bufferstrategy to get rid of the flickering problem, now it compiles, but when I run it it immediately throws an illegalStateException and crashes. Any idea what could cause that?

    doing that...
    Last edited by PRW56; 06-14-2012 at 09:49 PM.

  12. #12
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default Re: game engine trouble

    Can you make a small program that compiles, executes and shows the problem?
    If you don't understand my response, don't ignore it, ask a question.

  13. #13
    PRW56 is offline Member
    Join Date
    Mar 2012
    Posts
    75
    Rep Power
    0

    Default Re: game engine trouble

    ok here is smaller code with same problem

    Java Code:
    import java.awt.*;
    import java.awt.image.BufferStrategy;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.util.Timer;
    import java.util.TimerTask;
    import java.awt.Rectangle;
    public class TRYstrat extends Fram
    {
        Panel base = new Panel();
        Canvas canvas = new Canvas();
        Timer t;
        int x=50,y=50;
        BufferStrategy strategy;
        TRYstrat()
        {
            super("TRYstrat");
            setSize(800,600);
            setIgnoreRepaint(true);
            add(base);
            canvas.setPreferredSize(new Dimension(this.getWidth(),this.getHeight()));
            canvas.setIgnoreRepaint(true);
            base.add(canvas);
            canvas.createBufferStrategy(2);
            t.schedule(new TimerTask()
                        {
                            public void run()
                            {
                                strategy = canvas.getBufferStrategy();
                                do
                                {
                                    do
                                    {
                                        Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
                                        render(g);
                                        g.dispose();
                                    }while(strategy.contentsRestored());
                                    strategy.show();
                                }while(strategy.contentsLost());
                            }
                        },1000,500);
            setVisible(true);
            pack();
        }
        public void render(Graphics2D g2)
        {
            x+=10;
            g2.draw(new Rectangle(x,y,50,50));
        }
        public static void main(String[] args)
        {
            TRYstrat a = new TRYstrat();
        }
    }

  14. #14
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default Re: game engine trouble

    tried requesting focus it still did not work, the mouseListener does for some reason
    here is smaller code with same problem
    I don't see any listeners in the code. Nor anything to do with focus.

    Is this code for some other problem? See post#10
    If you don't understand my response, don't ignore it, ask a question.

  15. #15
    PRW56 is offline Member
    Join Date
    Mar 2012
    Posts
    75
    Rep Power
    0

    Default Re: game engine trouble

    sorry if I wasn't clear, this code is for the buffer strategy problem b/c I would need a larger code to test the other (and I can get around it using mouselistener)

  16. #16
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default Re: game engine trouble

    Quote Originally Posted by PRW56 View Post
    ok here is smaller code with same problem

    Java Code:
    import java.awt.*;
    import java.awt.image.BufferStrategy;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.util.Timer;
    import java.util.TimerTask;
    import java.awt.Rectangle;
    public class TRYstrat extends Fram
    {
        Panel base = new Panel();
        Canvas canvas = new Canvas();
        Timer t;
        int x=50,y=50;
        BufferStrategy strategy;
        TRYstrat()
        {
            super("TRYstrat");
            setSize(800,600);
            setIgnoreRepaint(true);
            add(base);
            canvas.setPreferredSize(new Dimension(this.getWidth(),this.getHeight()));
            canvas.setIgnoreRepaint(true);
            base.add(canvas);
            canvas.createBufferStrategy(2);
            t.schedule(new TimerTask()
                        {
                            public void run()
                            {
                                strategy = canvas.getBufferStrategy();
                                do
                                {
                                    do
                                    {
                                        Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
                                        render(g);
                                        g.dispose();
                                    }while(strategy.contentsRestored());
                                    strategy.show();
                                }while(strategy.contentsLost());
                            }
                        },1000,500);
            setVisible(true);
            pack();
        }
        public void render(Graphics2D g2)
        {
            x+=10;
            g2.draw(new Rectangle(x,y,50,50));
        }
        public static void main(String[] args)
        {
            TRYstrat a = new TRYstrat();
        }
    }
    throws an illegalStateException
    Please post the full text of any error messages.

    The code you posted does not compile. Missing classes/methods.
    Last edited by Norm; 06-14-2012 at 10:07 PM.
    If you don't understand my response, don't ignore it, ask a question.

  17. #17
    PRW56 is offline Member
    Join Date
    Mar 2012
    Posts
    75
    Rep Power
    0

    Default Re: game engine trouble

    here is the window adapter:
    Java Code:
    import java.awt.event.*;
    import java.awt.*;
    public class Fram extends Frame implements WindowListener
    {
        public Fram(String str)
        {
            super(str);
            addWindowListener(this);
        }
        public void windowClosing(WindowEvent e)
        {
            System.exit(0);
        }
        public void windowClosed(WindowEvent e) {}
        public void windowDeiconified(WindowEvent e) {}
        public void windowIconified(WindowEvent e) {}
        public void windowOpened(WindowEvent e) {}
        public void windowActivated(WindowEvent e) {}
        public void windowDeactivated(WindowEvent e) {}
    }
    full error message:

    illegalStateException
    componet must have a valid peer (in java.awt.Componet$FlipBufferStrategy)

  18. #18
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default Re: game engine trouble

    The full text would have the source line number.

    Have you looked up the error message and the doc for the method that threw it?
    Does the component have a valid peer?
    If you don't understand my response, don't ignore it, ask a question.

  19. #19
    PRW56 is offline Member
    Join Date
    Mar 2012
    Posts
    75
    Rep Power
    0

    Default Re: game engine trouble

    Im sorry its not the full error code but blueJ doesn't let me copy it, I have looked at the method (which is createBufferStrategy) and I do not understand the error or what it means by peer.

  20. #20
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default Re: game engine trouble

    The peer is what the OS gives to the JVM as a place to show stuff. To understand you need to read up on heavyweight/native and lightweight components and when they are viewable.

    What does the text of the error description say for the method where the error occurred?
    If you don't understand my response, don't ignore it, ask a question.

Page 1 of 3 123 LastLast

Similar Threads

  1. Easy Clip2D Game Engine now posted
    By rdjava in forum Reviews / Advertising
    Replies: 3
    Last Post: 06-03-2011, 05:24 PM
  2. Easy Clip2D Game Engine now posted
    By rdjava in forum Java Gaming
    Replies: 2
    Last Post: 06-03-2011, 05:18 PM
  3. Replies: 1
    Last Post: 06-02-2011, 09:29 AM
  4. Game Engine in Java, is it practical idea?
    By chan_nguyen in forum New To Java
    Replies: 2
    Last Post: 09-14-2010, 03:20 PM
  5. Crate Game Engine 20080323
    By JavaBean in forum Java Software
    Replies: 0
    Last Post: 03-25-2008, 04:50 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •