Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (499)
Games in Android Showcase (118)
games submitted by our members
Games in WIP (568)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  [Java2D] Drawing enimies with an arraylist. How to call thier methods  (Read 1128 times)
0 Members and 1 Guest are viewing this topic.
Offline Mr.CodeIt

Junior Member





« Posted 2014-04-27 05:20:21 »

I'm using Java2D for a small basic game I started a while ago. I have an enemy class that draws and moves a rectangle. The thing is, I don't want to make a ton of enemies using:
1  
Enemy e1 = new Enemy; Enemy e2 = new Enemy;
and so on. I'm not too good with ArrayLists so bare with me. I used:
1  
private ArrayList <Enemy> e;
to create the arraylist of enemies. In my
1  
init()
or initialization method I used:
1  
2  
3  
ArrayList <Enemy> e = new ArrayList();
      e.add(0, null);
      e.add(1, null);
to initialize and add enemies. null is the type of enemy that is never defined. The problem may lay with that but in rendering method I used:
1  
e.draw(g);
which obviously gave an error. How do I call a method from an arraylist's class.


I tried researching some arraylists help which was good but not what I needed

I'm not drunk, I've just been up late coding.
Offline LiquidNitrogen
« Reply #1 - Posted 2014-04-27 05:30:49 »

the easiest way would be to use an enhanced for loop to draw each enemy:

1  
2  
3  
4  
5  
6  
7  
ArrayList <Enemy> enemies = new ArrayList();
      enemies.add(0, null);
      enemies.add(1, null);

      for (Enemy e : enemies){
             e.draw();
      }

Offline BurntPizza
« Reply #2 - Posted 2014-04-27 05:30:57 »

Did your research include the JavaDocs??
No need to specify an index for
add()
if you're adding them in order anyway, just add them normally:
e.add(null);
e.add(null);
(Also, why add null elements?)

To "get" an entry back out of the list, you use (gasp)
get()
:

1  
2  
3  
4  
5  
6  
7  
Enemy first = e.get(0);
Enemy second = e.get(1);
Enemy last = e.get(e.size() - 1);

if(first != null) // if first is null, dereferencing it to call draw() will throw a NullPointerException as you would expect, so don't if it's null
   first.draw(g);
...
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline trollwarrior1
« Reply #3 - Posted 2014-04-27 05:33:21 »

I'm afraid that is not how it works. ArrayList is like an array, but you can easily add/remove components from it, not being worried about the size of the array at all.

When adding components to an array, you cannot add null. This alone should give you null pointer exception.

If you want to render all the enemies in the array, you need to render each guy individually.

For example:
1  
2  
3  
4  
5  
6  
7  
      List<Enemy> enemies=new ArrayList<Enemy>();
     
      enemies.add(new Enemy());
     
      for(int i=0;i<enemies.size();i++) {
         enemies.get(i).draw();
      }


There are other ways to do it as you like, but since you're beginner you wouldn't be able to wrap your head around it, since its very very abstract.
Offline Mr.CodeIt

Junior Member





« Reply #4 - Posted 2014-04-27 05:33:42 »

Did your research include the JavaDocs??
No need to specify an index for
add()
if you're adding them in order anyway, just add them normally:
e.add(null);
e.add(null);
(Also, why add null elements?)

To "get" an entry back out of the list, you use (gasp)
get()
:

1  
2  
3  
4  
5  
6  
7  
Enemy first = e.get(0);
Enemy second = e.get(1);
Enemy last = e.get(e.size() - 1);

if(first != null) // if first is null, dereferencing it to call draw() will throw a NullPointerException as you would expect, so don't if it's null
   first.draw(g);
...


Thanks, and it gives me an error if I don't put null in there. I think it's an object type declaration

I'm not drunk, I've just been up late coding.
Offline Mr.CodeIt

Junior Member





« Reply #5 - Posted 2014-04-27 05:35:11 »


If you want to render all the enemies in the array, you need to render each guy individually.

For example:
1  
2  
3  
4  
5  
6  
7  
      List<Enemy> enemies=new ArrayList<Enemy>();
     
      enemies.add(new Enemy());
     
      for(int i=0;i<enemies.size();i++) {
         enemies.get(i).draw();
      }


Thanks, this is great! It is more efficient

I'm not drunk, I've just been up late coding.
Offline BurntPizza
« Reply #6 - Posted 2014-04-27 05:39:01 »

Thanks, and it gives me an error if I don't put null in there. I think it's an object type declaration

Do you mean this?

1  
2  
3  
Enemy guy;

enemyList.add(guy); // The local variable guy may not have been initialized


That means you need to initialize the variable:
guy = new Enemy(); // alternatively: guy = null;



Thanks, this is great! It is more efficient

What's more efficient about it? I'm asking as I don't want you to have any more misconceptions than you may already have.
Offline Mr.CodeIt

Junior Member





« Reply #7 - Posted 2014-04-27 05:44:20 »

Oh I see. I didn't initialize spereate enimies. That may be why I get the error:
1  
2  
3  
xception in thread "Thread-2" java.lang.NullPointerException
   at main.Panel.draw(Panel.java:116)
   at main.Panel.run(Panel.java:78)

I'm not drunk, I've just been up late coding.
Offline Mr.CodeIt

Junior Member





« Reply #8 - Posted 2014-04-27 05:48:13 »

Thanks, and it gives me an error if I don't put null in there. I think it's an object type declaration

Do you mean this?

1  
2  
3  
Enemy guy;

enemyList.add(guy); // The local variable guy may not have been initialized


That means you need to initialize the variable:
guy = new Enemy(); // alternatively: guy = null;



Thanks, this is great! It is more efficient

What's more efficient about it? I'm asking as I don't want you to have any more misconceptions than you may already have.

I still get an error. Based off my question, here is the Panel class:


1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
package main;


import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.event.*;
import java.util.ArrayList;

import javax.swing.JPanel;

import objects.Enemy;
import objects.Player;


public class Panel extends JPanel implements Runnable, KeyListener{  
   private static final long serialVersionUID = -5122190028751177848L;

   
   // dimensions
  public static final int WIDTH = 320;
   public static final int HEIGHT = 240;
   public static final int SCALE = 2;
   
   // game thread
  private Thread thread;
   private boolean running;
   
   // image
  private BufferedImage image;
   private Graphics2D g;
   
   private Player p;
   Enemy a;
   private ArrayList <Enemy> e;
   
   public Panel() {
      super();
      setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
      setFocusable(true);
      requestFocus();
   }
   // DRAWS PANEL TO FRAME
  public void addNotify() {
      super.addNotify();
      if(thread == null) {
         thread = new Thread(this);
         addKeyListener(this);
         thread.start();
      }
   }
   
   private void init() {
     
      image = new BufferedImage(
               WIDTH, HEIGHT,
               BufferedImage.TYPE_INT_RGB
            );
      g = (Graphics2D) image.getGraphics();
      p = new Player(100, 100);
     
      a = new Enemy(100, 50);
     
      ArrayList<Enemy> e = new ArrayList<Enemy>();
         
         e.add(a);
         
         
     
      running = true;
   }
   
   public void run() {
     
      init();
     
     
      // game loop
     while(running) {
         
         update();
         draw();
         drawToScreen();    
         System.out.println("ELAPSED :" + System.nanoTime()/ 1000000 + " Seconds");
         
         try {
            Thread.sleep(10);
         }
         catch(Exception e) {
            e.printStackTrace();
         }
     
      }
     
   }
   
   private void update() {
      p.update();
     
     
   }
   private void draw(){
      //// Clear Screen /////
      g.setColor(Color.BLACK);
       g.fillRect(0, 0, WIDTH, HEIGHT);
     
     
      // NAME (remember it loops)
     String name = "2014 Jay H.";
      g.setFont(new Font("Name", 0, 12));
      g.setColor(Color.WHITE);
      g.drawString(name, 0, 10);
      g.setColor(Color.BLUE);
      g.fillRect( 0, 10, 65, 5);
     
     
      //DRAW PLAYER
     p.draw(g);
     
      //DRAW ENEMY
     for(int i = 0; i < e.size(); i++) {
            e.get(i).draw(g);
         }
     
      g.draw3DRect(20, 20, 50, 50, false);
     
      }
   // SCREEN IMAGE (don't have to use. Just use this^)
  private void drawToScreen() {  
      Graphics g2 = getGraphics();
      g2.drawImage(image, 0, 0,
            WIDTH * SCALE, HEIGHT * SCALE,null);
      g2.dispose();
   }
   
   public void keyTyped(KeyEvent key) {}
   
   // PUBLIC KEYRELEASES
  public void keyPressed(KeyEvent key) {
      int KeyCode = key.getKeyCode();
     
      //EXIT SYSTEM
     if(KeyCode == KeyEvent.VK_Q) {System.exit(0);}
     
     
      //UP
     if(KeyCode == KeyEvent.VK_W){p.setDY(-2);}  
      if(KeyCode == KeyEvent.VK_A){p.setDX(-2);}
      if(KeyCode == KeyEvent.VK_S){p.setDY(2);}
      if(KeyCode == KeyEvent.VK_D){p.setDX(2);}

   }
   
   
   // PUBLIC KEYRELEASES
  public void keyReleased(KeyEvent key) {
      int KeyCode = key.getKeyCode();
     
      //UP
     if(KeyCode == KeyEvent.VK_W) {p.setDY(0);}
      if(KeyCode == KeyEvent.VK_A){p.setDX(0);}
      if(KeyCode == KeyEvent.VK_S){p.setDY(0);}
      if(KeyCode == KeyEvent.VK_D){p.setDX(0);}

     

   }

}

I'm not drunk, I've just been up late coding.
Offline trollwarrior1
« Reply #9 - Posted 2014-04-27 05:52:03 »

You don't get errors in java. You get exceptions. They help you in debugging your code tremendously. You give us your huge piece of code and say "I still get an error" and don't even post the error and at which lines it happened..
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline BurntPizza
« Reply #10 - Posted 2014-04-27 05:53:48 »

A
NullPointerException
means that you tried to do something with an object that is null (doesn't exist).

1  
2  
3  
Enemy e = null;

e.draw(); //e doesn't exist, you can't call draw() on something that doesn't exist, will throw a NPE


You don't get errors in java. You get exceptions. They help you in debugging your code tremendously. You give us your huge piece of code and say "I still get an error" and don't even post the error and at which lines it happened..

java.lang.Error

But yes, really anytime you ask a question about an exception, you NEED to also give the stacktrace.

EDIT: If it's causing the stacktrace a post up, then it probably means
p
is null when
draw()
was called. The line numbers don't match up though, so you may have changed something and that's not the right line anymore.
Offline Mr.CodeIt

Junior Member





« Reply #11 - Posted 2014-04-27 05:55:55 »

You don't get errors in java. You get exceptions. They help you in debugging your code tremendously. You give us your huge piece of code and say "I still get an error" and don't even post the error and at which lines it happened..


I posted my error if you didn't notice. It was in a quote or reply

I'm not drunk, I've just been up late coding.
Offline BurntPizza
« Reply #12 - Posted 2014-04-27 06:05:15 »

Found it:

1  
e.get(i).draw(g);


e
is null because in your
init()
method you did this:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
private ArrayList <Enemy> e;

private void init() {
      ...
      ArrayList<Enemy> e = new ArrayList<Enemy>(); // this is a local variable, the e outside of init() is still null!
       
      e.add(a);

     ...
   }


There is a setting in eclipse to have it tell you you are overwriting or "hiding" a higher-scoped field with a like-named local variable. You should make sure it's on.
Offline Mr.CodeIt

Junior Member





« Reply #13 - Posted 2014-04-27 06:15:14 »

Thanks a bunch, now I just have to fix my multi threading problem

I'm not drunk, I've just been up late coding.
Offline LiquidNitrogen
« Reply #14 - Posted 2014-04-27 06:55:22 »

its generally advisable not to use multi-threading unless you are making very complex programs and really know what you are doing. its not needed for basic-medium sized games.

Offline Mr.CodeIt

Junior Member





« Reply #15 - Posted 2014-04-27 06:56:36 »

its generally advisable not to use multi-threading unless you are making very complex programs and really know what you are doing. its not needed for basic-medium sized games.

How else can I make 2 tasks run at once? A timer?

I'm not drunk, I've just been up late coding.
Offline LiquidNitrogen
« Reply #16 - Posted 2014-04-27 06:58:38 »

you probably dont need 2 tasks to run at once. you run one, then you run the other, then you render everything, repeat.

Offline Mr.CodeIt

Junior Member





« Reply #17 - Posted 2014-04-27 07:02:06 »

you probably dont need 2 tasks to run at once. you run one, then you run the other, then you render everything, repeat.

I made another topic a few minutes ago asking the question my full code is there except now  I use thread.sleep and it freezes. in the topic I used thread.wait(). And I need the enemy to move while the game is running

I'm not drunk, I've just been up late coding.
Offline Gibbo3771
« Reply #18 - Posted 2014-04-27 07:02:38 »

its generally advisable not to use multi-threading unless you are making very complex programs and really know what you are doing. its not needed for basic-medium sized games.

How else can I make 2 tasks run at once? A timer?

Look, I don't mean to shit all over your parade but you REALLY NEED TO STEP BACK, you hence been on this forum for like a week and almost every one if your posts is you heeding trouble with basic Java syntax!

You need to read the docs, do some more tutorials.

Tutorials Point

"This code works flawlessly first time and exactly how I wanted it"
Said no programmer ever
Offline LiquidNitrogen
« Reply #19 - Posted 2014-04-27 07:07:56 »

if you want to make the animation wait, yes use some kind of timer. running multiple threads will cause you all kinds of trouble, specially if you need one for each animation. just use a simple frame counter which waits a certain number of frames before changing, and add +1 to the counter each frame.

Offline Mr.CodeIt

Junior Member





« Reply #20 - Posted 2014-04-27 07:08:56 »

its generally advisable not to use multi-threading unless you are making very complex programs and really know what you are doing. its not needed for basic-medium sized games.

How else can I make 2 tasks run at once? A timer?

Look, I don't mean to shit all over your parade but you REALLY NEED TO STEP BACK, you hence been on this forum for like a week and almost every one if your posts is you heeding trouble with basic Java syntax!

You need to read the docs, do some more tutorials.

Tutorials Point

Yeah  Undecided. I guess this site is my best resource for java game dev

I'm not drunk, I've just been up late coding.
Offline BurntPizza
« Reply #21 - Posted 2014-04-27 07:10:45 »

Yeah  Undecided. I guess this site is my best resource for java game dev

JGO is your resource for gamedev, but not the best for basics. I recommend a book, consider Java Head First (and google/library around for other books) something more structured and thorough than random internet tutorials.
Offline Gibbo3771
« Reply #22 - Posted 2014-04-27 07:19:51 »

I would not recommend tutorials point if your literally brand new to the language, however if you have the basics down, it is good for reference.

"This code works flawlessly first time and exactly how I wanted it"
Said no programmer ever
Offline Mr.CodeIt

Junior Member





« Reply #23 - Posted 2014-04-27 07:24:55 »

I would not recommend tutorials point if your literally brand new to the language, however if you have the basics down, it is good for reference.

I've been using Java for months. I don't think I'm that new, It's just game dev that gave me a problem

I'm not drunk, I've just been up late coding.
Offline BurntPizza
« Reply #24 - Posted 2014-04-27 07:30:06 »

So you had no problems with import statements, object initialization, and exceptions outside of gamedev?
These are basic, fundamental language features and are not specifically related to gamedev at all.

Just get a book, thank me later.
List of good books
Offline Gibbo3771
« Reply #25 - Posted 2014-04-27 07:42:26 »

I would not recommend tutorials point if your literally brand new to the language, however if you have the basics down, it is good for reference.

I've been using Java for months. I don't think I'm that new, It's just game dev that gave me a problem

I believed everything on the internet, I would be one f**ked up individual.

"This code works flawlessly first time and exactly how I wanted it"
Said no programmer ever
Offline trollwarrior1
« Reply #26 - Posted 2014-04-27 08:33:28 »

I would not recommend tutorials point if your literally brand new to the language, however if you have the basics down, it is good for reference.

I've been using Java for months. I don't think I'm that new, It's just game dev that gave me a problem

Yes you have been using java for months, but don't even know what a List is.
Offline Roquen
« Reply #27 - Posted 2014-04-27 13:45:17 »

When adding components to an array, you cannot add null. This alone should give you null pointer exception.
For correctness sake: it's perfectly legal to place a null in either an array or an ArrayList.
Offline trollwarrior1
« Reply #28 - Posted 2014-04-27 14:01:27 »

When adding components to an array, you cannot add null. This alone should give you null pointer exception.
For correctness sake: it's perfectly legal to place a null in either an array or an ArrayList.

Sorry, for some reason I thought you get an exception when trying to add null to list. I don't really see any use of putting null into list..
Pages: [1]
  ignore  |  Print  
 
 

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Pippogeek (39 views)
2014-09-24 16:13:29

Pippogeek (30 views)
2014-09-24 16:12:22

Pippogeek (20 views)
2014-09-24 16:12:06

Grunnt (46 views)
2014-09-23 14:38:19

radar3301 (28 views)
2014-09-21 23:33:17

BurntPizza (64 views)
2014-09-21 02:42:18

BurntPizza (36 views)
2014-09-21 01:30:30

moogie (42 views)
2014-09-21 00:26:15

UprightPath (51 views)
2014-09-20 20:14:06

BurntPizza (54 views)
2014-09-19 03:14:18
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!