1

我刚刚加入了这个很棒的社区,但很遗憾我承认我在这里的第一篇文章与一个痛苦的错误有关。当我做我的家庭作业时,我遇到了各种各样的错误。到目前为止的故事:

  • 我必须创建一个继承 JButton 功能的抽象 Brick 类,它支持一个抽象方法,我称之为brickSpecialAction(),由各种砖子类(小丑砖、洗牌砖、彩色砖)实现。
  • 我还必须创建一个继承 JFrame 并为游戏添加棋盘功能的 Grid 类,并将功能扩展到每次用户没有可用动作时改变关卡,并且超过分数阈值,每次按下时就像一个 ActionListener其中一块砖等等
  • 除了这些类,我还有一些小类,比如关卡,它们支持游戏,但到目前为止没有做任何戏剧性的事情,或者与错误有​​关的任何事情。
  • 错误的来源:在制作 Brick 的第一个子类 ColourBrick(具有一定背景颜色的砖块)期间,我必须提供brickSpecialAction 方法的实现,每次我都会由侦听器类(Grid)调用按那种类型的砖。现在,起初,该方法以空指针异常折磨了我可怜的灵魂。在对代码进行了一些进一步的研究和改进之后,我想出了一个可行的解决方案,但实际上只是造成了更大的混乱:它没有正确执行,并且手头出现了 StackOverflowError。

到目前为止的课程:

基础砖类

package gr.teicrete.epp.ooplab.brickbreaker;

import java.awt.Color;
import java.awt.Container;
import java.awt.Point;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
 * The Brick class will provide general functionality to our bricks.
 *
 * @author Fokis
 */
public abstract class Brick extends JButton{

    private Point brickPosition; // The brick's position
    private Container cont;

    /**
     * The Brick constructor used to initialize the bricks. Not really used as
     * we cannot instantiate the brick class, being abstract and such.
     *
     * @param posx The brick's x position
     * @param posy The brick's y position
     */
     public Brick(int posx, int posy) {
        this.brickPosition = new Point(posx, posy);
        this.setVisible(true);
     }

     /**
      * The public accessor method to the brick's position
      * @return The brick's position
      */
      public Point getBrickPosition() {
         return this.brickPosition;
      }

     /**
      * The public accessor method to the brick's container.
      *
      * @return The grid's container.
      */
      public Grid getContainer() {
         return (Grid) this.cont;
      }

      public abstract int brickSpecialAction(Brick brickie);
 }

基本的 ColorBrick 类:

package gr.teicrete.epp.ooplab.brickbreaker;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.util.Random;

/**
 * The ColourBrick class provides functionality to the colourful bricks.
 *
 * @author Fokis
 */
 public class ColourBrick extends Brick {

/**
 * The constructor used to initialize our colour bricks.
 *
 * @param posx The x position of the brick. Used for indexing later.
 * @param posy The y position of the brick. Used for indexing later.
 * @param seed The seed to the random number generator, so as to pick
 * colours available at each level.
 */
public ColourBrick(int posx, int posy, int seed) {
    super(posx, posy);
    this.setBackground(this.pickColour(seed));
    this.setPreferredSize(new Dimension(50, 44));
}

/**
 * Public method used to initialise our bricks with a colour.
 *
 * @param seed the initial seed we provide to the random number generator
 * @return The color of the brick to be initialized.
 */
 public Color pickColour(int seed) {

    Random randomColour = new Random(); // A random object, for RNG
    Color assignedColor; // Used to store the color we picked

    int potentialColour = randomColour.nextInt(seed); // Picking a random num

    switch (potentialColour) {
        case 0:
            assignedColor = Color.RED;
            break;
        case 1:
            assignedColor = Color.CYAN;
            break;
        case 2:
            assignedColor = Color.GREEN;
            break;
        case 3:
            assignedColor = Color.YELLOW;
            break;
        case 4:
            assignedColor = Color.PINK;
            break;
        case 5:
            assignedColor = Color.MAGENTA;
            break;
        case 6:
            assignedColor = Color.BLACK;
            break;
        case 7:
            assignedColor = Color.ORANGE;
            break;
        case 8:
            assignedColor = Color.GREEN;
            break;
        default:
            // Not really needed, but we provide it to ensure that the compiler
            // won't argue that assignedColor might be uninitialized
            assignedColor = null;
    }
    return assignedColor;
}

/**
 * The method used to destroy the bricks that we click on.
 *
 * @param brickie Used for the recursive calls of the method.
 * @return The total number of bricks destroyed.
 */
@Override
public int brickSpecialAction(Brick brickie) {

    int totalRemovedBricks = 0; // Used to calculate the total number of removed bricks

    this.setVisible(false); // Making it invisible
    totalRemovedBricks++; // Counting it as a brick destroyed, in order to calculate the score later

    Grid omnigrid = (Grid) this.getTopLevelAncestor();
    Point brickPosition = this.getBrickPosition();

    for (int i = 0; i < 4; i++) {
        switch (i) {
            case 0:
                // Checking to see if the brick above the one we have now has the same colour as the one we are in now
                if (omnigrid.getBrickByXAndY(brickPosition.x, brickPosition.y + 1).getBackground().equals(this.getBackground())) {
                    totalRemovedBricks += brickSpecialAction(omnigrid.getBrickByXAndY(brickPosition.x, brickPosition. y + 1));
                }
                break;
            case 1:
                // Checking to see if the brick beyond the one that we have now has the same colour as the one we are in now
                if (omnigrid.getBrickByXAndY(brickPosition.x, brickPosition.y - 1).getBackground().equals(this.getBackground())) {
                    totalRemovedBricks += brickSpecialAction(omnigrid.getBrickByXAndY(brickPosition.x, brickPosition.y - 1));
                }
                break;
            case 2:
                // Checking to see if the brick on the left of the one we have now has the same colour as the one we are in now
                if (omnigrid.getBrickByXAndY(brickPosition.x - 1, brickPosition.y).getBackground().equals(this.getBackground())) {
                    totalRemovedBricks += brickSpecialAction(omnigrid.getBrickByXAndY(brickPosition.x - 1, brickPosition.y));
                }
                break;
            case 3:
                // Checking to see if the brick on the right of the one we have now has the same colour as the one we are in now
                if (omnigrid.getBrickByXAndY(brickPosition.x + 1, brickPosition.y).getBackground().equals(this.getBackground())) {
                    totalRemovedBricks += brickSpecialAction(omnigrid.getBrickByXAndY(brickPosition.x + 1, brickPosition.y));
                }
                break;
        }
    }
    return totalRemovedBricks; // returning the total ammount of bricks destroyed used to calculate the score later
}
}

和网格类:

package gr.teicrete.epp.ooplab.brickbreaker;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;

/**
 * The Grid class will provide objects that will be used as our board for the
 * game.
 *
 * @author Fokis
 */
 public class Grid extends JFrame implements ActionListener {

private Levels currentLevel; // A reference to the current level
private int generalHiscore; //  A variable storing the current HiScore
private float currentScore = 0.0f; // A variable storing the current Score
private int levelsElevated = 1; // A variable used to store the levels the player has elevated each time
private boolean changed;
private String playerName; // A variable used to store the current player's name

/**
 * The Grid constructor. Pretty much handles everything. From initialising
 * player score to filling the grid with bricks.
 *
 * @param playerName The current player's name.
 */
public Grid(String playerName) {
    super();
    this.currentLevel = new Levels(levelsElevated);
    this.generalHiscore = 0;
    this.currentScore = 0;
    this.playerName = playerName;
    this.setLayout(new GridLayout(currentLevel.getLevelRows(), currentLevel.getLevelColumns()));
    initialize();
    pack();

    this.setVisible(true);
    this.setTitle("Player name: " + playerName + " Current Score: " + currentScore + " Hiscore: " + currentLevel.getHiScore()); // To be reviewed.
    this.setDefaultCloseOperation(Grid.EXIT_ON_CLOSE);
}

/**
 * The method that will be invoked everytime we need to change the level
 *
 * @return Whether or not the method was successful.
 */
public boolean changeLevel() {
    levelsElevated++;
    this.currentLevel = new Levels(levelsElevated);
    this.setLayout(new GridLayout(currentLevel.getLevelRows(), currentLevel.getLevelColumns()));
    return true;
}

/**
 * The method that will be invoked everytime we need to see if the game
 * should change level, or if the player lost.
 */
public void checkState() {
    if (hasAvailableMoves() == false && isAboveScoreThreshold() == true) {
        changed = changeLevel();
    } else if (hasAvailableMoves() == false && isAboveScoreThreshold() == false) {
        System.out.println("What a pity. You lost.");
    }
}

/**
 * The method that will be used to calculate the score.
 *
 * @param removedBricks The total number of bricks removed each time. Used
 * to actually calculate the score.
 * @return The player's current score.
 */
public float calculateScore(int removedBricks) {
    if (removedBricks <= 4) {
        currentScore += removedBricks;
    } else if (removedBricks >= 5 && removedBricks <= 12) {
        currentScore += (removedBricks * 1.5);
    } else {
        currentScore += 2 * removedBricks;
    }

    if (currentScore > currentLevel.getHiScore()) {
        currentLevel.setHiScore(currentScore);
    }

    return currentScore;
}

/**
 * The method that will be used to check if the player is above each level's
 * winning score threshold.
 *
 * @return The current state of the player's score.
 */
public boolean isAboveScoreThreshold() {
    if (currentScore >= currentLevel.getLevelRequiredScore()) {
        return true;
    } else {
        return false;
    }
}

/**
 * The method that will be used to check if the player has available moves
 * left. Will later be used to check whether or not we should change level.
 * NOT YET IMPLEMENTED.
 *
 * @return Whether or not the player has available moves left
 */
public boolean hasAvailableMoves() {
    return true;
}

/**
 * The method that will be invoked everytime we need to parse one of the
 * bricks.
 *
 * @param x The x position of the brick
 * @param y The y position of the brick
 * @return The brick that we want to manipulate.
 */
public Brick getBrickByXAndY(int x, int y) {
    return (Brick) this.getContentPane().getComponent((y * this.currentLevel.getLevelRows()) + x);
}

/**
 * The method that will be invoked to actually fill our Grid with bricks.
 */
public void initialize() {

    int acceptedBricks; // To be used for calculation of acceptedBricks

    for (acceptedBricks = 0; acceptedBricks < currentLevel.getLevelTotalBricks(); acceptedBricks++) {
        for (int x = 1; x <= currentLevel.getLevelRows(); x++) {
            for (int y = 1; y <= currentLevel.getLevelColumns(); y++) {
                Brick newBrick = new ColourBrick(x, y, currentLevel.getLevelAvailableColours());
                newBrick.addActionListener(this);
                this.add(newBrick);
                acceptedBricks++;
            }
        }
    }
}

@Override
public void actionPerformed(ActionEvent evt) {
    Brick brickClicked = (Brick) evt.getSource();
    calculateScore(brickClicked.brickSpecialAction(brickClicked));
    this.setTitle("Player name: " + playerName + " Current Score: " + currentScore + " Hiscore: " + currentLevel.getHiScore());
    this.checkState();
}
}

重要提示:我不会便宜到向其他人寻求项目或问题的解决方案,我只是希望有人向我解释为什么我会出现此错误。在那之后,我将尝试独自解决这个问题。但请帮助我。我已经很努力了。

编辑:堆栈跟踪:

Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
    at java.awt.Component.isVisible_NoClientCode(Component.java:1288)
    at java.awt.Component.isVisible(Component.java:1285)
    at javax.swing.JComponent.setVisible(JComponent.java:2639)
    at gr.teicrete.epp.ooplab.brickbreaker.ColourBrick.brickSpecialAction(ColourBrick.java:90)
    at gr.teicrete.epp.ooplab.brickbreaker.ColourBrick.brickSpecialAction(ColourBrick.java:101)
    at gr.teicrete.epp.ooplab.brickbreaker.ColourBrick.brickSpecialAction(ColourBrick.java:101)
    at gr.teicrete.epp.ooplab.brickbreaker.ColourBrick.brickSpecialAction(ColourBrick.java:101)
    at gr.teicrete.epp.ooplab.brickbreaker.ColourBrick.brickSpecialAction(ColourBrick.java:101)
    at gr.teicrete.epp.ooplab.brickbreaker.ColourBrick.brickSpecialAction(ColourBrick.java:101)
    at gr.teicrete.epp.ooplab.brickbreaker.ColourBrick.brickSpecialAction(ColourBrick.java:101)
    at gr.teicrete.epp.ooplab.brickbreaker.ColourBrick.brickSpecialAction(ColourBrick.java:101)
    at gr.teicrete.epp.ooplab.brickbreaker.ColourBrick.brickSpecialAction(ColourBrick.java:101)
    at gr.teicrete.epp.ooplab.brickbreaker.ColourBrick.brickSpecialAction(ColourBrick.java:101)
    at 

它一直像这样一直在吓人。

4

3 回答 3

2

您的brickSpecialAction() 方法包含对其自身的调用。如果没有适当的控制,这会使您陷入无限递归循环。StackOverflow 错误经常是由这种情况引起的。

于 2012-05-30T20:51:06.380 回答
1

出现问题是因为您检查上面的块是否颜色相同,如果是则重复相同的逻辑,并且该逻辑正在检查下面的块是否颜色相同,如果是则重复相同的逻辑。因此,如果顶部的块与底部的块颜色相同,则它会来回弹跳,直到出现堆栈溢出。也许在您检查它们时删除这些块,或者制作一些标志以表示它们已经被标记为要删除并更改逻辑以检查它而不是无限地重新诅咒。

我猜你的代码还有其他问题,但这可能会让你克服当前的错误......

public int brickSpecialAction(Brick brickie) {

    int totalRemovedBricks = 0; // Used to calculate the total number of removed bricks
    if (!this.isVisible)    //Or whatever you can check to see if you have set this invisible already
        return;             // You've already executed on this block
    this.setVisible(false); // Making it invisible
于 2012-05-30T21:00:13.187 回答
1

你的问题绝对是brickSpecialAction() 中的递归

从概念上讲,这与您要完成的工作非常相似。

于 2012-05-30T21:08:12.483 回答