// Scott DeRuiter 1/27/03
// FindTreasure.java
// Move through a 2-Dimensional array and find the treasure.
public class FindTreasure
{
private int row, col, treasurex, treasurey, turns;
private int [][] board;
private boolean treasurefound;
private char move;
public FindTreasure ( )
{
turns = 0;
move = ' ';
treasurefound = false;
board = new int [10][10];
for ( int i = 0; i < board.length; i++ )
for ( int j = 0; j < board[i].length; j++ )
board[i][j] = 0;
row = col = 0;
board[row][col] = 1;
do
{
treasurex = (int)(Math.random()*10);
treasurey = (int)(Math.random()*10);
} while ( row == treasurex && col == treasurey );
board[treasurex][treasurey] = 100;
}
public static void main ( String [] args )
{
FindTreasure game = new FindTreasure ( );
game.RunGame ( );
}
public void RunGame ( )
{
do
{
PrintMap ( );
PromptUser ( );
ChangeMap ( );
// treasurefound = true;
} while (!treasurefound);
PrintMap ( );
System.out.println ( "\n\nGood work, it only took " + turns + " turns to find the treasure!\n\n" );
}
public void PrintMap ( )
{
for ( int i = 0; i < board.length; i++ )
{
for ( int j = 0; j < board[i].length; j++ )
{
if ( board[i][j] == 0 )
System.out.print ( Format.center ( "-", 3 ) );
else if ( board[i][j] == 1 )
System.out.print ( Format.center ( "!", 3 ) );
else if ( board[i][j] == 100 && treasurefound )
System.out.print ( Format.center ( "$", 3 ) );
else if ( board[i][j] == -1 )
System.out.print ( Format.center ( "+", 3 ) );
}
System.out.println ( "\n" );
}
System.out.println ( "\nYou are at a distance of " +
Format.center(Math.sqrt(Math.pow(row-treasurex,2) + Math.pow(col-treasurey,2)),6,2) +
" units from the treasure!" );
}
public void PromptUser ( )
{
TextReader keyboard = new TextReader ( );
do
{
System.out.print ( "Enter 'w' for up, 's' for down, 'd' for right, or 'a' for left : " );
move = keyboard.readlnChar ( );
if ( move == 'w' && row == 0 )
move = ' ';
else if ( move == 's' && row == 9 )
move = ' ';
else if ( move == 'd' && col == 9 )
move = ' ';
else if ( move == 'a' && col == 0 )
move = ' ';
} while ( move != 'w' && move != 's' && move != 'd' && move != 'a' );
}
public void ChangeMap ( )
{
board[row][col] = -1;
if (move == 'w')
row--;
else if (move == 's')
row++;
else if (move == 'd')
col++;
else if (move == 'a')
col--;
if ( row == treasurex && col == treasurey )
treasurefound = true;
else
board[row][col] = 1;
turns++;
}
}
Back to Lesson 17 Examples
Back to Java Main Page