我正在制作一个Chutes Ladder程序,需要另一种方法来确定Cell是否是我正在使用的3个空格旁边的空白区域。如果单元格有3个空格,还有其他方法可以确定Cell是否为空。
Cell.java:
public class Cell {
String text;
int number;
public Cell() {}
public Cell( String r ) {
text = r;
}
public Cell( int m, String r ) {
text = r;
number = m;
}
public String getText() {
return text;
}
public void setText( String x ) {
text = x;
}
public int getNumber() {
return number;
}
public void setText( int x ) {
number = x;
}
public boolean isLadder() {
return (text.equals( "L" ));
}
public boolean isChute() {
return (text.equals( "C" ));
}
public boolean isEmpty() {
return text.equals( " " );
}
public String toString() {
String s = "";
if ( isChute() )
s = s + text + Math.abs( number );
else if ( isLadder() )
s = s + text + number;
else if ( isEmpty() )
s = s + " ";
return s;
}
}
ChutesAndLadders.java
public class ChutesAndLadders {
Cell[] board;
Random ran = new Random();
public ChutesAndLadders() {}
public ChutesAndLadders( int numChutes, int numLadders ) {
board = new Cell[100];
for ( int i = 0; i < board.length; i++ ) {
board[i] = new Cell( " " );
}
chutes( numChutes );
ladders( numLadders );
}
public void setBoard( Cell[] board ) {
this.board = board;
}
public Cell[] getBoard() {
return board;
}
public void makeChutes( int x ) {
for ( int i = 0; i < x; i++ ) {
int temp = ran.nextInt( board.length );
if ( board[temp].isEmpty() )
board[temp] = new Cell( -10, "C" );
else
i--;
}
}
public void makeLadders( int y ) {
for ( int i = 0; i < y; i++ ) {
int temp = ran.nextInt( board.length );
if ( temp < 10 )
temp = ran.nextInt( board.length );
if ( board[temp].isEmpty() )
board[temp] = new Cell( 10, "L" );
else
i--;
}
}
public void chutes( int x ) {
for ( int i = 0; i < x; i++ ) {
int temp = ran.nextInt( board.length );
if ( board[temp].isEmpty() )
board[temp] = new Cell( -10, "C" );
else
i--;
}
}
public void ladders( int y ) {
for ( int i = 0; i < y; i++ ) {
int temp = ran.nextInt( board.length );
if ( temp < 10 )
temp = ran.nextInt( board.length );
if ( board[temp].isEmpty() )
board[temp] = new Cell( 10, "L" );
else
i--;
}
}
public int addToMove( String a ) {
if ( a.equals( "C10" ) ) {
int n = Integer.parseInt( a.substring( 1 ) );
return n;
}
if ( a.equals( "L10" ) ) {
int n = Integer.parseInt( a.substring( 1 ) );
return n * -1;
}
else
return 0;
}
public void printBoard() {
int counter = 0;
for ( int i = 0; i < board.length; i++ ) {
counter++;
System.out.print( "|" + board[i] );
if ( counter == 10 ) {
System.out.print( "|" + "\n" );
counter = 0;
}
}
}
}
test.java:
public class test {
public static void main( String[] args ) {
ChutesAndLadders cl = new ChutesAndLadders( 10, 10 );
cl.makeChutes( 5 );
cl.makeLadders( 5 );
int chutes = 0, ladders = 0;
for ( Cell cell : cl.getBoard() ) {
if ( cell.isLadder() )
ladders++;
else if ( cell.isChute() )
chutes++;
}
System.out.println( "Board has " + chutes + " chutes and " + ladders + " ladders" );
cl.printBoard();
}
}
答案 0 :(得分:1)
public boolean isEmpty() {
return !(isLadder() && isChute());
}