I'm currently working on a version of Conway's Game of Life with Netbeans IDE and I wanted to store cells in a matrix. For the operation of going to the Next generation of cells, I would return a new matrix of cells which is calculated from the inputting matrix.
The Code is the following:
public static Cell[][] nextGen(Cell[][] CellList)
{
Cell[][] Copy = CellList.clone();
for (int i = 0; i<Copy.length; i++)
{
for(int n = 0; n<Copy[i].length; n++)
{
if (Copy[i][n].isAlive())
{
if (Cell.count(Copy, i, n) <= 1 || Cell.count(Copy, i, n) >= 4 )
{
CellList[i][n].kill();
}
}else
{
if (Cell.count(Copy, i, n) == 3)
{
CellList[i][n].born();
}
}
}
}
return CellList;
}
The Class is called "Cell"
it has a private boolean property "alive" which can be set to false with the public method kill() or true with the public method born(). Everything except the method for counting alive cells surrounding a specific cell and the method for calculating the new generation is nonstatic.
The Problem why it isn't working is that if I make any changes to the input matrix "CellList", the same thing happens in the copy of this matrix.
How can I let the copy have the same Values but only make changes in the input matrix?
Thanks for the helping!
What you are doing is shallow copy, what you need is deep copy. Try this
public class Cell {
boolean alive = false;
protected Cell clone() {
return new Cell(this);
}
public Cell() {
}
public Cell(Cell cell) {
this.alive = cell.alive;
}
boolean isAlive() {
return alive;
}
void kill() {
alive = false;
}
void born() {
alive = true;
}
static int count(Cell[][] cell, int j, int k) {
return 1;
}
public static void main(String[] args) {
Cell[][] CellList = new Cell[2][3];
CellList[0][1] = new Cell();
nextGen(CellList);
}
public static Cell[][] nextGen(Cell[][] CellList) {
Cell[][] Copy = deepArrayCopy(CellList);
for (int i = 0; i < Copy.length; i++) {
for (int n = 0; n < Copy[i].length; n++) {
if (Copy[i][n].isAlive()) {
if (Cell.count(Copy, i, n) <= 1 || Cell.count(Copy, i, n) >= 4) {
CellList[i][n].kill();
}
} else {
if (Cell.count(Copy, i, n) == 3) {
CellList[i][n].born();
}
}
}
}
return CellList;
}
public static Cell[][] deepArrayCopy(Cell[][] celllist) {
Cell[][] copy = new Cell[celllist.length][celllist[0].length];
for (int i = 0; i < celllist.length; i++) {
for (int k = 0; k < celllist[i].length; k++) {
if (celllist[i][k] != null)
copy[i][k] = celllist[i][k].clone();
}
}
return copy;
}
}
Related
I am working on a program that will solve find a path in a maze. The maze is represented by 0's, 1's and an E to represent the Exit. The maze is represented by a 20x30 (0's represent the path, 1's represent walls). I am using a stack to keep track of a previous usable location.
I think I have most of the code figured out, but when I run it and enter the starting position, the final maze doesn't print out.
My code is as follows:
import java.util.*;
import java.io.*;
public class MazeGenerator {
//main
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int userRow, userCol;
MazeGenerator maze = new MazeGenerator();
maze.fillArray();
maze.print();
System.out.println();
//asking for user starting position
System.out.print("What row would you like to start in?: " );
userRow = sc.nextInt();
while(userRow > 29 || userRow < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 -
29 INCLUSIVE: " );
userRow = sc.nextInt();
}
System.out.println();
System.out.print("What column would you like to start in? ");
userCol = sc.nextInt();
while(userCol > 19 || userCol < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 -
19 INCLUSIVE: " );
userCol= sc.nextInt();
}
System.out.println("\n\nFind a path using a stack: ");
//maze.userStart(userRow,userCol);
maze.setUserRow(userRow);
maze.setUserColumn(userCol);
maze.solveStack();
//solveStack(maze);
}
//methods for creating maze
public static final int ROW = 30;
public static final int COLUMN = 20;
public int userRow = 0;
public int userColumn = 0;
private static String[][] maze = new String[ROW][COLUMN];
public void fillArray() throws IOException {
File file = new File("maze.txt");
FileReader reader = new FileReader(file);
BufferedReader buff = new BufferedReader(reader);
for(int counter1 = 0; counter1 < ROW; counter1++) {
String l = buff.readLine();
for(int counter2 = 0; counter2 < COLUMN; counter2++) {
maze[counter1][counter2] = String.valueOf(l.charAt(counter2));
}
}
buff.close();
}
public void print() throws IOException {
System.out.printf("%-4s", ""); //spaces column
for (int counter = 0; counter < COLUMN; counter++){
System.out.printf("%-4d",counter); //print the column number
}
System.out.println();
for(int counter1 = 0; counter1 < maze.length; counter1++) { //loop for
printing rows
System.out.printf("%-4d",counter1); //print row number
for(int counter2 = 0; counter2 < maze[counter1].length; counter2++)
{ //loop for printing columns
System.out.printf("%-4s", maze[counter1][counter2]); //printing
values of maze
}
System.out.println(); // new line
}
}
public int getWidth(){
return maze[0].length;
}
public int getHeight(){
return maze.length;
}
public void setUserRow (int userRow) {
this.userRow = userRow;
}
public void setUserColumn (int userColumn) {
this.userColumn = userColumn;
}
public int getUserRow() {
return userRow;
}
public int getUserColumn() {
return userColumn;
}
public String mark(int row, int col, String value) {
assert(inMaze(row,col));
String temp = maze[row][col];
maze[row][col] = value;
return temp;
}
public String mark (MazePosition pos, String value) {
return mark(pos.row(), pos.col(), value);
}
public boolean isMarked(int row, int col) {
assert(inMaze(row,col));
return (maze[row][col].equals("+"));
}
public boolean isMarked(MazePosition pos) {
return isMarked(pos.row(), pos.col());
}
public boolean Clear(int row, int col) {
assert(inMaze(row,col));
return (maze[row+1][col+1] != "1" && maze[row+1][col+1] != "+");
}
public boolean Clear(MazePosition pos) {
return Clear(pos.row(), pos.col());
}
//true if cell is within maze
public boolean inMaze(int row, int col) {
if (row >= 0 && col >= 0 && row < getWidth() && col < getHeight() ) {
return true;
}
return false;
}
//true if cell is within maze
public boolean inMaze(MazePosition pos) {
return inMaze(pos.row(), pos.col());
}
public boolean Done( int row, int col) {
return (maze[row][col].equals("E"));
}
public boolean Done(MazePosition pos) {
return Done(pos.row(), pos.col());
}
public String[][] clone() {
String[][] copy = new String[ROW][COLUMN];
for (int counter1 = 0; counter1 < ROW; counter1++) {
for (int counter2 = 0; counter2 < COLUMN; counter2++) {
copy[counter1][counter2] = maze[counter1][counter2];
}
}
return copy;
}
public void restore(String[][] savedMaze) {
for (int i=0; i< ROW; i++)
for (int j=0; j<COLUMN; j++)
maze[i][j] = savedMaze[i][j];
}
public MazeGenerator clone(MazeGenerator m) {
MazeGenerator maze = new MazeGenerator();
maze = m;
return maze;
}
//**************************************************
//this solution uses a stack to keep track of possible
//states/positions to explore; it marks the maze to remember the
//positions that it's already explored.
public void solveStack() throws IOException {
//save the maze
//MazeGenerator savedMaze = new MazeGenerator();
//savedMaze.clone(m);
String[][] savedMaze = clone();
//declare the locations stack
Stack<MazePosition> candidates = new Stack<MazePosition>();
//insert the start
candidates.push(new MazePosition(userRow,userColumn));
MazePosition current, next;
while (!candidates.empty()) {
//get current position
current = candidates.pop();
if (Done(current)) {
break;
}
//mark the current position
mark(current, "+");
//put its neighbors in the queue
next = current.north();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.east();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.west();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.south();
if (inMaze(next) && Clear(next)) candidates.push(next);
}
if (!candidates.empty()) {
System.out.println("You got it!");
}
else System.out.println("You're stuck in the maze!");
//savedMaze.print();
print();
restore(savedMaze);
}
class MazePosition {
public int row;
public int col;
public MazePosition(int row, int col) {
this.row = row;
this.col = col;
}
public int row() { return row; }
public int col() { return col; }
public void print() {
System.out.println("(" + row + "," + col + ")");
}
//positions
public MazePosition north() {
return new MazePosition(row-1, col);
}
public MazePosition south() {
return new MazePosition(row+1, col);
}
public MazePosition east() {
return new MazePosition(row, col+1);
}
public MazePosition west() {
return new MazePosition(row, col-1);
}
};
}
Without the benefit of a maze.txt, I created one based on your description. Here's what I found...
Short answer:
Your program hits an infinite loop searching for the exit, so it never reaches the code to print it out.
Long answer:
I see 3 problems on 2 lines of code:
1) A simple typo:
if (row >= 0 && col >= 0 && row < getWidth() && col < getHeight() ) {
getHeight() and getWidth() should be swapped:
if (row >= 0 && col >= 0 && row < getHeight() && col < getWidth() ) {
2) In one spot, you're using 1-based indices, when Java uses 0-based indices:
In this line here:
return (maze[row+1][col+1] != "1" && maze[row+1][col+1] != "+");
Array indices in java start at 0. Your row and col variables also start at 0. But you're adding one to them thereby converting them into 1-based indices. So, you'd want:
return (maze[row][col] != "1" && maze[row][col] != "+");
3) You're using != like !equals(), but in Java, == is not the same as .equals()
In the above line of code, you're comparing two Strings with the != operator. But that doesn't work like the String.equals() method, so your Clear() method always returns true.
This is the crux of your stated problem. The search routine, finding every cell clear, works its way into a corner, and then searches the same two adjacent cells forever.
So, what you really want is:
return (!maze[row][col].equals("1") && !maze[row][col].equals("+"));
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am working on a program that will solve find a path in a maze. The maze is represented by 0's, 1's and an E to represent the Exit. The maze is represented by a 20x30 (0's represent the path, 1's represent walls). I am using a stack to keep track of a previous usable location.
I think I have most of the code figured out, but whenever i try to run it, i get an ArrayIndexOutOfBoundsException. I think the main problem is that there are no defined walls around the border. Maybe surround the maze with a border of 1's?
My code is as follows:
import java.util.*;
import java.io.*;
public class MazeGenerator {
//main
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int userRow, userCol;
MazeGenerator maze = new MazeGenerator();
maze.fillArray();
maze.print();
System.out.println();
//asking for user starting position
System.out.print("What row would you like to start in?: " );
userRow = sc.nextInt();
while(userRow > 29 || userRow < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 - 29 INCLUSIVE: " );
userRow = sc.nextInt();
}
System.out.println();
System.out.print("What column would you like to start in? ");
userCol = sc.nextInt();
while(userCol > 19 || userCol < 0) {
System.out.print("INVALID INPUT! PLEASE ENTER VALUES BETWEEN 0 - 19 INCLUSIVE: " );
userCol= sc.nextInt();
}
System.out.println("\n\nFind a path using a stack: ");
//maze.userStart(userRow,userCol);
maze.setUserRow(userRow);
maze.setUserColumn(userCol);
maze.solveStack();
}
//methods for creating maze
public static final int ROW = 30;
public static final int COLUMN = 20;
public int userRow = 0;
public int userColumn = 0;
private static String[][] maze = new String[ROW][COLUMN];
public void fillArray() throws IOException {
File file = new File("maze.txt");
FileReader reader = new FileReader(file);
BufferedReader buff = new BufferedReader(reader);
for(int counter1 = 0; counter1 < ROW; counter1++) {
String l = buff.readLine();
for(int counter2 = 0; counter2 < COLUMN; counter2++) {
maze[counter1][counter2] = String.valueOf(l.charAt(counter2));
}
}
buff.close();
}
public void print() throws IOException {
System.out.printf("%-4s", ""); //spaces column
for (int counter = 0; counter < COLUMN; counter++){
System.out.printf("%-4d",counter); //print the column number
}
System.out.println();
for(int counter1 = 0; counter1 < maze.length; counter1++) { //loop for printing rows
System.out.printf("%-4d",counter1); //print row number
for(int counter2 = 0; counter2 < maze[counter1].length; counter2++) { //loop for printing columns
System.out.printf("%-4s", maze[counter1][counter2]); //printing values of maze
}
System.out.println(); // new line
}
}
public int size() {
return maze.length;
}
public void setUserRow (int userRow) {
this.userRow = userRow;
}
public void setUserColumn (int userColumn) {
this.userColumn = userColumn;
}
public int getUserRow() {
return userRow;
}
public int getUserColumn() {
return userColumn;
}
public String mark(int row, int col, String value) {
assert(inMaze(row,col));
String temp = maze[row][col];
maze[row][col] = value;
return temp;
}
public String mark (MazePosition pos, String value) {
return mark(pos.row(), pos.col(), value);
}
public boolean isMarked(int row, int col) {
assert(inMaze(row,col));
return (maze[row][col].equals("+"));
}
public boolean isMarked(MazePosition pos) {
return isMarked(pos.row(), pos.col());
}
public boolean Clear(int row, int col) {
assert(inMaze(row,col));
return (maze[row][col] != "1" && maze[row][col] != "+");
}
public boolean Clear(MazePosition pos) {
return Clear(pos.row(), pos.col());
}
//true if cell is within maze
public boolean inMaze(int row, int col) {
if (row >= 0 && col<size() && row>= 0 && col<size()) {
return true;
}
else if (row < 0 && col<size() && row >= 0 && col<size()) {
return false;
}
else return false;
}
//true if cell is within maze
public boolean inMaze(MazePosition pos) {
return inMaze(pos.row(), pos.col());
}
public boolean Done( int row, int col) {
return (maze[row][col].equals("E"));
}
public boolean Done(MazePosition pos) {
return Done(pos.row(), pos.col());
}
public String[][] clone() {
String[][] copy = new String[ROW][COLUMN];
for (int counter1 = 0; counter1 < ROW; counter1++) {
for (int counter2 = 0; counter2 < COLUMN; counter2++) {
copy[counter1][counter2] = maze[counter1][counter2];
}
}
return copy;
}
public void solveStack() throws IOException {
//save the maze
String[][] savedMaze = clone();
//declare the locations stack
Stack<MazePosition> candidates = new Stack<MazePosition>();
//insert the start
candidates.push(new MazePosition(userRow,userColumn));
MazePosition current, next;
while (!candidates.empty()) {
//get current position
current = candidates.pop();
if (Done(current)) {
break;
}
//mark the current position
mark(current, "S");
//put its neighbors in the queue
next = current.north();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.east();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.west();
if (inMaze(next) && Clear(next)) candidates.push(next);
next = current.south();
if (inMaze(next) && Clear(next)) candidates.push(next);
}
if (!candidates.empty())
System.out.println("You got it!");
else System.out.println("You're stuck in the maze!");
print();
}
class MazePosition {
public int row;
public int col;
public MazePosition(int row, int col) {
this.row = row;
this.col = col;
}
public int row() { return row; }
public int col() { return col; }
public void print() {
System.out.println("(" + row + "," + col + ")");
}
//positions
public MazePosition north() {
return new MazePosition(row-1, col);
}
public MazePosition south() {
return new MazePosition(row+1, col);
}
public MazePosition east() {
return new MazePosition(row, col+1);
}
public MazePosition west() {
return new MazePosition(row, col-1);
}
};
}
The error is as follows:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at MazeGenerator.Clear(MazeGenerator.java:137)
at MazeGenerator.Clear(MazeGenerator.java:141)
at MazeGenerator.solveStack(MazeGenerator.java:217)
at MazeGenerator.main(MazeGenerator.java:40)
i think you're doing a mistake in inMaze(int row, int col) method. I'll try to correct it for you
public boolean inMaze(int row, int col) {
if (row >= 0 && col >= 0 && row < getWidth() && col < getHeight() ) {
return true;
}
return false;
}
therefore you have to change the size() method into getWidth() and getHeight()
public int getWidth(){
return maze[0].length;
}
public int getHeight(){
return maze.length;
}
I am working on a Four in a row game.
But I have run into a problem with it. I have been able to make the game work. But I would like to know if I can move my public void fillBoard() and public void presentBoard() into another class. This is because I would like to make the code more organised.
package com.company;
public class Main {
public static void main(String[] args)
{
GameMechanics game = new GameMechanics();
game.play();
}
}
package com.company;
import java.util.Scanner;
public class GameMechanics
{
/*
This is my local variables
*/
public Scanner scanner = new Scanner(System.in);
public char token;
public int column;
public int player = 2;
public int turn = 2;
public int count = 0;
public boolean gameRunning = true;
public void play()
{
this.createBoard();
//While gameRunning is true, the methods inside the { } will run, and that's the 4InARow game
while (gameRunning)
{
this.presentBoard();
this.changeTurn();
this.dropToken();
this.gameWon();
}
presentBoard();
}
public void gameWon()
{
this.winConHorizontal();
this.winConVertical();
}
private char[][] board = new char[6][7];
//Creating my board and assign "space" to all the fields in the array.
public void createBoard() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
board[i][j] = ' ';
}
}
}
//Presents the board, it prints the board with |"space"| so it looks more like a gameboard.
public void presentBoard() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
if (j == 0) {
System.out.print("|");
}
System.out.print(board[i][j] + "|");
}
System.out.println();
}
}
public void changeTurn() {
if (this.turn == this.player) {
this.turn = 1;
this.token = 'X';
} else {
this.turn++;
this.token = 'O';
}
}
public void dropToken() {
System.out.println("player " + turn + ": press 1-7 to drop the token");
column = scanner.nextInt() - 1;
//If pressed any intValue outside the board, it will tell you to try again.
if (column >= 7 || column <= -1)
{
System.out.println("place the token inside the bord");
changeTurn();
} else {
//Drops the token and replace it with playerChar.
for (int i = 5; i > -1; i--) {
if (board[i][column] == ' ')
{
board[i][column] = token;
break;
}
}
}
}
public boolean winConHorizontal() {
while (gameRunning) {
for (int i = 0; 6 > i; i ++) {
for (int j = 0; 7 > j; j ++) {
if (board[i][j] == this.token) {
count ++;
} else {
count = 0;
}
if (count >= 4) {
System.out.println("player " + (turn) + " Wins!!!!");
gameRunning = false;
}
}
}
break;
}
return gameRunning;
}
public boolean winConVertical() {
while (gameRunning) {
for (int i = 0; 7 > i; i ++) {
for (int j = 0; 6 > j; j ++) {
if (board[j][i] == this.token) {
count ++;
} else {
count = 0;
}
if (count >= 4) {
System.out.println("player " + (turn) + " Wins!!!!");
gameRunning = false;
}
}
}
break;
}
return gameRunning;
}
}
An easy way to do this is as follows:
extract your char[][] board into its own class, e.g. Board
Said class could expose the function char getField(int index)
Extract the ,,presenting" part of your code into another class, e.g. BoardPresenter. Said class should have a function presentBoard(Board board) which internally uses getField(int index) of the Board class.
By doing this you abstract away your internal board storage mechanism while also reducing the number of responsibilities the GameMechanics class has (See https://en.wikipedia.org/wiki/Single_responsibility_principle)
yes, you can make another class and extend it with the current class GameMechanics and inside another class you can define the functions.
Note : This is a very simple approachable way.
Otherwise better if you manage your classes and interfaces similar to mvc model, for which you can search youtube for mvc structure java.
This is my Queue class. I have implemented it using arrays.
public class QueueUsingArray {
private int data[];
private int firstElementIndex;
private int nextElementIndex;
private int size;
public QueueUsingArray() {
data = new int[10];
firstElementIndex = -1;
nextElementIndex = 0;
size = 0;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size() == 0;
}
private void checkEmpty() throws QueueEmptyException {
if (size == 0) {
QueueEmptyException e = new QueueEmptyException();
throw e;
}
}
public int front() throws QueueEmptyException {
checkEmpty();
return data[firstElementIndex];
}
public int dequeue() throws QueueEmptyException {
checkEmpty();
int output = data[firstElementIndex];
size--;
data[firstElementIndex] = 0;
firstElementIndex = (firstElementIndex + 1) % data.length;
if (size == 0) {
firstElementIndex = -1;
nextElementIndex = 0;
size = 0;
}
return output;
}
public void enqueue(int element) {
if (size == data.length) {
int[] temp = data;
data = new int[data.length * 2];
int k = 0;
for (int i = firstElementIndex; i < temp.length; i++) {
data[k] = temp[i];
k++;
}
for (int i = 0; i < firstElementIndex; i++) {
data[k] = temp[i];
k++;
}
firstElementIndex = 0;
nextElementIndex = temp.length;
}
if (size == 0) {
firstElementIndex = 0;
}
data[nextElementIndex] = element;
size++;
nextElementIndex = (nextElementIndex + 1) % data.length;
}
}
Here is my QueueUse class.
public class QueueUse {
public static void main(String[] args) throws QueueEmptyException {
QueueUsingArray q=new QueueUsingArray();
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
q.enqueue(60);
q.enqueue(70);
q.enqueue(80);
q.enqueue(90);
q.enqueue(100);
q.enqueue(110);
q.enqueue(120);
q.enqueue(130);
q.enqueue(140);
q.enqueue(150);
q.enqueue(160);
q.enqueue(170);
q.enqueue(180);
q.enqueue(190);
q.enqueue(200);
q.enqueue(210);
q.enqueue(220);
q.enqueue(230);
q.enqueue(240);
q.enqueue(250);
q.enqueue(260);
q.enqueue(270);
q.enqueue(280);
q.enqueue(290);
q.enqueue(300);
System.out.println("All elements");
for(int i=0;i<q.size();i++){
try {
System.out.println(q.dequeue());
} catch (QueueEmptyException e) {
System.out.println("Sorry");
}
}
}
}
My output is not complete. Output is not showing all the elements in my queue. What is the error. Output is only showing until 140 and not beyond that.
Your print method does not work because you decrement the size every time you invoke your dequeue() method in the for loop. If you are going to use a for loop you should be using a fixed size. Basically in this statement ( i < q.size() ) as i grows size decreases. If i = 0 and size = 4 the first loop i would be 1 and size would be 3. Your never going to get to the 0th or 1st element in your queue because by the next loop your already at i = 2 and size = 3.
first you should add a getter for the queue items
public int getElementAt(int index){
return data[index];
}
then you can call the method in the for loop for every index in data
int length = q.size();
for(int i = 0; i < length; i++){
System.out.println(q.getElementAt(i));
}
If it is not mandatory to do an array implementation, I would suggest using the Vector class because it has a better API for a queue. I would also suggest slowly tracing your program every time you have issues and to start with smaller test data sets to make tracing a easier.
public class Queue {
private Vector<String> data ;
Queue(){
data = new Vector();
}
public void enqueue(String item){
data.add(item);
}
public void dequeue(){
data.remove(0);
}
public void printQueueItems(){
int length = data.size();
for(int i = 0; i < length; i++){
System.out.println(data.get(i));
}
}
public static void main(String[] args) {
Queue myQ = new Queue();
myQ.enqueue("hello");
myQ.enqueue("world");
myQ.enqueue("!");
myQ.printQueueItems();
}
}
I'm new to Java and getting an NullPointerException error with this code at this line:
spielfeld[i][j] = new DominionTile(world,i,j); // last function
Here is the whole program code:
public class MapProvider implements ....... {
private DominionTile[][] spielfeld;
int row;
int col;
public MapProvider(int zahl1, int zahl2) {
DominionTile[][] spielfeld = new DominionTile[zahl1][zahl2];
col = zahl1;
row = zahl2;
}
#Override
public MapTile[] getColumn(int spalte) { // DONE
if ((spalte < 0) && (spalte > col) ) {
return null;
}
else {
return spielfeld[spalte];
}
}
#Override
public int getColumns() { // DONE
return col;
}
#Override
public int getRows() { // DONE
return row;
}
#Override
public boolean isValid(int spalte, int zeile) { // DONE
if ((spalte < 0) && (zeile < 0)) {
return false;
}
else if ((spalte > col) && (zeile > row)) {
return false;
}
else {
return true;
}
}
#Override
public DominionTile getTile(int col, int row) { // DONE
return spielfeld[col][row];
}
#Override
public void setupMapTiles(MapWorld world) { // NICHT FERTIG
final Map karte = world.getMap();
int zeilen = karte.getRows();
int spalten = karte.getColumns();
for (int i = 1; i <= spalten; i++) { // I-TE SPALTE
for (int j = 1; j <= zeilen; j++) { // J-TE ZEILE
spielfeld[i][j] = new DominionTile(world,i,j);
//DominionTile neu = new DominionTile(world, i, j);
//spielfeld[i][j] = (DominionTile)neu;
}
}
}
}
The last function should put a DominionTile in each place of the array. What am I doing wrong?
You have this in your constructor. This declares and assigns to a local variable, not the spielfeld field, and hence the field is left with a null value.
DominionTile[][] spielfeld = new DominionTile[zahl1][zahl2];
You probably want:
public MapProvider(int zahl1, int zahl2) {
spielfeld = new DominionTile[zahl1][zahl2];
col = zahl1;
row = zahl2;
}
i.e. without the type declaration, which will assign to the object's field.
As a starting point, you might want print out the values of zeilen and spalten. I am guessing this is caused by accessing spielfeld[i][j] where spielfeld[i] does not exist in the first place.