/** * This class implements the board for the game MineSweeper. * * @author John Paxton * @version 1.1 (January 21, 2004) */ import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; public class GameBoard { GameBoard () { board = new Tile [SIZE + 2][SIZE + 2]; console = new BufferedReader (new InputStreamReader (System.in)); } public void initialize() { mineHit = false; successfulGuesses = 0; for (int row = 0; row < SIZE + 2; row++) { for (int col = 0; col < SIZE + 2; col++) { board[row][col] = new Tile(); } } placeMines(); for (int row = 1; row <= SIZE; row++) { for (int col = 1; col <= SIZE; col++) { board[row][col].setSurroundingMines( calculateMines (row, col) ); } } } private void placeMines() { int placed = 0; int row; int col; while (placed < MINES) { row = (int) (Math.random() * SIZE) + 1; col = (int) (Math.random() * SIZE) + 1; if (!board[row][col].getMine()) { board[row][col].setMine(); placed++; } } } private int calculateMines (int row, int col) { int answer = 0; for (int r = row - 1; r <= row + 1; r++) { for (int c = col -1; c <= col + 1; c++) { if ( board[r][c].getMine() ) { answer++; } } } return answer; } public void print () { System.out.println(); System.out.print(" "); for (int row = 1; row <= SIZE; row++) { System.out.print(" " + row + " "); } System.out.println(); for (int row = 1; row <= SIZE; row++) { printLine(); System.out.print(row + " "); for (int col = 1; col <= SIZE; col++) { System.out.print("| " + board[row][col].getPrintString() + " "); } System.out.println("|"); } printLine(); System.out.println(); if (gameWon()) { System.out.println("Congratulations, you won!"); } else if (gameLost()) { System.out.println("Sorry, you lost!"); } } private void printLine() { System.out.print(" "); for (int i = 0; i < SIZE; i++) { System.out.print("+---"); } System.out.println("+"); } public void makeGuess() { int row = getGuess("row"); int col = getGuess("column"); if (board[row][col].getMine()) { mineHit = true; } else if (!board[row][col].getGuessed()) { successfulGuesses++; } board[row][col].setGuessed(); } private int getGuess(String message) { try { int result; System.out.print("Please enter the " + message + ": "); result = Integer.parseInt(console.readLine()); while ((result < 1) || (result > SIZE)) { System.out.print("Invalid, please reenter: "); result = Integer.parseInt(console.readLine()); } return result; } catch (IOException e) { System.out.println("Error trying to read input"); return 1; } } public boolean gameOver () { return (gameLost() || gameWon()); } private boolean gameLost () { return mineHit; } private boolean gameWon () { return ( SIZE * SIZE - MINES == successfulGuesses); } private static final int SIZE = 3; private static final int MINES = 2; private Tile [][] board; private boolean mineHit; private int successfulGuesses; private BufferedReader console; }