努力设计一个滑动的3x3拼图,其中包含交换拼贴的方法

时间:2016-11-24 13:22:54

标签: java arrays nullpointerexception indexoutofboundsexception puzzle

我正在尝试设计一个简单的3x3滑动益智游戏。您可以移动的唯一图块是空白图块,可以与任何相邻图块交换。目前没有最终目标,但我在实施拼图时遇到了麻烦,并且能够交换拼图。当我测试我的交换方法时,我一直得到java null指针异常,并且似乎无法解决这个问题。我知道这个错误是什么,但不知道为什么它会出现在我的代码中。

public class Game() {

    public Node[][] buildPuzzle() {

        Node[][] puzzle = new Node[3][3];

        Node One = new Node("1", 0, 0, null, puzzle[0][1], null, puzzle[1][0]);
        Node Two = new Node("2", 1, 0, null, puzzle[1][1], puzzle[0][0], puzzle[2][0]); 
        Node Three = new Node("3", 2, 0, null, puzzle[2][1], puzzle[1][0], null);

        Node Four = new Node("4", 0, 1, puzzle[0][0], puzzle[0][2], null, puzzle[1][1]);
        Node Five = new Node("5", 1, 1, puzzle[1][0], puzzle[1][2], puzzle[0][1], puzzle[2][1]);
        Node Six = new Node("6", 2, 1, puzzle[2][0], puzzle[2][2], puzzle[1][1], null);

        Node Seven = new Node("7", 0, 2, puzzle[0][1], null, null, puzzle[1][2]);
        Node Eight = new Node("8", 1, 2, puzzle[1][1], null, puzzle[0][2], puzzle[2][2]);
        Node blank = new Node("blank", 2, 2, puzzle[2][1], null, puzzle[1][2], null);

    }

    public void swapAbove (Node[][] puzzle, Node blank, Node blankAbove) {

        if (blank.getLabel() == "blank" && blankAbove != null){

            Node temp = blank;
            Node temp2 = blankAbove;
            blank = temp2;
            blankAbove = temp;

            puzzle[temp.getX()][temp.getY()] = blankAbove;
            puzzle[temp2.getX()][temp.getY()] = blank;

        } else { 

            System.out.println("Invalid Move");

        }

    }

    //also have swapUp swapLeft and swapRight methods
}

这是我的Node类:

public class Node {

    String label;
    int x;
    int y;
    Node above;
    Node below;
    Node left;
    Node right;

    public Node(String label, int x, int y, Node above, Node below, Node left, Node right) {
            this.label = label;
            this.x = x;
            this.y = y;
            this.above = above;
            this.below = below;
            this.left = left;
            this.right = right;
    }

    //also have accessor methods for my variables

}

0 个答案:

没有答案