Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java swing small 2D game: how to modelize the view?

In a small java swing 2D game, what is the best solution for creating the board view?

  1. Use a component for the board and custom paint it and each square of the checker at once?
  2. Use a component for the board and create another component modelizing the square with its own paint component doing the job for the square only. Use a layout to place each Square instance in the board?

I know this is subjective and I don't want a fight about it. I just need some clues to figure myself which way I should go. I've begun a side project and I've using 1), with the feeling that there is something wrong.

like image 903
Guillaume Avatar asked Jan 23 '23 13:01

Guillaume


2 Answers

Just go with one drawing panel/container for everything.

Consider a tile based game. Using your second solution each tile would be an object, memory would skyrocket and the game would slow to a crawl.

Using the first option you are flexiable. You draw what you want, you have the panel coordinates so everything is relative to this. Using the tile based example you'd know the height and width of the panel, draw your square and increment in the X and Y coordinates as appropriate.

GUI frameworks such as Swing or .NET's Winforms are expensive as they have a whole lot of other stuff that a game won't need. So to answer your question, go with option one, rather than say using a panel for every checker on your board.

One nice solution to using the second method, in combination with the first method is the Flyweight Design Pattern. You still get to use OO objects, but you'll have a fraction of the amount you normally would. Check it out.

like image 102
Finglas Avatar answered Jan 25 '23 03:01

Finglas


Like Finglas, I lean toward your first approach. This tile-based game is a concrete example. In contrast, this component-based game uses a GridLayout of JToggleButton. The former is somewhat more complex but plays well even on large screens; the latter is simpler yet sufficient for reasonable games. You may have to experiment with your game's geometry and logic to decide which to prefer.

like image 23
trashgod Avatar answered Jan 25 '23 03:01

trashgod