/** * Class to implement the board for SuDoKu * @author gtowell * Created: Oct 2020 * Modified: Oct 2021 */ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class GameBoard { Spot[][] board; // the board is a 2d array of instance of the class spot /** * Constructor * @param initFile, the file to be read with the starting board * @throws FileNotFoundException * @throws IOException */ public GameBoard(String initFile) throws FileNotFoundException, IOException, ArrayIndexOutOfBoundsException { board = new Spot[9][9]; BufferedReader br = new BufferedReader(new FileReader(initFile)); for (int i = 0; i < 9; i++) { String line = br.readLine(); String[] sline = line.split(","); for (int j = 0; j < 9; j++) { int jj = Integer.parseInt(sline[j]); board[i][j] = new Spot(jj); } } br.close(); updateLegal(); } // Make a new instance of GameBoard that is a copy of the old one. public GameBoard(GameBoard ogb) { board = new Spot[9][9]; for (int i=0; i<9; i++) { for (int j=0; j<9; j++) { board[i][j]=new Spot(ogb.board[i][j]); } } updateLegal(); } /** * Updates the set of legal moves for every unoccupied spot on the board. The is really ugly because it has to do the * sudoku rules */ public void updateLegal() { for (int i=0; i<9; i++) { for (int j=0; j<9; j++) { board[i][j].clearLegal(); if (board[i][j].value==0) { for (int ii=0; ii<9;ii++) { if (board[ii][j].value > 0) board[i][j].legalMoves[board[ii][j].value-1]=false; } for (int jj=0; jj<9; jj++) { if (board[i][jj].value > 0) board[i][j].legalMoves[board[i][jj].value-1]=false; } int lx=0; int ux=2; int ly=0; int uy=2; if (i>2 && i<6) { lx=3; ux=5; } if (i>5) { lx=6; ux=8; } if (j>2 && j<6) { ly=3; uy=5; } if (j>5) { ly=6; uy=8; } for (int ix=lx; ix<=ux; ix++) { for (int jy=ly; jy<=uy; jy++) { if (board[ix][jy].value > 0) board[i][j].legalMoves[board[ix][jy].value-1]=false; } } } } } } /** * Return true if the puzzle is potentially solvable from this * position * @return true iff potentially solvalble */ public boolean solvable() { for (int i=0; i<9; i++) { for (int j=0; j<9; j++) { if (board[i][j].value == 0) { int kk=0; for (int k=0; k<9; k++) { if (board[i][j].legalMoves[k]) kk++; } if (kk==0) return false; } } } return true; } public String toString() { StringBuffer sb = new StringBuffer(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { sb.append(board[i][j].value); sb.append(","); } sb.append("\n"); } return sb.toString(); } // String rep of board showing legal moves at each position public String toStringLegal() { StringBuffer sb = new StringBuffer(); for (int i=0; i<9; i++) { for (int j=0; j<9; j++) { sb.append(board[i][j].toString()); sb.append(","); } sb.append("\n"); } return sb.toString(); } // 0 is an unsolvede loc //so noZeros is a solution has been reached public boolean noZeros() { for (int i=0; i<9; i++) { for (int j=0; j<9; j++) { if (board[i][j].value==0) return false; } } return true; } }