Sudoku - Generator Views
This article is part of a series in which a Sudoku game is implemented. As a second step, a generator view for showing Sudokus is built.
The SudokuGeneratorView holds a model class SudokuModel and includes Buttons for generating a random sudoku field. The SudokuGenerator is instantiated when needed only.
struct SampleSudokuGeneratorView: View {
@StateObject private var sudokuModel: SudokuModel = SudokuModel()
let color1: Color = Color(.systemGray6)
let color2: Color = Color(.systemGray4)
var body: some View {
VStack {
Text("Sudoku Generator")
.font(.largeTitle)
.padding(.bottom, 24)
Spacer()
VStack(spacing: 16) {
Button(action: {
let gen = SudokuGenerator()
gen.generate(model: sudokuModel)
}, label: {
Text("Generate")
})
.buttonStyle(.bordered)
Button(action: {
let gen = SudokuGenerator()
gen.makeGaps(model: sudokuModel, count: 30)
}, label: {
Text("Make Gaps")
})
.buttonStyle(.bordered)
}
.padding(.bottom, 32)
VStack(spacing: 0) {
ForEach(0 ..< SudokuModel.DIM, id: \.self) { row in
HStack(spacing: 0) {
ForEach(0 ..< SudokuModel.DIM, id: \.self) { col in
Text(sudokuModel.text(row: row, col: col))
.frame(width: 32, height: 32)
.background(
sudokuModel.colorIndex(row: row, col: col) == 1 ? color1 : color2
)
.border(Color.gray, width: 1)
.font(.system(size: 16, weight: .medium, design: .monospaced))
}
}
}
}
Spacer()
Spacer()
}
}
/* SudokuModel and SudokuGenerator are included in the first article */
}
#Preview {
SampleSudokuGeneratorView()
}