java实现数独游戏
时间: 2023-07-11 21:04:36 浏览: 154
以下是一个简单的 Java 数独游戏实现:
```
import java.util.Scanner;
public class SudokuGame {
private int[][] board;
public SudokuGame() {
board = new int[9][9];
}
public void play() {
Scanner scanner = new Scanner(System.in);
while (!isComplete()) {
printBoard();
System.out.print("Enter row: ");
int row = scanner.nextInt();
System.out.print("Enter column: ");
int col = scanner.nextInt();
System.out.print("Enter value: ");
int val = scanner.nextInt();
if (isValidMove(row, col, val)) {
board[row][col] = val;
} else {
System.out.println("Invalid move, try again.");
}
}
System.out.println("Congratulations, you won!");
printBoard();
}
private boolean isComplete() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == 0) {
return false;
}
}
}
return true;
}
private boolean isValidMove(int row, int col, int val) {
if (row < 0 || row > 8 || col < 0 || col > 8 || val < 1 || val > 9) {
return false;
}
// Check row and column
for (int i = 0; i < 9; i++) {
if (board[i][col] == val || board[row][i] == val) {
return false;
}
}
// Check 3x3 box
int boxRow = row / 3 * 3;
int boxCol = col / 3 * 3;
for (int i = boxRow; i < boxRow + 3; i++) {
for (int j = boxCol; j < boxCol + 3; j++) {
if (board[i][j] == val) {
return false;
}
}
}
return true;
}
private void printBoard() {
System.out.println(" -----------------------");
for (int i = 0; i < 9; i++) {
System.out.print("| ");
for (int j = 0; j < 9; j++) {
System.out.print(board[i][j] == 0 ? " " : board[i][j]);
System.out.print(' ');
if (j % 3 == 2) {
System.out.print("| ");
}
}
System.out.println();
if (i % 3 == 2) {
System.out.println(" -----------------------");
}
}
}
public static void main(String[] args) {
SudokuGame game = new SudokuGame();
game.play();
}
}
```
这个实现使用一个 `9x9` 的二维数组来表示数独棋盘,其中 `0` 表示空格。`play()` 方法循环接受用户输入的行、列和值,并在输入合法时更新棋盘。`isComplete()` 方法检查棋盘是否已经完成,即是否所有空格都已经填写。`isValidMove()` 方法检查给定的行、列和值是否符合数独规则。`printBoard()` 方法打印当前的棋盘状态。
在 `main()` 方法中创建一个 `SudokuGame` 对象并调用 `play()` 方法开始游戏。
阅读全文