I am doing the infamous Number Tile game program. In which you have a number tile shaped like a diamond. Using an array list you fill out the diamond with any random integer 1-9. You can then place your a numbertile from your hand on to the board if it meets the requirement. I am trying to see what causes my program to crash.
package diamond;
/** * * @author Snake */ import java.util.ArrayList ;
public class TileGame { private ArrayList board;
// Creates an empty board
public TileGame()
{
board= new ArrayList() ;
NumberTile FirstD= new NumberTile();
board.add(FirstD);
System.out.println(board);
}
// Accessor for the board
public ArrayList<NumberTile> getBoard()
{
// Do not modify this method
return board ;
}
// Creates and returns a hand of 5 random number tiles
public ArrayList<NumberTile> getHand()
{
ArrayList<NumberTile> hand = new ArrayList<NumberTile>() ;
for(int i=0; i<5; i++)
{
NumberTile random = new NumberTile();
hand.add(random);
}
return hand;
}
// If the current tile fits in the board (without rotating) then
// return the index i of a tile in the board so that the current tile
// fits before ti for i = 0..k-1, or return k if the current tile fits
// after the last tile. If the tile does not fit, return -1
public int getIndexForFit(NumberTile currentTile)
{
if(currentTile.getRight()==board.get(0).getLeft())
{
return 0;
}
if(currentTile.getLeft()==board.get(board.size()-1).getRight())
{
return board.size();
}
for(int i=0; i<board.size(); i++)
{
if(board.get(i).getLeft()==currentTile.getRight() &&
board.get(i-1).getRight()==currentTile.getLeft())
{
return i;
}
}
return -1 ;
}
// Call the method getIndexForFit to see whether a tile can be inserted
// into the board. In this method the tile can be rotated. If the tile
// can be inserted, return true. If the tile does not fit after
// rotating (at most 3 times), return false.
public boolean canInsertTile(NumberTile currentTile)
{
for(int i=0; i<=3; i++)
{
if(getIndexForFit(currentTile)!=-1)
{
return true;
}
else
currentTile.rotate();
}
return false ;
}
// Make a move. I.e. if a tile in the hand fits on the board
// then remove it from the hand and place it in the board. If no tile
// from the hand fits, then add another tile to the hand
public void makeMove(ArrayList<NumberTile> hand)
{
NumberTile drawHand = new NumberTile();
for(int i=0; i<hand.size(); i++)
{
if(canInsertTile(hand.get(i))==true)
{
int index = getIndexForFit(hand.get(i));
board.add(index,hand.get(i));
hand.remove(hand.get(i));
}
else if(canInsertTile(hand.get(i))==false && i==hand.size()-1)
{
hand.add(drawHand);
}
}
}
/**
* Get the board as a String
* @return the board as a multi-line String
*/
public String toString()
{
// Do not modify this method
return board.toString() ; // ArrayList as a String
}
} // end of TileGame class
Aucun commentaire:
Enregistrer un commentaire