我的connect4游戏中的主要方法问题

时间:2011-05-17 00:42:27

标签: java swing awt

我的主要方法有问题,我运行它我的代码无法编译因为这个问题: "线程中的异常" main"显示java.lang.NullPointerException     在UI.ConnectFourFrame.refreshUI(ConnectFourFrame.java:96)     在UI.ConnectFourFrame。(ConnectFourFrame.java:43)     在main.main(main.java:11)​​"

我试图看看问题是什么,但我无法弄明白,有人可以帮助我

package Game;

import java.util.ArrayList;

public class ConnectFourBoard {


    // This constant is used to indicate the width and height, in cells,
    // of the board.  Since we want an 8x8 board, we'll set it to 8.
    private static final int WIDTH = 7;
    private static final int HEIGHT = 6;
    private ConnectFourCell[][] currentPlayer;



    // The current state the Othello board is defined with these two
    // fields: a two-dimensional array holding the state of each cell,
    // and a boolean value indicating whether it's the black player's
    // turn (true) or the white player's turn (false).
    private ConnectFourCell[][] cells;
    private boolean isBlueTurn;

    // Since the board is a model and it needs to notify views of changes,
    // it will employ the standard "listener" mechanism of tracking a list
    // of listeners and firing "events" (by calling methods on those
    // listeners) when things change.
    private ArrayList<ConnectFourListener> listeners;


    public ConnectFourBoard()
    {
        // Arrays, in Java, are objects, which means that variables of
        // array types (like cells, which has type OthelloCell[][]) are
        // really references that say where an array lives.  By default,
        // references point to null.  So we'll need to create an actual
        // two-dimensional array for "cells" to point to.
        cells = new ConnectFourCell[WIDTH][HEIGHT];
        listeners = new ArrayList<ConnectFourListener>();
        reset();
    }

    public void reset(){
        for (int i = 0; i<WIDTH ; i++){
            for (int j = 0; j<HEIGHT; j++){

                cells[i][j] = ConnectFourCell.NONE; 
            }
        }

        isBlueTurn = true; 
    }

    public void addConnectFourListener(ConnectFourListener listener)
    {
        listeners.add(listener);
    }


    public void removeConnectFourListener(ConnectFourListener listener)
    {
        if (listeners.contains(listener))
        {
            listeners.remove(listener);
        }
    }


    // These are fairly standard "fire event" methods that we've been building
    // all quarter, one corresponding to each method in the listener interface.

    private void fireBoardChanged()
    {
        for (ConnectFourListener listener : listeners)
        {
            listener.boardChanged();
        }
    }


    private void fireGameOver()
    {
        for (ConnectFourListener listener : listeners)
        {
            listener.gameOver();
        }
    }


    // isBlackTurn() returns true if it's the black player's turn, and false
    // if it's the white player's turn.
    public boolean isBlueTurn()
    {
        return isBlueTurn;
    }

    public int getWidth()
    {
        return WIDTH;


    }

    public int getHeight(){

        return HEIGHT; 
    }
    // getBlackScore() calculates the score for the black player.
    public int getBlackScore()
    {
        return getScore(ConnectFourCell.BLUE);
    }


    // getWhiteScore() calculates the score for the white player.
    public int getWhiteScore()
    {
        return getScore(ConnectFourCell.RED);
    }

    // getScore() runs through all the cells on the board and counts the
    // number of cells that have a particular value (e.g., BLACK or WHITE).
    // This method uses the naive approach of counting them each time
    // it's called; it might be better to keep track of this score as we
    // go, updating it as tiles are added and flipped.
    private int getScore(ConnectFourCell cellValue)
    {
        int score = 0;

        for (int i = 0; i < WIDTH; i++)
        {
            for (int j = 0; j < HEIGHT; j++)
            {
                if (cells[i][j] == cellValue)
                {
                    score++;
                }
            }
        }

        return score;
    }




    // getWhiteScore() calculates the score for the white player.
    public int getRedScore()
    {
        return getScore(ConnectFourCell.RED);
    }

    public int getBlueScore() {
        // TODO Auto-generated method stub
        return getScore(ConnectFourCell.BLUE);
    }


    public ConnectFourCell getCell(int x, int y)
    {
        if (!isValidCell(x, y))
        {
            throw new IllegalArgumentException(
                "(" + x + ", " + y + ") is not a valid cell");
        }

        return cells[x][y];
    }
    /**
    * The drop method.
    *
    * Drop a checker into the specified HEIGHT,
    * and return the WIDTH that the checker lands on.
    */
    int drop(int HEIGHT) {
    if (hasWon()) {
    return -1;
    }

    for ( ; WIDTH<6 && HEIGHT != 0; WIDTH++) { };

    if (WIDTH==6) {
    // if the WIDTH is 6, it went through all 6 WIDTHs
    // of the cells, and couldn't find an empty one.
    // Therefore, return false to indicate that this
    // drop operation failed.
    return -1;
    }
    // fill the WIDTH of that HEIGHT with a checker.
    cells[HEIGHT][WIDTH] = currentPlayer[HEIGHT][WIDTH];
    // alternate the players
    //currentPlayer = (currentPlayer%2)+1;
    return WIDTH;
    }
    /**
    * The toString method
    *
    * Returns a String representation of this
    * Connect Four (TM) game.
    */
    public String toString() {
    String returnString = "";
    for (int WIDTH=5; WIDTH>=0; WIDTH--) {
    for (int HEIGHT=0; HEIGHT<7; HEIGHT++) {
    returnString = returnString + cells[HEIGHT][WIDTH];
    }
    returnString = returnString + "\n";
    }
    return returnString;
    }
    /**
    * The hasWon method.
    *
    * This method returns true if one of the
    * players has won the game.
    */
    public boolean hasWon() {
    boolean status = false;
    // check for a horizontal win
    for (int WIDTH=0; WIDTH<6; WIDTH++) {
    for (int HEIGHT=0; HEIGHT<4; HEIGHT++) {
    if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE)  &&
    cells[HEIGHT][WIDTH] == cells[HEIGHT+1][WIDTH] &&
    cells[HEIGHT][WIDTH] == cells[HEIGHT+2][WIDTH] &&
    cells[HEIGHT][WIDTH] == cells[HEIGHT+3][WIDTH]) {
    status = true;
    }
    }
    }
    // check for a vertical win
    for (int WIDTH=0; WIDTH<3; WIDTH++) {
    for (int HEIGHT=0; HEIGHT<7; HEIGHT++) {
    if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE)  &&
    cells[HEIGHT][WIDTH] == cells[HEIGHT][WIDTH+1] &&
    cells[HEIGHT][WIDTH] == cells[HEIGHT][WIDTH+2] &&
    cells[HEIGHT][WIDTH] == cells[HEIGHT][WIDTH+3]) {
    status = true;
    }
    }
    }
    // check for a diagonal win (positive slope)
    for (int WIDTH=0; WIDTH<3; WIDTH++) {
    for (int HEIGHT=0; HEIGHT<4; HEIGHT++) {
        if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE) &&
    cells[HEIGHT][WIDTH] == cells[HEIGHT+1][WIDTH+1] &&
    cells[HEIGHT][WIDTH] == cells[HEIGHT+2][WIDTH+2] &&
    cells[HEIGHT][WIDTH] == cells[HEIGHT+3][WIDTH+3]) {
    status = true;
    }
    }
    }
    // check for a diagonal win (negative slope)
    for (int WIDTH=3; WIDTH<6; WIDTH++) {
    for (int HEIGHT=0; HEIGHT<4; HEIGHT++) {
        if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE)  &&
    cells[HEIGHT][WIDTH] == cells[HEIGHT+1][WIDTH-1] &&
    cells[HEIGHT][WIDTH] == cells[HEIGHT+2][WIDTH-2] &&
    cells[HEIGHT][WIDTH] == cells[HEIGHT+3][WIDTH-3]) {
    status = true;
    }
    }
    }
    return status;
    }


    private boolean isValidCell(int x, int y)
    {
        return x >= 0 && x < WIDTH
              && x>= 0 && x<HEIGHT
              && y >= 0 && y < WIDTH
              && y>= 0 && y<HEIGHT;
    }
}


package UI;



import java.awt.*; 


import javax.swing.*;

import UI.ConnectFourBoardPanel;

import Game.ConnectFourBoard;
import Game.ConnectFourListener;

public class ConnectFourFrame extends JFrame implements ConnectFourListener {

    // Variables

    private ConnectFourBoard board;

    private JLabel scoreLabel;
    private ConnectFourBoardPanel boardPanel;
    private JLabel statusLabel;


    public ConnectFourFrame()
    {
        // The frame builds its own model.
        ConnectFourBoard board = new ConnectFourBoard();

        // We want the frame to receive notifications from the board as its
        // state changes.
        System.out.println(this);
        board.addConnectFourListener(this);

        setTitle("Informatics 45 Spring 2011: ConnectFour Game");
        setSize(700, 700);
        setResizable(true);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setBackground(Color.BLACK);

        buildUI();
        refreshUI();
    }


    private void buildUI()
    {
        GridBagLayout layout = new GridBagLayout();
        getContentPane().setLayout(layout);

        Font labelFont = new Font("SansSerif", Font.BOLD, 18); 

        scoreLabel = new JLabel();
        scoreLabel.setForeground(Color.WHITE);
        scoreLabel.setFont(labelFont);
        layout.setConstraints(
            scoreLabel,
            new GridBagConstraints(
                0, 0, 1, 1, 1.0, 0.0,
                GridBagConstraints.CENTER,
                GridBagConstraints.NONE,
                new Insets(10, 10, 10, 10), 0, 0));
        getContentPane().add(scoreLabel);

        boardPanel = new ConnectFourBoardPanel(board);
        layout.setConstraints(
            boardPanel,
            new GridBagConstraints(
                0, 1, 1, 1, 1.0, 1.0,
                GridBagConstraints.CENTER,
                GridBagConstraints.BOTH,
                new Insets(10, 10, 10, 10), 0, 0));
        getContentPane().add(boardPanel);

        statusLabel = new JLabel();
        statusLabel.setForeground(Color.WHITE);
        statusLabel.setFont(labelFont);
        layout.setConstraints(
            statusLabel,
            new GridBagConstraints(
                0, 2, 1, 1, 1.0, 0.0,
                GridBagConstraints.CENTER,
                GridBagConstraints.NONE,
                new Insets(10, 10, 10, 10), 0, 0));
        getContentPane().add(statusLabel);
    }

    private void refreshUI()
    {
        // Refreshing the UI means to change the text in each of the
        // two labels (the score and the status) and also to ask the
        // board to repaint itself.

        scoreLabel.setText(
            "Blue: " + board.getBlueScore() +
            "          Red: " + board.getRedScore());

        statusLabel.setText(
            (board.isBlueTurn() ? "Blue's" : "Red's")
            + " turn");

        boardPanel.repaint();
    }

    // These are the ConnectFourBoardListener event-handling methods.

    public void boardChanged()
    {
        // When the board changes, we'll refresh the entire UI.  (There
        // are times when this approach is too inefficient, but it will
        // work fine for our relatively simple UI.)

        refreshUI();
    }


    public void gameOver()
    {
        // When the game is over, we'll pop up a message box showing the final
        // score, then, after the user dismisses the message box, dispose of
        // this window and end the program.

        JOptionPane.showMessageDialog(
            this,
            "Game over!\nFinal score: " + scoreLabel.getText(),
            "Game Over",
            JOptionPane.INFORMATION_MESSAGE);

        dispose();
    }

}

2 个答案:

答案 0 :(得分:2)

初始化本地var而不是你的成员var

    ConnectFourBoard board = new ConnectFourBoard();

将该行更改为:

    board = new ConnectFourBoard();

答案 1 :(得分:0)

查看完整堆栈跟踪会很有帮助,但是{{1and1}}似乎是返回整数,而您尝试使用getBlueScore()设置它将需要一个字符串。