Jump to content

  • Log In with Google      Sign In   
  • Create Account


#Actualnerdboy64

Posted 24 November 2013 - 08:55 PM

You didn't give me an awful lot to work with, so I'm making some assumptions here. First, since you reference Graphics, I'm assuming your game is packaged as a Runnable object. Second, it sounds like you know how to use Graphics and are just having trouble getting your NPCs to paint to the same Graphics object.

First, make an abstract class which will be the parent of all NPCs, and give it an abstract method which accepts a Graphics object as an argument, like so:

public abstract class NPC {
    public abstract void render(Graphics g);
}

Then, have every NPC class extend the new class, for example:

public class Villager extends NPC {
    public void render(Graphics g){
        //rendering code goes here
    }
}

Then, in your game's central class, make an ArrayList of all the NPCs and iterate over it in your paint() method, like this:

public class JavaGame extends Runnable {
    public List<NPC> npcs = new ArrayList<NPC>(); //list of all NPCs currently in the game

    public void paint(Graphics g){
        //other rendering code goes here (any background images, UI pieces, etc.)
        for(NPC npc : npcs) npc.render(g); //loop through the list of NPCs and render each one
    }
}

#1nerdboy64

Posted 24 November 2013 - 08:38 PM

You didn't give me an awful lot to work with, so I'm making some assumptions here. First, since you reference Graphics, I'm assuming your game is packaged as a Runnable object. Second, it sounds like you know how to use Graphics and are just having trouble getting your NPCs to paint to the same Graphics object.

First, make an abstract class which will be the parent of all NPCs, and give it an abstract method which accepts a Graphics object as an argument, like so:

public abstract class NPC {
    public abstract void render(Graphics g);
}

Then, have every NPC class extend the new class, for example:

public class Villager extends NPC {
    public void render(Graphics g){
        //rendering code goes here
    }
}

Then, in your game's central class, make an ArrayList of all the NPCs and iterate over it in your paint() method, like this:

public class JavaGame extends Runnable {
    public List<NPC> npcs = new ArrayList<NPC>(); //list of all NPCs currently in the game

    public void paint(Graphics g){
        for(NPC npc : npcs) npc.render(g); //loop through the list of NPCs and render each one
    }
}

PARTNERS