0
我正處於學習Java的早期階段,我只是想做一個簡單的Pong類遊戲。我有2班Wall和Ball。它們幾乎完全相同,只是它們在它們中都有不同的java.awt.geom子類(一個具有Ellipse2d和一個Rectangle2D),但幾乎在所有其他方面它們都是相同的(Ball類將有更多的變量處理velocity ,但其他方面相同)。乒乓遊戲:牆壁和球幾乎完全一樣 - 如何超級Ellipse2D和Rectangle2D?
我的問題是,現在我看到有冗餘我想做一個超類GameObject。我只是不知道如何處理的事實,兩個子類指和Ellipse2D的矩形2D
類華爾街{
private double posX, posY, width, height; // wall position and dimensions
Rectangle2D wall2D;
/**
*
*/
public Wall(double Xin, double Yin, double widthIn, double heightIn) { // passes in variables and creates a new Ellipse2D
posX = Xin;
posY = Yin;
width = widthIn;
height = heightIn;
wall2D = new Rectangle2D.Double(posX, posY, width, height);
}
private void setWall2D() { // makes the Wall2D have the same location/dimensions as the variables in this class
wall2D.setFrame(posX, posY, width, height);
}
Rectangle2D getWall2D() { // returns the actual Rectangle2D so it can get displayed on the screen when needed
return wall2D;
}
// getters
double getPositionX() {
return posX;
}
double getPositionY() {
return posY;
}
double getHeight() {
return height;
}
double getWidth() {
return width;
}
// setters (all have to call setWall2D after variable has been set! - to update the actual Rectangle2D shape)
void setPositionX(double xIn) {
posX = xIn;
setWall2D();
}
void setPositionY(double yIn) {
posY = yIn;
setWall2D();
}
void setHeight(double heightIn) {
height = heightIn;
setWall2D();
}
void setwidth(double widthIn) {
width = widthIn;
setWall2D();
}
}
這裏是我的球類
class Ball {
private double posX, posY, width, height; // ball position and dimensions
Ellipse2D ball2D;
/**
*
*/
public Ball(double Xin, double Yin, double widthIn, double heightIn) { // passes in variables and creates a new Ellipse2D
posX = Xin;
posY = Yin;
width = widthIn;
height = heightIn;
ball2D = new Ellipse2D.Double(posX, posY, width, height);
}
private void setBall2D() { // makes the Ball2D have the same location/dimensions as the variables in this class
ball2D.setFrame(posX, posY, width, height);
}
Ellipse2D getBall2D() { // returns the actual Ellipse2D so it can get displayed on the screen when needed
return ball2D;
}
// getters
double getPositionX() {
return posX;
}
double getPositionY() {
return posY;
}
double getHeight() {
return height;
}
double getWidth() {
return width;
}
// setters (all have to call setBall2D after variable has been set! - to update the actual Ellipse2D shape)
void setPositionX(double xIn) {
posX = xIn;
setBall2D();
}
void setPositionY(double yIn) {
posY = yIn;
setBall2D();
}
void setHeight(double heightIn) {
height = heightIn;
setBall2D();
}
void setwidth(double widthIn) {
width = widthIn;
setBall2D();
}
}
任何意見,將不勝感激。提前致謝。
「你還可以指定合適的子類中相應的構造......」 ...... 這就是我有一部分麻煩與。任何人想幫助給我一行代碼? – ljg
我可以忽略超類中的RectangularShape內容,只需將它們添加到Wall和Ball中,但肯定會有更優雅的方式實現它?我的意思是除了他們處理的2D形狀類型之外,上面的Ball和Wall是相同的。 – ljg
添加了一些代碼... –