Java classes in game programming?

I am making a small strategy game to help me learn Java in a fun way. The fact is that I saw units as objects that they themselves would draw on the game map (using images and buffering) and respond to mouse actions with listeners attached to them.

Now, based on some of the lessons I've read regarding basic game programming, everything seems to be drawn in the Graphics method of my Map class. If a new block appears, I just update the Map.Graphics method, it's not as simple as creating a new Unit object that I would draw myself ... In this case, I would be stuck with a number of Map methods instead of using classes to render new things.

So my question is: can I use classes for rendering units, interface objects, etc., or will I have to create methods and just do some kind of structural programming instead of object oriented? I am a little confused, and I would like to have a mental plan of how everything will be organized.

Thank!

+3
source share
3 answers

As ck said, you can do this using a paintable interface, for example:

public interface GameElement {
    public void draw(Graphics g);
}

public class Sprite implements GameElement{
    private Image image;
    private int x;
    private int y;
    public void draw(Graphics g) {
                g.drawImage(image,x,y,null);
    }
}

public class GameLoop {

        public void drawElements(final Graphics2D g, final List<GameElement> elements) {
                for (final GameElement gameElement : elements) {
                        gameElement.draw(g);
                }
        }


}

, , , , . dash-tom-bang, , . , , , . , , - .

+1

, , .

. , , .


#, Java

public interface IRenderable
{
    void RenderMe(Graphics graphics)
}

List<IRenderable> myGameObjects;

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

, .

+4

"" , - :

while True:
   ProcessUserInput()

   for o in objects:
      o.Update()

   for o in objects:
      o.Render()

, , .:) , , . , " " , ( , ).

From your question, maybe the units belong to the map? In this case, the Map.Render function will iterate over all units belonging to it, calling Render on each of them in turn. Despite this, it is probably the cleanest if the code for drawing the unit is in the class for this device.

Good luck

+1
source

Source: https://habr.com/ru/post/1740812/


All Articles