简体   繁体   English

Java swing小型2D游戏:如何对视图进行建模?

[英]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? 在一个小型的Java swing 2D游戏中,创建棋盘视图的最佳解决方案是什么?

  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. 使用一个组件用于电路板并创建另一个组件,使用自己的paint组件对该方块进行建模,仅为方形工作。 Use a layout to place each Square instance in the board? 使用布局将每个Square实例放置在电路板中?

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. 我已经开始了一个侧面项目,我已经使用了1),感觉有些不对劲。

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. 使用基于图块的示例,您将知道面板的高度和宽度,绘制正方形并根据需要增加X和Y坐标。

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. 诸如Swing或.NET的Winforms之类的GUI框架是昂贵的,因为它们具有游戏不需要的许多其他东西。 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 . 结合第一种方法使用第二种方法的一个很好的解决方案是Flyweight设计模式 You still get to use OO objects, but you'll have a fraction of the amount you normally would. 你仍然可以使用OO对象,但是你通常会得到一小部分。 Check it out. 看看这个。

Like Finglas, I lean toward your first approach. 像Finglas一样,我倾向于你的第一种方法。 This tile-based game is a concrete example. 这个基于图块的游戏就是一个具体的例子。 In contrast, this component-based game uses a GridLayout of JToggleButton . 相比之下,这个基于组件的游戏使用了JToggleButtonGridLayout 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. 您可能需要尝试游戏的几何和逻辑来决定选择哪个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM