//  Scott DeRuiter          7/26/01
//  Match.java
//  Play the game of Match

public class Match   
{
	
	private int row, col, previousrow, previouscol;
	private int turns, count, input;
	private String [][] board;
	private boolean [][] mirror;
	private String [] word = { "FRED", "MIRROR", "JAVA", "SUMMER", "SWIMMING",
					"VACATION?", "DESK", "FRIDAY" };
	private boolean firstcard;

	public Match ( )   
	{
		row = col = previousrow = previouscol = turns = count = input = 0;
		firstcard = true;
		board = new String [4][4];
		mirror = new boolean [4][4];
		for ( int i = 0; i < board.length; i++ )
			for ( int j = 0; j < board [i].length; j++ )
				board [i][j] = "";
	}

	public static void main ( String [] args )   
	{
		Match game = new Match ( );

		game.FillBoard ( );
		game.RunGame ( );
	}

	public void RunGame ( )   
	{
		do  
		{
			PrintBoard ( );
			PromptUser ( );
			ChangeBoard ( );
		} while ( count < 8 );
		PrintBoard ( );
		System.out.println ( "\n\nGood work!  It took " + turns + " to finish the game.\n\n" );
	}

	public void PrintBoard ( )   
	{
		System.out.println ( "\n\n\n" );	
		for ( int i = 0; i < board.length; i++ )   
		{
			for ( int j = 0; j < board [i].length; j++ )      
			{
				if ( mirror [i][j] )
					System.out.print ( Format.center ( board [i][j], 14 ) );
				else
					System.out.print ( Format.center ( i * 4 + j + 1, 14 ) );
			}
			System.out.println ( "\n\n\n" );	
		}
		System.out.println ( "\nTurns: " + turns + "\n" );
		System.out.println ( "\n\n\n" );		
	}

	public void FillBoard ( )   
	{
		for ( int k = 1; k <= 2; k++ )  
		{
			for ( int m = 0; m <= 7; m++ )   
			{
				int rowindex = (int)( Math.random ( ) * 4 );
				int colindex = (int)( Math.random ( ) * 4 );
				if ( board [rowindex][colindex].equals ( "" ) )
					board [rowindex][colindex] = word [m];
				else
					m--;
			}
		}
	}

	public void PromptUser ( )  
	{
		TextReader keyboard = new TextReader ( );
		do  
		{
			System.out.print ( "\n\nEnter the card number you wish to flip -> " );
			input = keyboard.readlnInt ( );
			row = (input - 1) / 4;
			col = (input - 1) % 4;
		} while ( input < 1 || input > 16 || mirror [row][col] );
	}

	public void ChangeBoard ( )   
	{
		TextReader console = new TextReader ( );
		turns++;
		if ( firstcard )   
		{
			mirror [row][col] = true;
			previousrow = row;
			previouscol = col;
		}
		else if ( board[row][col].equals ( board [previousrow][previouscol] ) )
		{
			mirror [row][col] = true;
			count++;
			System.out.println ( "\n\nYOU FOUND A MATCH!!\n" );
		}
		else   
		{
			mirror [row][col] = true;
			PrintBoard ( );
			mirror [row][col] = false;
			mirror [previousrow][previouscol] = false;
			System.out.print ( "\n\nSorry, no match this time. Press any key to continue:  " );
			console.readAnyChar ( );
		}
		firstcard = !firstcard;
	}
}

Back to Lesson 17 Examples

Back to Java Main Page