2012-04-13 24 views
0

Ich mache ein Labyrinth-Spiel mit aufgezählten Typen, um die Werte von Wänden, Freiflächen (etc) zu halten, und ich bin mir nicht sicher, warum dieser Code nicht funktioniert, ich versuche, eine neue Platine zu erstellen alles zu öffnen, dann durchzugehen und Werte auf die Punkte im Array zufällig zu setzen.Enum Typ 2Darray Labyrinth

maze = new Cell[row][col]; 
for (int r = 0; r < maze.length; r++) { 
    for (int c = 0; c < maze.length; c++) 
     maze[r][c].setType(CellType.OPEN); 
    } 

Random randomMaze = new Random(); 
for (int ran = 0; ran <= numWalls ; ran++){ 
    maze[randomMaze.nextInt(maze.length)][randomMaze.nextInt(maze.length)].setType(CellType.WALL); 

} 

Antwort

0

dies wird tun, was Sie gesagt haben. nicht sicher, dass Sie die Art von Labyrinth bekommen, die Sie wollen:

import java.util.Random; 
class Maze { 
    enum CellType { 
     open,wall; 
    } 
    Maze(int n) { 
     this.n=n; 
     maze=new CellType[n][n]; 
     init(); 
    } 
    private void init() { 
     for(int i=0;i<n;i++) 
      for(int j=0;j<n;j++) 
       maze[i][j]=CellType.open; 
    } 
    void randomize(int walls) { 
     init(); 
     Random random=new Random(); 
     for(int i=0;i<=walls;i++) 
      maze[random.nextInt(n)][random.nextInt(n)]=CellType.wall; 
    } 
    public String toString() { 
     StringBuffer sb=new StringBuffer(); 
     for(int i=0;i<n;i++) { 
      for(int j=0;j<n;j++) 
       switch(maze[i][j]) { 
        case open: 
         sb.append(' '); 
         break; 
        case wall: 
         sb.append('|'); 
         break; 
       } 
      sb.append('\n'); 
     } 
     return sb.toString(); 
    } 
    final int n; 
    CellType[][] maze; 
} 
public class Main { 
    public static void main(String[] args) { 
     Maze maze=new Maze(5); 
     System.out.println(maze); 
     maze.randomize(4); 
     System.out.println(maze); 
    } 
} 
0

Ich denke, Ihre innere Schleife sollte so etwas wie

for (int c = 0; c < maze[r].length; c++) 

... mit dem [r] sein.

Ich habe es nicht versucht, obwohl.

0

Ich denke, dass Ihr Labyrinth ein guter Kandidat für eine Klasse wäre. So etwas sollte funktionieren:

import java.util.Random; 

public class Maze { 
    private int[][] mMaze; 
    private int mRows; 
    private int mCols; 

    //enums here: 
    public static int CELL_TYPE_OPEN = 0; 
    public static int CELL_TYPE_WALL = 1; 

    public Maze(int rows, int cols){ 
     mRows = rows; 
     mCols = cols; 
     mMaze = new int[mRows][mCols]; 
     for (int r = 0; r < mRows; r++) { 
      for (int c = 0; c < mCols; c++) { 
       mMaze[r][c] = Maze.CELL_TYPE_OPEN; 
      } 
     } 
    } 

    public void RandomizeMaze(int numWalls){ 
     Random randomMaze = new Random(); 
     for (int ran = 0; ran <= numWalls ; ran++){ 
      mMaze[randomMaze.nextInt(mRows)][randomMaze.nextInt(mCols)]=(Maze.CELL_TYPE_WALL); 
     } 
    } 

}