Start
import random class SudokuGenerator: BOARD_SIZE=9 SUBGRID_SIZE=3 def __init__(self) -> None: self.board = [[0 for _ in range(self.BOARD_SIZE)] for _ in range(self.BOARD_SIZE)] def generate(self): self.fill_values() return self.board def fill_values(self): self.fill_diagonal_subgrids() self.fill_remaining(0,self.SUBGRID_SIZE) def fill_diagonal_subgrids(self): for i in range(0,self.BOARD_SIZE, self.SUBGRID_SIZE): self.fill_subgrid(i,i) def fill_remaining(self, row, col): if row == self.BOARD_SIZE-1 and col == self.BOARD_SIZE: return True if col == self.BOARD_SIZE: row += 1 col = 0 if self.board[row][col] !=0: return self.fill_remaining(row,col+1) for num in range(1,self.BOARD_SIZE+1): if self.is_safe_to_place_num(row,col,num): self.board[row][col] = num if self.fill_remaining(row,col+1): return True self.board[row][col] = 0 return False def fill_subgrid(self, row, col): for i in range(self.SUBGRID_SIZE): for j in range(self.SUBGRID_SIZE): num = 0 while not self.is_safe_to_place_num(row+i,col+j,num): num = self.get_random_number() self.board[row+i][col+j] = num def is_safe_to_place_num(self, row, col, num): return not self.is_in_row(row,num) and not self.is_in_col(col,num) and not self.is_in_subgrid(row-row % self.SUBGRID_SIZE,col-col % self.SUBGRID_SIZE,num) def is_in_row(self, row, num): return num in self.board[row] def is_in_col(self, col, num): return num in [self.board[i][col] for i in range(self.BOARD_SIZE)] def is_in_subgrid(self, row, col, num): for i in range(self.SUBGRID_SIZE): for j in range(self.SUBGRID_SIZE): if self.board[row+i][col+j] == num: return True return False def get_random_number(self): return random.randint(1,self.BOARD_SIZE) class Sudoku: def __init__(self, board) -> None: self.board = board def printf(self): for row in self.board: print(" ".join(str(num) for num in row)) class SudokuGame: def main(self): generator = SudokuGenerator() board = generator.generate() sudoku = Sudoku(board) sudoku.printf(); if __name__ == "__main__": game = SudokuGame() game.main()
End
标签:游戏,Python,self,num,board,SIZE,col,数独,row From: https://www.cnblogs.com/lnsylt/p/17749792.html