-1

我在 Java 中制作 Pong 是为了好玩。我刚完成俄罗斯方块但开始错误地构建游戏,因此整个程序都遵循了糟糕的设计,这限制了我可以做的事情。

这一次,我想从正确的开始。我想要:

  • 按照 MVC 模型创建游戏
  • 有合理的班级组织和脱钩
  • 正确使用封装
  • 将 GUI 与游戏规则分开

话虽如此,我提出的班级结构是否正确使用了班级?

主类:extends JFrame负责将 JPanels 添加到 JFrame 并初始化游戏

  • 将 GamePanel 和 ScorePanel 添加到 JFrame
  • 设置它们的大小和位置等...(使用 frame.pack()...)
  • 初始化游戏——public static void main(String[] args) {...

GamePanel 类:扩展 JPanel:只负责了解自己的边界以及对象是否违反这些规则......

  • paintComponent() 将形状(桨和球)绘制到屏幕上
  • 具有边界和碰撞(球与桨碰撞)规则
  • KeyListeners(不确定是否在正确的位置)
  • 游戏计时器设置游戏节拍

GameRules 类:负责从 GamePanel 获取数据(例如,如果球与桨发生碰撞),并根据该数据计算得分和其他信息......

  • 游戏计分、游戏结束规则、练级
  • 球反弹时的角度(不确定是否在正确的位置)

ScorePanel 类: GUI 负责向玩家显示分数、级别和其他相关数据...将从 GameRules 类中获取其数据。

  • paintComponent() 将分数和其他数据绘制到屏幕上

Paddle 类:扩展 Rectangle2D (AWT)负责只知道自己的 (x,y) 坐标...拥有自己的颜色,设置新位置

  • 获取X(),获取Y()
  • 获取颜色()
  • 设置位置(x,y)

Ball 类:扩展 Ellipse2D (AWT)负责只知道自己的 (x,y) 坐标......就像 Paddle


问题:

  • 不确定计算角度的数学应该在哪里反弹
  • keyListener 应该去哪里?
  • 如何使用“游戏循环”而不是让游戏运行paintComponent()
  • 试图遵循 MVC 模型......这能实现吗?

谢谢!

编辑

在此处输入图像描述

4

1 回答 1

4

Unsure where to put math for calculating angles ball should bounce at

GameRules is as good a class as any. If your math was more elaborate, you could create a GameMath class.

Where should the keyListener go?

My first guess would be the GamePanel class.

How do I use a "game loop" instead of having the game run through paintComponent()?

Your GamePanel paintComponent method is responsible for drawing the current state of the paddles and ball. It helps if your paddles and ball have their own draw method, so that paintComponent merely calls the paddles and ball draw methods.

Your game loop updates the values in the paddles and ball classes. You can call paintComponent in it's own loop, to get a steady frame rate, and call your paddles and ball position updates in a different loop.

Trying to follow MVC model... does this achieve it?

Java Swing can have controller code in the view, in the form of anonymous action classes. I said to put drawing code in the model classes.

While the code isn't necessarily separated, the functionality is. Drawing code in the model classes is executed by the drawing JPanel. Control code in the view classes is executed as part of a control action.

Take a look at this article, Sudoku Solver Swing GUI, to see how to put together a moderately complicated Swing GUI. I don't have any examples of a video game to show you.

于 2013-05-21T19:04:15.610 回答