-
Notifications
You must be signed in to change notification settings - Fork 0
Collapse file tree
Files
Search this repository
/
Copy pathmain.cpp
More file actions
More file actions
Latest commit
660 lines (566 loc) · 23.9 KB
/
main.cpp
File metadata and controls
660 lines (566 loc) · 23.9 KB
You must be signed in to make or propose changes
More edit options
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
/*******************************************************
* Sudoku GUI (C++17 + raylib)
* -----------------------------------------------------
* ・マウスでマスをクリック → セル選択
* ・数字キー / テンキー → 入力
* ・0 / Del / Backspace → そのマスを空にする
*
* 追加機能:
* - Hキー:間違っているマスを赤で教えてくれるヒント
* - Nキー:新しい問題を生成
* - Sキー:解答を全部埋める(答え表示)
*
* 学べること:
* - 数独ロジック(バックトラック、盤生成、解の一意性チェック)
* - raylib を使ったシンプルな2D GUI
* - 入力処理(マウス / キーボード)
* - 状態管理(GameState 構造体)
*******************************************************/
#include "raylib.h" // 2D描画・ウィンドウ・入力処理などのライブラリ
#include <array> // std::array(固定長配列)
#include <vector> // std::vector(可変長配列)
#include <random> // std::mt19937 など乱数関連
#include <chrono> // 時刻を乱数シードに使う
#include <algorithm> // std::shuffle など
#include <stdexcept> // std::runtime_error などの例外
/********************************************************
* Board 型(9x9の数独盤)
* ------------------------------------------------------
* - 9行 × 9列 の int 配列
* - 0 → 空
* - 1〜9 → 数字
********************************************************/
using Board = std::array<std::array<int, 9>, 9>;
/*******************************************************
* ここから数独ロジック(CLI版でも共通で使えるコア部分)
*******************************************************/
/********************************************************
* IsValid()
* ------------------------------------------------------
* 指定した位置 (row, col) に num を置けるか判定する。
*
* チェック内容:
* 1. 同じ行に num がないか
* 2. 同じ列に num がないか
* 3. 同じ 3x3 ブロック内に num がないか
*
* どれかに引っかかったら false(置けない)
* 全部OKなら true(置いてよい)
********************************************************/
bool IsValid(const Board &board, int row, int col, int num) {
// ---------- 1. 行チェック ----------
for (int c = 0; c < 9; ++c) {
if (board[row][c] == num) {
return false;
}
}
// ---------- 2. 列チェック ----------
for (int r = 0; r < 9; ++r) {
if (board[r][col] == num) {
return false;
}
}
// ---------- 3. 3×3 ブロックチェック ----------
// (row, col) が属するブロックの左上の座標を求める。
int box_r = (row / 3) * 3;
int box_c = (col / 3) * 3;
// ブロック内は 3行×3列
for (int r = 0; r < 3; ++r) {
for (int c = 0; c < 3; ++c) {
if (board[box_r + r][box_c + c] == num) {
return false;
}
}
}
return true;
}
/********************************************************
* FindEmpty()
* ------------------------------------------------------
* 盤面の中から「まだ数字が入っていないマス(=0)」を探す。
*
* 見つかったら:
* - row, col に座標を入れて true
* 見つからなかったら:
* - false(=盤面が全て埋まっている → 完成状態)
********************************************************/
bool FindEmpty(const Board &board, int &row, int &col) {
for (row = 0; row < 9; ++row) {
for (col = 0; col < 9; ++col) {
if (board[row][col] == 0) {
// 最初に見つけた空マス
return true;
}
}
}
// 1つも 0 がない → 完成
return false;
}
/********************************************************
* Solve()
* ------------------------------------------------------
* 再帰的バックトラックによるソルバー。
*
* 手順:
* 1. 空きマスを 1 つ探す(FindEmpty)
* 2. 見つからない → 完成 → true
* 3. 1〜9 を順に試す
* 4. IsValid でOKなら仮置き → 再帰呼び出し
* 5. その先で true が返ればそのまま true
* 6. ダメだったら戻して(0にして)次の数字を試す
* 7. 全部ダメなら false
********************************************************/
bool Solve(Board &board) {
int row, col;
// まだ空いているマス(0のマス)を探す
if (!FindEmpty(board, row, col)) {
// 空きマスが無い → 全て埋まっている → 解けている
return true;
}
// 見つかった (row, col) に 1〜9 を順番に試す
for (int num = 1; num <= 9; ++num) {
if (IsValid(board, row, col, num)) {
// ルール上OKなので、いったん num を置いてみる
board[row][col] = num;
// 残りのマスも解けるか、再帰的に Solve() に任せる
if (Solve(board)) {
// どこかの深さで true(完成)が返されたら、
// ずっと true を返していく。
return true;
}
// ここまで来る=この num では解けなかった → 戻す
board[row][col] = 0;
}
}
// 1〜9 どれを試してもうまくいかなかった → 失敗
return false;
}
/********************************************************
* SolveCount()
* ------------------------------------------------------
* 解の数を数える関数。
*
* 目的:
* - パズル生成時に「解が1通りだけか?」をチェックするため
*
* 特徴:
* - count が limit(通常 2)に到達したら打ち切り
* → 「2個見つかった時点で『複数解あり』が確定」
********************************************************/
void SolveCount(Board &board, int &count, int limit = 2) {
// すでに十分な数を見つけていたら、それ以上探索しない
if (count >= limit) return;
int row, col;
if (!FindEmpty(board, row, col)) {
// 空きマスが無い → 解を1つ発見
++count;
return;
}
// 1〜9 を試して解の数を数える
for (int num = 1; num <= 9; ++num) {
if (IsValid(board, row, col, num)) {
board[row][col] = num;
SolveCount(board, count, limit);
board[row][col] = 0;
if (count >= limit) return;
}
}
}
/********************************************************
* Rng()
* ------------------------------------------------------
* 乱数生成器 std::mt19937 を 1 回だけ作って使い回す。
* シード(初期値)には「現在時刻からの経過時間」を使う。
********************************************************/
std::mt19937 &Rng() {
static std::mt19937 mt(
static_cast<unsigned int>(
std::chrono::high_resolution_clock::now().time_since_epoch().count()
)
);
return mt;
}
/********************************************************
* FillBoard()
* ------------------------------------------------------
* 完成済みの 9x9 数独盤をランダムに生成する。
*
* やっていることは Solve() に近いが、
* - 数字を 1〜9 順ではなくランダム順で試す
* ことで、毎回違う完成盤ができるようにしている。
********************************************************/
bool FillBoard(Board &board) {
int row, col;
if (!FindEmpty(board, row, col)) {
// 空きマス無し → 完成
return true;
}
// 1〜9 をベクターに詰める
std::vector<int> nums(9);
for (int i = 0; i < 9; ++i) nums[i] = i + 1;
// 数字の順番をランダムに並び替え
std::shuffle(nums.begin(), nums.end(), Rng());
// ランダム順で数字を試す
for (int num : nums) {
if (IsValid(board, row, col, num)) {
board[row][col] = num;
if (FillBoard(board)) {
// 先まで含めて完成できた → true
return true;
}
// ダメだった → 戻す
board[row][col] = 0;
}
}
// どの数字もダメだった → 失敗
return false;
}
/********************************************************
* GeneratePuzzle()
* ------------------------------------------------------
* 実際にユーザーに出す「問題の盤面」を生成する。
*
* 手順のイメージ:
* 1. まず完成盤(フルの答え)を1つ作る(FillBoard)
* 2. そこからマスを消していく(0 を入れる)
* 3. 消すたびに「解の数が1つだけか」をチェックする
* - 解の数を SolveCount() で数える(limit = 2)
* - 解が2つ以上になったら「戻して」そのマスは消さない
********************************************************/
Board GeneratePuzzle(int removeAttempts = 50) {
Board board{};
// まずは全部 0 で初期化
for (auto &row : board) {
row.fill(0);
}
// 完成盤を生成
if (!FillBoard(board)) {
throw std::runtime_error("Failed to generate full board");
}
// puzzle に完成盤をコピーし、こちらからマスを消していく
Board puzzle = board;
// 81マスを 0〜80 の 1次元インデックスで表現
std::vector<int> cells(81);
for (int i = 0; i < 81; ++i) {
cells[i] = i;
}
// マスを消す順番をランダムにする
std::shuffle(cells.begin(), cells.end(), Rng());
int attempts = removeAttempts; // 「戻した回数」を制御するためのパラメータ
for (int idx : cells) {
if (attempts <= 0) {
// もう調整したくない → ここで終了
break;
}
int r = idx / 9;
int c = idx % 9;
if (puzzle[r][c] == 0) {
// すでに空ならスキップ
Color cellColor = RAYWHITE;
// 選択中のマスなら、少し薄い青でハイライト
if (r == selectedRow && c == selectedCol) {
cellColor = Color{220, 240, 255, 255};
}
// セル背景を塗る
DrawRectangle(x, y, cellSize, cellSize, cellColor);
// ---- 数字の描画 ----
int value = state.current[r][c];
if (value != 0) {
// 1文字の数字を文字列として用意("1" 〜 "9")
char buf[2] = { static_cast<char>('0' + value), '\0' };
int fontSize = 32;
int textW = MeasureText(buf, fontSize);
int textX = x + (cellSize - textW) / 2;
int textY = y + (cellSize - fontSize) / 2 + 4;
// デフォルトの色:
// 初期配置(fixed=true) → 黒
// プレイヤーが入れた数字 → 青
Color numColor = state.fixed[r][c] ? BLACK : BLUE;
// ヒントで「間違っている」と判定されたマスは赤に上書き
if (state.invalid[r][c]) {
numColor = RED;
}
// 数字を描画
DrawText(buf, textX, textY, fontSize, numColor);
}
}
}
// ---------- グリッド線(マスの枠線)描画 ----------
for (int i = 0; i <= 9; ++i) {
int x = gridX + i * cellSize;
int y = gridY + i * cellSize;
// 3マスごとの区切り(0,3,6,9)は太線扱いで黒、
// それ以外(1,2,4,5,7,8)は薄いグレー。
Color lineColor = (i % 3 == 0) ? BLACK : LIGHTGRAY;
// 縦線
DrawLine(x, gridY, x, gridY + gridSizePx, lineColor);
// 横線
DrawLine(gridX, y, gridX + gridSizePx, y, lineColor);
}
// ---------- クリアメッセージ ----------
if (state.solved) {
const char *msg = "Solved!";
int msgFontSize = 30;
int msgWidth = MeasureText(msg, msgFontSize);
DrawText(
msg,
screenWidth / 2 - msgWidth / 2,
gridY + gridSizePx + 20,
msgFontSize,
DARKGREEN
);
}
EndDrawing(); // 描画終了 → 画面に反映
}
// ウィンドウを閉じて終了
CloseWindow();
return 0;
}