Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 22 of 22

Thread: Need help on simple game for Practice

  1. #1
    Member
    Join Date
    Jul 2012
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default Need help on simple game for Practice

    Hey there.

    I am trying to practice my Java and work on this basic game I'm creating.

    I am at the stage where I am trying to draw the tiled map, but I'm having two problems. The first problem is a logical one, I am trying to create a for loop that will draw the below image, and assign every 20x20 square a rectangle. I am having problems logically accomplishing this. The second problem is, I started to try a way to do it, but I get this error:

    Exception in thread "Thread-2" java.lang.NullPointerException
    at bandits.World.draw(World.java:43)
    at bandits.GamePanel.draw(GamePanel.java:101)
    at bandits.GamePanel.gameRender(GamePanel.java:96)
    at bandits.GamePanel.run(GamePanel.java:48)
    at java.lang.Thread.run(Thread.java:722)



    Tile.jpg

    Here is the code for my 3 classes:

    package bandits;
     
    import javax.swing.JFrame;
     
     
     
    public class Bandits extends JFrame {
     
        GamePanel gp;
     
     
        public Bandits(){
            gp = new GamePanel();
            setSize(500, 500);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
            setResizable(false);
            add(gp);
     
        }
     
        public static void main(String[] args){
            Bandits b = new Bandits();
        }
    }
     
    package bandits;
     
    import javax.swing.JPanel;
    import java.awt.*;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
     
    public class GamePanel extends JPanel implements Runnable{
        //Double Buffering
        private Image dbImage;
        private Graphics dbg;
     
        //JPanel Variables
        static final int GWIDTH = 500, GHEIGHT = 400;
        static final Dimension gameDim = new Dimension(GWIDTH, HEIGHT);
     
        //Game Variables
        private Thread game;
        private volatile boolean running = false;
     
        World world;
     
        public GamePanel(){
            world = new World();
            setPreferredSize(gameDim);
            setFocusable(true);
            requestFocus();
     
            addKeyListener(new KeyAdapter(){
                @Override
                public void keyPressed(KeyEvent e){
     
     
                }
                @Override
                public void keyReleased(KeyEvent e){
     
     
                }
          });
          }
        @Override
        public void run(){
            while(running){
     
                gameUpdate();
                gameRender();
                paintScreen();
     
     
            }
        }
     
     
        @Override
        public void addNotify(){
            super.addNotify();
            startGame();
        }
     
        private void startGame(){
            if(game == null || !running){
                game = new Thread(this);
                game.start();
                running = true;
            }
        }
     
        public void stopGame(){
            if(running){
                running = false;
            }
        }
     
        private void gameUpdate() {
            if(running && game !=null){
     
            }
        }
     
        private void gameRender() {
            if(dbImage == null){
                dbImage = createImage(GWIDTH, GHEIGHT);
                if(dbImage == null){
                    System.err.println("DBImage is still null!");
                    return;
                }else{
                    dbg = dbImage.getGraphics();
                }
            }
     
            dbg.setColor(Color.WHITE);
            dbg.fillRect(0, 0, getWidth(), getHeight());
     
            draw(dbg);
        }
     
        /* Everything that is graphics gets drawn here*/
        public void draw(Graphics g){
            world.draw(g);
        }
     
        private void paintScreen(){
            Graphics g;
            try{
                g=this.getGraphics();
                if(dbImage != null && g != null){
                    g.drawImage(dbImage,0,0,null);
                }
                Toolkit.getDefaultToolkit().sync();
                g.dispose();
            }catch(Exception e){
                System.err.println(e);
            }
        }
     
    }
    package bandits;
     
    import java.awt.*;
    import javax.swing.ImageIcon;
     
     
    public class World {
     
        private Rectangle[] blocks;
        private Image[] blockImg;
        private final int arrayNum = 625;
     
        private Image BLOCK_FLOOR, BLOCK_WALL;
     
        private int x= 0;
        private int y= 0;
     
        public World(){
            BLOCK_FLOOR = new ImageIcon("C:/Users/Thomas/Documents/NetBeansProjects/Images/Floor.gif").getImage();
            BLOCK_WALL = new ImageIcon("C:/Users/Thomas/Documents/NetBeansProjects/Images/Wall.gif").getImage();
     
            blocks = new Rectangle[625];
            blockImg = new Image[625];
     
            loadArrays();
        }
     
        private void loadArrays(){
            for(int i = 0; i < arrayNum; i++){
              if(x > 500){
                  x = 0;
                  y += 20;
              }
              if(x <= 20){
                  blockImg[i] = BLOCK_WALL;
                  blocks[i] = new Rectangle(x,y,20,20);
              }
              x += 20;
            }
        }
        public void draw(Graphics g){
            for(int i=0; i < arrayNum; i++){
                g.drawImage(blockImg[i], blocks[i].x, blocks[i].y, null);
            }
        }
    }

    Any help would be appreciated, this is not a homework assignment, just trying to refine, practice, and improve my Java skills.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help on simple game for Practice

    Exception in thread "Thread-2" java.lang.NullPointerException
    at bandits.World.draw(World.java:43)
    Look at line 43 and find the variable with the null value. Then backtrack in the code to find out why that variable does not have a valid non-null value.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    Harrald (October 2nd, 2012)

  4. #3
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Need help on simple game for Practice

    Quote Originally Posted by Harrald View Post
    Hey there.
    Hey!
    Quote Originally Posted by Harrald View Post
    ...I get this error:
    Exception in thread "Thread-2" java.lang.NullPointerException
    at bandits.World.draw(World.java:43)
    So: Look at line number 43 in World.java. What is it doing that might be trying to access a pointer but encounters a null value?

    Look at the code that makes values not null. Look real hard.

    Can't see anything (anything at all) that could cause this specific problem? Then make the program tell you exactly what it does:

        private void loadArrays() {
            for(int i = 0; i < arrayNum; i++){
                if(x > 500){
                    x = 0;
                    y += 20;
                }
                if(x <= 20){
                    // From Zaphod_b:
                    //   Debugging: See which of these array elements are given values
                    System.out.printf("in loadArrays(): i = %d\n", i);
                    blockImg[i] = BLOCK_WALL;
                    blocks[i] = new Rectangle(x,y,20,20);
                }
                x += 20;
            }
        }
     
        public void draw(Graphics g) {
            for(int i=0; i < arrayNum; i++){
                // From Zaphod_b:
                //   Debugging: Print value of i as it goes through the loop so that you
                //   can see how far it gets before crashing.
                System.out.printf("in draw(): i = %d\n", i);
                g.drawImage(blockImg[i], blocks[i].x, blocks[i].y, null);
            }
        }


    I mean, it's always OK to ask, but wouldn't it be more time-effective (from your point of view) to get into the groove of simple debugging steps like this?



    Cheers!

    Z.
    Last edited by Zaphod_b; October 2nd, 2012 at 05:36 PM.

  5. The Following User Says Thank You to Zaphod_b For This Useful Post:

    Harrald (October 2nd, 2012)

  6. #4
    Member
    Join Date
    Jul 2012
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default Re: Need help on simple game for Practice

    Thanks for the help you have given so far! I really appreciate this community, hopefully one day I'll be answering these types of questions!

    Also thank you for showing me a way to debug, didn't think of that. My knowledge is nothing but one intro to Java class and a few youtube tutorials. I have got more advanced ones on the way, but I want to stay frosty.

    I have come to the conclusion that it must be something in the loadArrays(); Because it works just fine, well it only paints one rectangle in the topright corner, when I remove the x += 20. You two were mentioning null values, so I think I'm off...

  7. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help on simple game for Practice

    To work out the logic you first need to make a drawing and label the upper left corner of each square.
    The look at the relationship of the x an y values for all the squares in the columns on each row
    and again for each row. Then write nested loops that vary the y value for the rows and the x value for the columns.
    To get the logic, write a small simple testing program with the nested loops that prints out the x,y values for the corner of each square. Then compare the print out with the drawing you made to see if the x,y values match. When you get the logic right in this simple test, you can take it to the main program to set the positions of each square.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #6
    Member
    Join Date
    Jul 2012
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default Re: Need help on simple game for Practice

    I'm stumped. I have been staring at this the whole week. I cannot figure it out. I did a test loop and I didn't run into any problems, I just have the null pointer problem. Any further advice would be greatly appreciated. Thanks!

  9. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help on simple game for Practice

    What printed out in the testing program? Can you post the testing program and its output?

    Also post the current version of your code
    and the full text of the error messages.
    Last edited by Norm; October 5th, 2012 at 03:50 PM.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #8
    Member
    Join Date
    Jul 2012
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default Re: Need help on simple game for Practice

    For some reason dbImage is still Null!... The if statement says if dbImage is null, dbImage = createImage(500, 500);. but for some reason it skips this step and goes to the next step. The next step makes sure dbImage isnt null, if it is, it returns the statement "dbImage is still Null!".

  11. #9
    Member
    Join Date
    Jul 2012
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default Re: Need help on simple game for Practice

    There's the test loop I did to make sure the way I cycle through x's and y's worked.
    int x=0;
            int y=0;
     
            for(int i =0; i < 500; i++){
                if(x >500){
                    x=0;
                    y+=20;
                }
                System.out.println("i is = " + i + " x is = " + x + " y is = " + y);
                x += 20;
         }

  12. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help on simple game for Practice

    For some reason dbImage is still Null
    The default value for object variables is null. If they are not assigned a non-null value, their value will still be null.
    Check the logic and add printlns to show where dbImage is given a value.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #11
    Member
    Join Date
    Jul 2012
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default Re: Need help on simple game for Practice

    I assigned it too dbImage=createImage(500, 500). Is that a wrong type to assign it to?

  14. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help on simple game for Practice

    I assigned it too dbImage=createImage(500, 500)
    If it has any value, it won't be null and cause a NullPointerException.

    If you don't post the full text of the error message and the code, there is very little anyone can do to help you.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #13
    Member
    Join Date
    Jul 2012
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default Re: Need help on simple game for Practice

    run:
    in loadArrays(): i = 0
    DBImage is still null!
    in loadArrays(): i = 1
    java.lang.NullPointerException
    DBImage is still null!
    java.lang.NullPointerException
    DBImage is still null!
    java.lang.NullPointerException
    DBImage is still null!
    java.lang.NullPointerException
    DBImage is still null!
    java.lang.NullPointerException
    DBImage is still null!
    java.lang.NullPointerException
    DBImage is still null!
    "
    "
    java.lang.NullPointerException
    DBImage is still null!
    Exception in thread "Thread-1" java.lang.NullPointerException
    at bandits.World.draw(World.java:46)
    at bandits.GamePanel.draw(GamePanel.java:102)
    at bandits.GamePanel.gameRender(GamePanel.java:97)
    at bandits.GamePanel.run(GamePanel.java:49)
    at java.lang.Thread.run(Thread.java:722)
    BUILD SUCCESSFUL (total time: 2 seconds)

    Hope this helps.

  16. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help on simple game for Practice

    Hope this helps..
    Not much without the code.

    What variable is null and why is it null?

    I'm done for tonight. Back tomorrow.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #15
    Member
    Join Date
    Jul 2012
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default Re: Need help on simple game for Practice

    Here is the code for my 3 classes:
    package bandits;
     
    import javax.swing.JFrame;
     
     
     
    public class Bandits extends JFrame {
     
        GamePanel gp;
     
     
        public Bandits(){
            gp = new GamePanel();
            setSize(500, 500);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
            setResizable(false);
            add(gp);
     
        }
     
        public static void main(String[] args){
            Bandits b = new Bandits();
        }
    }
    package bandits;
     
    import javax.swing.JPanel;
    import java.awt.*;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
     
    public class GamePanel extends JPanel implements Runnable{
        //Double Buffering
        private Image dbImage;
        private Graphics dbg;
     
        //JPanel Variables
        static final int GWIDTH = 500, GHEIGHT = 400;
        static final Dimension gameDim = new Dimension(GWIDTH, HEIGHT);
     
        //Game Variables
        private Thread game;
        private volatile boolean running = false;
     
        World world;
     
        public GamePanel(){
            world = new World();
            setPreferredSize(gameDim);
            setFocusable(true);
            requestFocus();
     
            addKeyListener(new KeyAdapter(){
                @Override
                public void keyPressed(KeyEvent e){
     
     
                }
                @Override
                public void keyReleased(KeyEvent e){
     
     
                }
          });
          }
        @Override
        public void run(){
            while(running){
     
                gameUpdate();
                gameRender();
                paintScreen();
     
     
            }
        }
     
     
        @Override
        public void addNotify(){
            super.addNotify();
            startGame();
        }
     
        private void startGame(){
            if(game == null || !running){
                game = new Thread(this);
                game.start();
                running = true;
            }
        }
     
        public void stopGame(){
            if(running){
                running = false;
            }
        }
     
        private void gameUpdate() {
            if(running && game !=null){
     
            }
        }
     
        private void gameRender() {
            if(dbImage == null){
                dbImage = createImage(GWIDTH, GHEIGHT);
                if(dbImage == null){
                    System.err.println("DBImage is still null!");
                    return;
                }else{
                    dbg = dbImage.getGraphics();
                }
            }
     
            dbg.setColor(Color.WHITE);
            dbg.fillRect(0, 0, getWidth(), getHeight());
     
            draw(dbg);
        }
     
        /* Everything that is graphics gets drawn here*/
        public void draw(Graphics g){
            world.draw(g);
        }
     
        private void paintScreen(){
            Graphics g;
            try{
                g=this.getGraphics();
                if(dbImage != null && g != null){
                    g.drawImage(dbImage,0,0,null);
                }
                Toolkit.getDefaultToolkit().sync();
                g.dispose();
            }catch(Exception e){
                System.err.println(e);
            }
        }
     
    }
    package bandits;
     
    import java.awt.*;
    import javax.swing.ImageIcon;
     
     
    public class World {
     
        private Rectangle[] blocks;
        private Image[] blockImg;
        private final int arrayNum = 625;
     
        private Image BLOCK_FLOOR, BLOCK_WALL;
     
        private int x= 0;
        private int y= 0;
     
        public World(){
            BLOCK_FLOOR = new ImageIcon("C:/Users/Thomas/Documents/NetBeansProjects/Images/Floor.gif").getImage();
            BLOCK_WALL = new ImageIcon("C:/Users/Thomas/Documents/NetBeansProjects/Images/Wall.gif").getImage();
     
            blocks = new Rectangle[625];
            blockImg = new Image[625];
     
            loadArrays();
        }
     
        private void loadArrays(){
            for(int i = 0; i < arrayNum; i++){
              if(x > 500){
                  x = 0;
                  y += 20;
              }
              if(x <= 20){
                  blockImg[i] = BLOCK_WALL;
                  blocks[i] = new Rectangle(x,y,20,20);
              }
              x += 20;
            }
        }
        public void draw(Graphics g){
            for(int i=0; i < arrayNum; i++){
                g.drawImage(blockImg[i], blocks[i].x, blocks[i].y, null);
            }
        }
    }

  18. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help on simple game for Practice

    Exception in thread "Thread-1" java.lang.NullPointerException
    at bandits.World.draw(World.java:46)
    What variable on line 46 has a null value? Add a println to print out the values of all the variables on line 46 if you can't tell which variable could be null.


    If the code in post#9 printed out correct X&Y values for the corners,
    why didn't you use the logic from post #9 for the loadArrays() method's code in post#15?
    Last edited by Norm; October 7th, 2012 at 08:55 PM.
    If you don't understand my answer, don't ignore it, ask a question.

  19. #17
    Member
    Join Date
    Jul 2012
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default Re: Need help on simple game for Practice

    dbImage is the variable that is null, even right after the assign statement it is still null.

    The logic worked the same in both I thought, just have problems with dbImage. Am I mising something?

  20. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help on simple game for Practice

    even right after the assign statement it is still null.
    Is it being assigned a null value?
    Object obj1 = null;
    Object obj2 = obj1; // obj2 will be null here because obj1 is null

    Did you see this in my last post?
    If the code in post#9 printed out correct X&Y values for the corners,
    why didn't you use the logic from post #9 for the loadArrays() method's code in post#15?
    If you don't understand my answer, don't ignore it, ask a question.

  21. #19
    Member
    Join Date
    Jul 2012
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default Re: Need help on simple game for Practice

    Initially, but I assign it too createImage(500,500). I am starting to think that createImage is null. I'm not sure how createImage works totally, I navigated to source but it is kind of confusing.

    I'm still terribly new to java, hence I'm working on this simple top down game to maybe learn somethings and refine what I already know.

  22. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help on simple game for Practice

    You'll have to post the code if you want any help with it.

    Did you see this in my last post?
    If the code in post#9 printed out correct X&Y values for the corners,
    why didn't you use the logic from post #9 for the loadArrays() method's code in post#15?
    If you don't understand my answer, don't ignore it, ask a question.

  23. #21
    Member
    Join Date
    Jul 2012
    Posts
    56
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default Re: Need help on simple game for Practice

    The code hasn't changed from page 1, I just copied and pasted it unto page 2.

    "The logic worked the same in both I thought, just have problems with dbImage. Am I mising something?"
    Yes I saw it, and it is basically exactly the same minus the fact that I add the arrays into it. But the x and y coordinate increases are the same.

  24. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need help on simple game for Practice

    it is basically exactly the same
    I think they are different. This statement from post#15:
         if(x <= 20){
    is NOT in post#9.

    You said that the code in post#9 worked
    The code in post #15 does not work. Add some printlns to the code to print out the values of x and y when a new Rectangle is created to see.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Programming AI for simple game?
    By YouGoLast in forum Java Theory & Questions
    Replies: 3
    Last Post: September 27th, 2024, 02:33 AM
  2. Simple game that requires me to load game settings from a file
    By 14fenix in forum Java Theory & Questions
    Replies: 5
    Last Post: December 1st, 2011, 09:21 PM
  3. Simple game problem
    By frozen java in forum What's Wrong With My Code?
    Replies: 7
    Last Post: November 30th, 2011, 09:14 PM
  4. Simple game in Java
    By velop in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 27th, 2010, 05:04 AM
  5. Simple graphics practice on previous Java code
    By amrawad_85 in forum AWT / Java Swing
    Replies: 5
    Last Post: June 19th, 2009, 10:30 AM