[英]Having trouble making my first subclass in Java
我正在尝试为我的Java课程制作一个Breakout游戏程序,该程序包含一系列彩色块(砖)。 我已经成功完成了此任务,但现在我的教练希望我们添加不同的Bricks子类。 他想要的子类之一是ColorBrick,它继承了Brick超类的所有行为,除了它具有每5个滴答变化一次的颜色数组。 构造函数采用颜色数组,而不是单一颜色。
这是我的Brick超类所拥有的:
package Breakout;
import java.awt.Color;
import java.awt.Graphics;
public class Brick {
public int x, y, i, j;
public Color c;
Brick[][] brick;
public Brick() {
}
public Brick(Color c, Brick[][] brick, int i, int j) {
this.c = c;
this.brick = brick;
this.x = i * 40;
this.y = j * 10 + 50;
this.i = i;
this.j = j;
}
public void tick() {
}
public void paint(Graphics g) {
g.setColor(c);
g.fillRect(x, y, Breakout.brickWidth, Breakout.brickHeight);
}
public void hit(Ball b) {
if (b.yThen > y + Breakout.brickHeight) {
b.yv = -b.yv;
b.yNow = 2 * (y + Breakout.brickHeight) - b.yNow;
}
if (b.yThen < y) {
b.yv = -b.yv;
b.yNow = 2 * (y) - b.yNow;
}
if (b.xThen > x + Breakout.brickWidth) {
b.xv = -b.xv;
b.xNow = 2 * (x + Breakout.brickWidth) - b.xNow;
}
if (b.xThen < x) {
b.xv = -b.xv;
b.xNow = 2 * (x) - b.xNow;
}
brick[i][j] = null;
}
}
到目前为止,这是我的colorBrick子类所拥有的:
package Breakout;
import java.awt.Color;
public class ColorBrick extends Brick {
Color colors[] = {Color.red, Color.green, Color.blue, Color.yellow};
public ColorBrick(Color[] colors, Brick[][] brick, int i, int j){
this.colors = colors;
this.brick = brick;
this.i = i;
this.j = j;
}
public void tick(){
}
}
在这一点上,我碰壁了,我不确定从这里开始该怎么做。 我的教练说,由于某种原因,tick方法在超类中需要为空。 如果需要为空,那他为什么要我们把它放在那里? 我也不确定应该在子类tick方法中添加什么。 我到底是朝着正确的方向前进,还是到目前为止我做的一切完全错误? 任何指导将不胜感激!
如果有用,这是我的主要突破代码:
package Breakout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Breakout extends javax.swing.JFrame {
public static final int fieldHeight = 600;
public static final int fieldWidth = 400;
public int diameter = 5;
public int xNow = 200 - (diameter / 2);
public int yNow = 300 - (diameter - 2);
public int paddleWidth = 50;
public int paddleHeight = 5;
public int platform = 580;
public static int mousex;
public int mousey;
public static int brickWidth = 40;
public static int brickHeight = 10;
public Random randoms = new Random();
Brick[][] bricks = new Brick[arrayWide][arrayHigh];
public static boolean startUp;
public static int arrayWide = 10;
public static int arrayHigh = 5;
Ball ball = new Ball(200 - (diameter / 2), 20 /*300 - (diameter /2)*/, 0, 0, diameter, Color.white);
Paddle myPaddle = new Paddle(platform, paddleWidth, paddleHeight);
/**
* Creates new form Breakout
*/
public Breakout() {
initComponents();
clock.start();
}
public class MyPanel extends JPanel {
@Override
public void paint(Graphics g) {
super.paint(g);
if (startUp) {
ball.paint(g);
}
myPaddle.paint(g);
for (int i = 0; i < arrayWide; i++) {
for (int j = 0; j < arrayHigh; j++) {
if (bricks[i][j] != null) {
bricks[i][j].paint(g);
}
}
}
// Insert code to paint the scene here.
// Use methods in the Graphics class to do the painting
// Remember coordinates use (0,0) at the top left
}
}
public Timer clock = new Timer(50, new ActionListener() { // 50ms delay between ticks
public void actionPerformed(ActionEvent e) {
tick(); // Write a method named tick to advance your game
jPanel1.repaint();
}
}); // panel is the name of the JPanel that displays the game
public void launchball() {
}
public void tick() {
ball.move();
Brick brick2 = brickAt(ball);
if (brick2 != null) {
brick2.hit(ball);
}
myPaddle.move(mousex);
myPaddle.bounce(ball);
System.out.println();
}
public Brick brickAt(Ball b) {
int j = (int) (b.yNow - 50) / 10;
int i = (int) (b.xNow / 40);
if (i < arrayWide && i >= 0 && j < arrayHigh && j >= 0) {
return (bricks[i][j]);
}
return null;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPopupMenu1 = new javax.swing.JPopupMenu();
jPanel2 = new javax.swing.JPanel();
jPanel1 = new MyPanel();
jLabel1 = new javax.swing.JLabel();
start = new javax.swing.JButton();
org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 100, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(0, 0, 0));
jPanel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
mouseMove(evt);
}
});
org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 400, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 600, Short.MAX_VALUE)
);
jLabel1.setFont(new java.awt.Font("Hobo Std", 1, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(153, 51, 255));
jLabel1.setText("Breakout");
start.setFont(new java.awt.Font("Hobo Std", 0, 13)); // NOI18N
start.setForeground(new java.awt.Color(255, 51, 0));
start.setText("Start");
start.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(164, 164, 164)
.add(jLabel1))
.add(layout.createSequentialGroup()
.add(15, 15, 15)
.add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(175, 175, 175)
.add(start)))
.addContainerGap(17, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(16, 16, 16)
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(start)
.addContainerGap(10, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void mouseMove(java.awt.event.MouseEvent evt) {
mousex = evt.getX();
mousey = evt.getY();
}
private void startActionPerformed(java.awt.event.ActionEvent evt) {
startUp = true;
ball.xNow = 200 - (diameter / 2);
ball.yNow = 300 - (diameter - 2);
ball.xv = 0;
ball.yv = 8;
for (int i = 0; i < arrayWide; i++) {
for (int j = 0; j < arrayHigh; j++) {
if ((j % 2 == 0 && i % 2 == 0) || (j % 2 == 1 && i % 2 == 1)) {
bricks[i][j] = new Brick(Color.magenta, bricks, i, j);
} else {
bricks[i][j] = new Brick(Color.gray, bricks, i, j);
}
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Breakout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Breakout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Breakout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Breakout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Breakout().setVisible(true);
}
});
}
由于这听起来像homework.classwork,所以我不会详细介绍。
大概,某事(TBD)将每5秒(或定期)调用一次tick()。 普通的Brick
什么都不做。 您的ColorBrick
应该每5秒钟更改为下一个颜色。 它需要以某种方式知道它的当前颜色,然后更改为下一个。
Brick
需要有一个空的tick
方法,以便另一个类只需要处理Bricks。 调用tick
的类不需要知道它是Brick
还是ColorBrick
。 tick
的行为由运行时类指定; 这是多态性-相关类对同一方法调用做出不同反应的能力。
子类tick
方法需要跟踪已生成的tick数量。 必要时,它将更改Color变量c
。
我可能要进行的另一项更改是在您的ColorBrick
构造函数中:利用super
调用超类构造函数,以免重复您的代码。
另外,声明实例变量( c
, x
, y
等) protected
以便只有类本身和子类才能直接访问它们。
tick方法需要在超类上存在,因为我想这样做的目的是针对每个存在的Brick都将调用tick()(可能在主Breakout类中,可能在循环中)。 超类中的tick()方法指定“默认”行为,该行为不执行任何操作。 对于您的ColorBrick类,当调用刻度时,颜色需要每五个刻度更改一次,因此您需要在子类(ColorBrick)中指定这种特殊的行为方式。
为此,ColorBrick需要一种方法来计数tick()被调用的次数。 添加了可以执行此操作的代码后,您就可以考虑在某些刻度上更改ColorBrick的颜色:您的ColorBrick已经“知道”它的当前颜色,因为它是从Brick扩展而来的,Brick具有Color属性( c),因此是在某些价格变动时更改该值的情况。
我已经故意离开了这个模糊的地方,因为我不想为您完成任务,但是请随时提出任何问题。
您需要在ColorBrick
实现您的tick
方法,如下所示:
private int i = 0;
public void tick(){
c = colors[i++ % colors.length];
}
现在,在制作图形应用程序时,您可以简单地使用Brick
类来创建ColorBricks
。 例如,添加多块砖砌成一堵墙:
Brick[][] wall = new Brick[5][5];
上面数组中的某些Brick
可能是ColorBrick
。 这允许为每个Brick
对象具有通用接口,即tick()
方法。 但是对于ColorBrick
此方法实际上会更改Brick
的颜色,就像其他Brick
它什么也不做!
您可以做更多诸如DancingBrick
类的事情,这些事情在每次tick
之后都会改变大小。 您不需要对图形实现进行彻底的更改即可添加不同种类的Brick
因为它使用的基本类型为Brick
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.