Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Classes in game programming?

Tags:

java

class

I'm doing a little strategy game to help me learn Java in a fun way. The thing is I visioned the units as objects that would self draw on the game map (using images and buffering) and would react to the mouse actions with listeners attached to them.

Now, based on some tutorials I've been reading regarding basic game programming, all seems to be drawn in the Graphics method of my Map class. If a new unit emerges, i just update the Map.Graphics method, it's not as easy as making a new Unit object which would self draw... In this case, I'd be stuck with a whole bunch of Map methods instead of using classes for rendering new things.

So my question is, is it possible to use classes for rendering units, interface objects, etc, or i'll have to create methods and just do some kind of structural programming instead of object oriented? I'm a little bit confused and I'd like to have a mental blueprint of how things would be organized.

Thanks!

like image 996
Gabriel Avatar asked Dec 07 '25 06:12

Gabriel


1 Answers

Sounds like your objects need to have a common interface that they can all be down-casted to for rendering.

E.g. have a generic list of your interface type, populate it with the game objects, then enumerate the list and call the common method to do the rendering.


This is C# code, but it should be similar for Java

public interface IRenderable
{
    void RenderMe(Graphics graphics)
}

List<IRenderable> myGameObjects;

foreach (IRenderable myGameObject in myGameObjects)
{
    myGameObject.RenderMe(myMap);
}

While the objects are held in the list they can respond to events and update their internal state ready for the next render cycle.

like image 171
cjk Avatar answered Dec 08 '25 18:12

cjk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!