208 Commits

Author SHA1 Message Date
05df8a56a7 refactor read
Some checks failed
Linux arm64 / Build (push) Failing after 35s
2025-02-27 10:15:52 +01:00
af0ac0ff77 remove debug logs
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-26 17:01:29 +01:00
375e0eddbd udp: bigger buffer 2025-02-26 17:00:44 +01:00
7b90a81365 feat: udp
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-26 16:59:15 +01:00
11a246adfd fix multiplayer loading screen
Some checks failed
Linux arm64 / Build (push) Failing after 49s
2025-02-03 11:03:40 +01:00
20db850334 Update README.md
All checks were successful
Linux arm64 / Build (push) Successful in 28s
2025-02-02 23:01:51 +00:00
Melvyn
69135e8173 fix : fin
Some checks failed
Linux arm64 / Build (push) Failing after 32s
2025-02-03 00:00:33 +01:00
09aa4bc3c1 Update README.md
Some checks failed
Linux arm64 / Build (push) Failing after 29s
2025-02-02 22:59:07 +00:00
836eb85e1f Update README.md
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-02-02 22:58:01 +00:00
Melvyn
3bf3ed23ba doc : add javadoc
Some checks failed
Linux arm64 / Build (push) Failing after 29s
2025-02-02 23:56:01 +01:00
Melvyn
6a54635c59 fix : doc
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-02-02 23:55:03 +01:00
78537be4e9 fix warnings
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-02-02 23:45:22 +01:00
Melvyn
5a1fd9ff9d doc : Dossier de conception
Some checks failed
Linux arm64 / Build (push) Failing after 29s
2025-02-02 23:39:54 +01:00
c047379d01 fix multidoku display
All checks were successful
Linux arm64 / Build (push) Successful in 40s
2025-02-02 23:29:29 +01:00
5bda0a1be7 feat: add + shaped mutlidokus gui
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-02-02 23:27:34 +01:00
c3610c47c9 send disconnect packet
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-02-02 23:13:56 +01:00
08ed9b46b1 fix multi login 2025-02-02 23:13:28 +01:00
2595af2d48 doc solver
All checks were successful
Linux arm64 / Build (push) Successful in 44s
2025-02-02 22:56:19 +01:00
edfc5733db fix mixedsolver 2025-02-02 22:56:14 +01:00
Melvyn
71666a3883 refactor : mini fixs
All checks were successful
Linux arm64 / Build (push) Successful in 44s
2025-02-02 22:51:33 +01:00
3f1ef93323 doc: serializer
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-02-02 22:29:52 +01:00
a580321bd0 doc: constraints
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-02-02 22:25:28 +01:00
d7d7dfe787 restore console save
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-02-02 22:06:45 +01:00
Janet-Doe
2fb3874a99 update ConsoleInterface
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-02 21:46:29 +01:00
Janet-Doe
591e4f977a update ConsoleInterface
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-02-02 21:31:32 +01:00
Janet-Doe
c481f66b0c add doc + delete unused class
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-02 21:03:36 +01:00
Janet-Doe
aafb025874 doc ConsoleInterface
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-02-02 17:50:15 +01:00
Melvyn
627c49b961 refactor : StateManager
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-02-02 16:42:31 +01:00
Melvyn
b4157167b5 refactor : SudokuFactory
All checks were successful
Linux arm64 / Build (push) Successful in 43s
2025-02-02 16:38:04 +01:00
Melvyn
1419898955 refactor : Sudoku
Some checks failed
Linux arm64 / Build (push) Failing after 32s
2025-02-02 16:22:08 +01:00
Melvyn
dd3be67be0 refactor : MultiDoku
Some checks failed
Linux arm64 / Build (push) Failing after 28s
2025-02-02 16:13:51 +01:00
Melvyn
c6a32b8d07 refactor : Difficulty
Some checks failed
Linux arm64 / Build (push) Failing after 30s
2025-02-02 16:07:29 +01:00
Melvyn
a8439df736 refactor : Coordinate
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-02 16:03:13 +01:00
Melvyn
27032d264d refactor : Block
Some checks failed
Linux arm64 / Build (push) Failing after 30s
2025-02-02 15:57:30 +01:00
Melvyn
8afd51b353 refactor : Cell
Some checks failed
Linux arm64 / Build (push) Failing after 29s
2025-02-02 15:52:10 +01:00
2460b7539e action test after
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-02-02 15:42:18 +01:00
0f5020b0b4 fix tests
Some checks failed
Linux arm64 / Build (push) Failing after 29s
2025-02-02 15:41:29 +01:00
ac4f859fd8 refactor build.gradle
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-02 15:07:26 +01:00
4a8644181a build.gradle fix tests
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-02 15:03:26 +01:00
efa357a1ab refactor MixedSolver 2025-02-02 14:56:31 +01:00
618e436270 refactor stupidsolver 2025-02-02 14:43:09 +01:00
d5009371f2 remove unused import
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-02-02 14:39:56 +01:00
87727f39e8 refactor HumanSolver
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-02-02 14:36:47 +01:00
413201882b change loading text
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-02-02 14:24:56 +01:00
d8289b553a fix empty grid gen
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-02 14:24:23 +01:00
Janet-Doe
adeb9b07e5 update solver tests
All checks were successful
Linux arm64 / Build (push) Successful in 40s
2025-02-02 11:51:56 +01:00
Janet-Doe
4903fd567b tests redaction
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-02 11:36:22 +01:00
990c830590 Fixes #5
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-02-02 11:33:21 +01:00
d806420d21 Fixes #32
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-02-02 11:01:10 +01:00
4b98341618 feat: basic gen loading 2025-02-02 10:53:24 +01:00
68021b796b Fixes #28
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-02-02 10:35:00 +01:00
06efbf649b Fixes #33
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-02-02 10:27:42 +01:00
4ee29d8f50 Fixes #10
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-02-02 10:17:09 +01:00
eda2a1afae Fixes #39 2025-02-02 10:14:27 +01:00
f3bbfd9e6c feat: show resolve logs
All checks were successful
Linux arm64 / Build (push) Successful in 40s
2025-02-02 00:04:52 +01:00
Melvyn
129c3ef0b2 fix : countSolutions
All checks were successful
Linux arm64 / Build (push) Successful in 36s
2025-02-01 23:39:04 +01:00
14d0521215 NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-02-01 23:15:57 +01:00
7568208045 fix warnings
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-02-01 23:07:53 +01:00
86aa6e9bb5 refactor: move classes
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-02-01 23:06:11 +01:00
91c645e34f fix steps
All checks were successful
Linux arm64 / Build (push) Successful in 43s
2025-02-01 23:00:36 +01:00
78bdefebe5 feat: add history 2025-02-01 22:54:02 +01:00
3e30332245 Merge branch 'constraint'
All checks were successful
Linux arm64 / Build (push) Successful in 4m2s
2025-02-01 22:29:03 +01:00
275878932b refactor: IConstraints in sudoku
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-01 22:24:26 +01:00
68d577a99a Merge pull request 'finished console interface' (#37) from osekour into master
All checks were successful
Linux arm64 / Build (push) Successful in 23m58s
Reviewed-on: #37
2025-02-01 20:48:26 +00:00
fa3124220d finished console interface
All checks were successful
Linux arm64 / Build (push) Successful in 5m14s
2025-02-01 20:43:01 +00:00
3a009256c5 Fixes #12
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-01 21:16:36 +01:00
d09bf6e9ce feat: allow user to be wrong
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-01 21:12:13 +01:00
5da915932d Fixes #31
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-01 21:00:59 +01:00
da422e78b8 Fixes #30
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-01 20:59:06 +01:00
f0a0a8e328 Fixes #23
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-01 20:55:08 +01:00
436b641269 Fixes #34 2025-02-01 20:47:40 +01:00
34a59546e6 remove unused import
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-01 20:46:06 +01:00
9e2421accf Fixes #25 2025-02-01 20:45:56 +01:00
52ca8b208c fix: sudoku save
All checks were successful
Linux arm64 / Build (push) Successful in 23m59s
2025-02-01 16:11:38 +00:00
Janet-Doe
140d37fbd9 update console interface
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-01 15:51:45 +01:00
Janet-Doe
2b3581a400 fix
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-01 14:56:45 +01:00
a6b1fae230 Merge branch 'gradle'
Some checks failed
Linux arm64 / Build (push) Failing after 23s
2025-02-01 14:49:54 +01:00
a20a5387a7 chore: bundle deps in jar 2025-02-01 14:34:19 +01:00
Janet-Doe
8c672e24ad merged version
Some checks failed
Linux arm64 / Build (push) Failing after 22s
2025-02-01 14:32:11 +01:00
Janet-Doe
815756b5e9 functional multidoku printer
# Conflicts:
#	app/src/main/java/sudoku/io/ConsoleInterface.java
#	app/src/main/java/sudoku/solver/Solver.java
2025-02-01 14:29:54 +01:00
a1032335a5 chore: remove unused deps 2025-02-01 14:10:15 +01:00
336d8378ae fix: slower background animation speed by default
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-01 13:45:44 +01:00
c165ecdae5 Merge pull request 'Fixes #15' (#36) from multiplayer into master
All checks were successful
Linux arm64 / Build (push) Successful in 39s
Reviewed-on: #36
2025-02-01 12:43:13 +00:00
352aee49e4 feat: make timer stop game (Fixes #15)
All checks were successful
Linux arm64 / Build (push) Successful in 29s
2025-02-01 13:41:13 +01:00
f22debdf5f fix: score display
All checks were successful
Linux arm64 / Build (push) Successful in 28s
2025-02-01 12:54:11 +01:00
02089c649b feat: select game duration
All checks were successful
Linux arm64 / Build (push) Successful in 28s
2025-02-01 12:27:50 +01:00
e98199e1ec refactor: remove sysout
All checks were successful
Linux arm64 / Build (push) Successful in 25s
2025-02-01 11:59:05 +01:00
438252a8ca feat: first player progress display 2025-02-01 11:58:42 +01:00
caf6569409 fix: synced timer
All checks were successful
Linux arm64 / Build (push) Successful in 26s
2025-02-01 11:22:59 +01:00
3863c812c8 fix: format timer
All checks were successful
Linux arm64 / Build (push) Successful in 26s
2025-02-01 10:56:02 +01:00
6d96455ac4 feat: display wrong timer
All checks were successful
Linux arm64 / Build (push) Successful in 28s
2025-02-01 00:19:00 +01:00
a5c046f891 feat: good leaderboard 2025-02-01 00:09:25 +01:00
Melvyn
b7f9ca8a98 fix : MixedSolver
All checks were successful
Linux arm64 / Build (push) Successful in 40s
2025-01-31 18:26:44 +01:00
a160042ef4 feat: uggly leaderboard
All checks were successful
Linux arm64 / Build (push) Successful in 27s
2025-01-31 13:48:51 +01:00
f47e4cc309 feat: animated background
All checks were successful
Linux arm64 / Build (push) Successful in 10m56s
2025-01-30 22:28:26 +01:00
25c2270a37 feat: multi synced player scores
All checks were successful
Linux arm64 / Build (push) Successful in 31s
2025-01-30 22:16:29 +01:00
bcded60fbe small fix 2025-01-30 21:46:55 +01:00
edfffaf061 feat: multi select sudoku
All checks were successful
Linux arm64 / Build (push) Successful in 27s
2025-01-30 18:35:41 +01:00
a74bf42e59 refactor solvers
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-30 18:05:18 +01:00
1f92c49f3c feat: select solve algorithm
All checks were successful
Linux arm64 / Build (push) Successful in 25m12s
2025-01-30 17:28:43 +01:00
c262007ca8 fix multithreading issue 2025-01-30 17:28:22 +01:00
73f572ee18 fix merge
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-30 16:37:10 +01:00
ec07d88577 Merge branch 'symbols' 2025-01-30 16:35:05 +01:00
6caf5d5c54 feat: add cyrilic
All checks were successful
Linux arm64 / Build (push) Successful in 29s
2025-01-30 16:32:09 +01:00
Janet-Doe
696062e9db merge image branch with main
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-01-30 16:23:07 +01:00
Janet-Doe
c825807aea set background picture 2025-01-30 16:23:03 +01:00
39529e0b64 fix agaaaaain 2025-01-30 16:22:47 +01:00
3fa22a4cf0 fix build.gradle (agin) 2025-01-30 16:22:43 +01:00
337911d038 bye bye png lib 2025-01-30 16:21:53 +01:00
1930bc02bd aaaaaa
# Conflicts:
#	app/src/main/java/sudoku/Main.java
#	app/src/main/java/sudoku/solver/Solver.java
2025-01-30 16:21:43 +01:00
b9788d6a51 application du cours d'APO de 15h
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-01-30 15:24:57 +01:00
7789209651 feat: change symbols
All checks were successful
Linux arm64 / Build (push) Successful in 27s
2025-01-30 15:23:54 +01:00
Melvyn
54a4bd9f22 feat : diminue automatiquement la difficulté si elle n'est pas possible
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-01-30 14:59:19 +01:00
8596781ce3 Fixes #14
All checks were successful
Linux arm64 / Build (push) Successful in 40s
2025-01-30 14:51:21 +01:00
Melvyn
d6c3504bc7 feat : mixedSolve
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-01-30 14:32:15 +01:00
44a4432ac0 Merge branch 'master' of git.ale-pri.com:Ryuk/Sudoku
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-01-30 13:21:05 +01:00
a42ec2f27c fix merge 2025-01-30 13:14:43 +01:00
bff7abcd02 Merge branch 'serialize-fix' 2025-01-30 13:13:44 +01:00
Melvyn
bf67afe4a9 refactor : Solver
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-01-30 12:03:03 +01:00
67da77af2e feat: add states
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-01-30 11:54:23 +01:00
c4becf2d55 fix: serialize 2025-01-30 11:54:21 +01:00
Janet-Doe
f1d963e546 semi-functionning console interface
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-01-30 11:51:17 +01:00
b9a6617967 feat: add states
All checks were successful
Linux arm64 / Build (push) Successful in 26s
2025-01-30 09:34:00 +01:00
03f577828b fix: serialize 2025-01-30 00:51:22 +01:00
9b776d4b0f custom symbols
All checks were successful
Linux arm64 / Build (push) Successful in 26s
2025-01-29 19:47:46 +01:00
d4beaec8a8 Merge pull request 'fix desezrialize' (#18) from fix into master
All checks were successful
Linux arm64 / Build (push) Successful in 37s
Reviewed-on: #18
2025-01-29 18:29:32 +00:00
a742cace3a fix desezrialize
All checks were successful
Linux arm64 / Build (push) Successful in 25s
2025-01-29 19:28:36 +01:00
Melvyn
e12955ab4a merge
All checks were successful
Linux arm64 / Build (push) Successful in 36s
2025-01-29 18:57:00 +01:00
Melvyn
412684e6f0 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	app/src/main/java/sudoku/structure/MultiDoku.java
#	app/src/main/java/sudoku/structure/Sudoku.java
#	app/src/main/java/sudoku/structure/SudokuFactory.java
#	app/src/test/java/sudoku/solver/SolverTest.java
2025-01-29 18:51:23 +01:00
Melvyn
cd4d01e1e6 fix : MultiDoku.getCells 2025-01-29 18:42:58 +01:00
ff85cbef01 Fix #4
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-01-29 18:32:50 +01:00
c16f2b8f5a feat: dynamic constraints (Fixes #8)
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-01-29 17:19:44 +01:00
5e26bea609 refactor: remove sudokufactory difficulties 2025-01-29 16:11:56 +01:00
cd792a0f8a add diagonal constraint
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-29 15:48:01 +01:00
de1f3c59d6 refactor isValid
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-01-29 15:13:43 +01:00
c0a3f85f24 test: clean serializer files 2025-01-29 15:12:52 +01:00
a616ab63e4 gui: save sudoku
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-29 15:08:30 +01:00
00866256a7 gui: revert suoku scrolling 2025-01-29 15:07:34 +01:00
ed9b636b58 tests: make it faster 2025-01-29 14:59:06 +01:00
a10d2eda9a gui: fix big grid display
All checks were successful
Linux arm64 / Build (push) Successful in 1m2s
2025-01-29 14:42:41 +01:00
c4a9bf6354 gui: select from file
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-29 14:14:54 +01:00
074131b69c refactor sudoku selection
All checks were successful
Linux arm64 / Build (push) Successful in 1m8s
2025-01-29 12:42:06 +01:00
21b7011ece 🗣️🔥
All checks were successful
Linux arm64 / Build (push) Successful in 59s
2025-01-29 12:25:43 +01:00
859d5795d0 nerd
All checks were successful
Linux arm64 / Build (push) Successful in 57s
2025-01-29 12:22:19 +01:00
cd81334c95 basic README
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-29 12:18:33 +01:00
89653f8517 gui: display victory
All checks were successful
Linux arm64 / Build (push) Successful in 58s
2025-01-29 12:10:30 +01:00
9213a10c17 gui: difficulties
All checks were successful
Linux arm64 / Build (push) Successful in 1m20s
2025-01-29 11:56:32 +01:00
4190bf15d8 difficulties
All checks were successful
Linux arm64 / Build (push) Successful in 52s
2025-01-29 11:47:18 +01:00
Melvyn
a221233c06 fix : création MultiDoku à résoudre avec cell imuable
All checks were successful
Linux arm64 / Build (push) Successful in 53s
2025-01-29 11:26:36 +01:00
5ad8fa30f4 fix edit of immutable cells
All checks were successful
Linux arm64 / Build (push) Successful in 43s
2025-01-29 11:24:43 +01:00
532b2d152b Prepare fix for #5
All checks were successful
Linux arm64 / Build (push) Successful in 57s
2025-01-29 11:23:16 +01:00
ec36e19c4e Fixes #2
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-29 11:05:15 +01:00
Janet-Doe
aa86e9b956 valid tests save and getFromSave sudoku
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-29 10:55:35 +01:00
b8553428ee fix: create solvable sudoku
All checks were successful
Linux arm64 / Build (push) Successful in 53s
2025-01-29 10:34:40 +01:00
Melvyn
7c06fe2e31 feat : création MultiDoku à résoudre
All checks were successful
Linux arm64 / Build (push) Successful in 1m7s
2025-01-29 10:21:26 +01:00
Melvyn
cd45d1c22c feat : humanSolve
All checks were successful
Linux arm64 / Build (push) Successful in 50s
2025-01-29 09:55:14 +01:00
Melvyn
c7217894b2 adding documentation 2025-01-29 09:13:24 +01:00
Janet-Doe
6801bd2efc addo save directory
All checks were successful
Linux arm64 / Build (push) Successful in 52s
2025-01-29 09:12:32 +01:00
Janet-Doe
a6dea76785 addo save in json files
All checks were successful
Linux arm64 / Build (push) Successful in 40s
2025-01-28 18:58:26 +01:00
4208e7058f feat: ui remove cell content
All checks were successful
Linux arm64 / Build (push) Successful in 4m7s
2025-01-28 15:18:29 +01:00
944f2c0596 feat: various ui changes
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-01-28 14:56:06 +01:00
f489c4c8ab remove useless class
All checks were successful
Linux arm64 / Build (push) Successful in 24m6s
2025-01-28 11:30:16 +01:00
c430a1e1b0 fix previous commit 2025-01-28 11:30:09 +01:00
Melvyn
5eabf87c94 doc : Block, Cell, Coordiante, MultiDoku
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-01-28 11:21:49 +01:00
a1fd715aee fix solver log display
All checks were successful
Linux arm64 / Build (push) Successful in 24m1s
2025-01-28 10:08:26 +01:00
Melvyn
ebb3a4c48a feat : logger
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-01-28 10:00:01 +01:00
b1ae79a2e8 add multidoku to solo
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-01-28 09:56:44 +01:00
0174ec08d7 Merge branch 'master' of git.ale-pri.com:Ryuk/Sudoku
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-01-28 09:25:27 +01:00
c7d3430d21 multidoku constraints gui
Some checks are pending
Linux arm64 / Build (push) Waiting to run
2025-01-28 09:20:48 +01:00
182f79d4b4 feat: render multidokus
Some checks are pending
Linux arm64 / Build (push) Waiting to run
2025-01-28 08:55:58 +01:00
Melvyn
4c02be3d39 feat : generation de doku par rapport à une difficulté
Some checks are pending
Linux arm64 / Build (push) Waiting to run
2025-01-27 16:17:22 +01:00
e9a77d9826 render multidoku (may be broken)
Some checks are pending
Linux arm64 / Build (push) Waiting to run
2025-01-27 15:52:00 +01:00
Melvyn
584a1c8b42 fix : solver tests
Some checks are pending
Linux arm64 / Build (push) Waiting to run
2025-01-27 14:49:47 +01:00
Melvyn
80239274d7 feat : solver random
Some checks are pending
Linux arm64 / Build (push) Waiting to run
2025-01-27 14:48:28 +01:00
3a0279afe3 begin multidoku display code 2025-01-26 22:19:56 +01:00
3bb610b9c2 Merge branch 'network'
All checks were successful
Linux arm64 / Build (push) Successful in 23m59s
2025-01-26 21:16:57 +01:00
df07f11a9c basic multiplayer
Some checks failed
Linux arm64 / Build (push) Failing after 5m3s
2025-01-26 18:53:45 +01:00
6658b0e884 show player names
Some checks failed
Linux arm64 / Build (push) Failing after 5m3s
2025-01-26 18:22:20 +01:00
47dc35ebfa more stable connexion
Some checks failed
Linux arm64 / Build (push) Failing after 5m1s
2025-01-26 14:54:46 +01:00
e51cc23459 mooore stuff
Some checks failed
Linux arm64 / Build (push) Failing after 5m5s
2025-01-26 13:46:23 +01:00
e64fa97573 display sudoku inner grids
All checks were successful
Linux arm64 / Build (push) Successful in 23m58s
2025-01-24 22:42:23 +01:00
4b4ed76eb8 canellable stupid solver
All checks were successful
Linux arm64 / Build (push) Successful in 24m8s
2025-01-24 21:41:12 +01:00
00941edb19 resolve doku gui
All checks were successful
Linux arm64 / Build (push) Successful in 24m6s
2025-01-24 16:51:17 +01:00
Melvyn
8f4330f710 merge
All checks were successful
Linux arm64 / Build (push) Successful in 24m8s
2025-01-24 16:17:56 +01:00
Melvyn
981bf8529d Merge branch 'solver'
Some checks failed
Linux arm64 / Build (push) Has been cancelled
# Conflicts:
#	app/src/main/java/sudoku/Main.java
#	app/src/main/java/sudoku/Sudoku.java
2025-01-24 15:51:25 +01:00
Melvyn
187bcea939 fix : solverTest
All checks were successful
Linux arm64 / Build (push) Successful in 5m5s
2025-01-23 23:47:12 +01:00
Melvyn
483b286bac feat : solver + test
All checks were successful
Linux arm64 / Build (push) Successful in 5m9s
2025-01-23 23:20:16 +01:00
caf7011f08 update Gradle
All checks were successful
Linux arm64 / Build (push) Successful in 5m11s
2025-01-23 22:24:48 +01:00
bfe98a2cf0 better network structure
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-01-23 22:24:23 +01:00
baafa15fa4 Revert gradle test version
All checks were successful
Linux arm64 / Build (push) Successful in 24m14s
2025-01-23 20:44:06 +00:00
2f6f58334c Update gradle version
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-01-23 20:43:41 +00:00
7e38fe2ac2 Update test gradle version
Some checks failed
Linux arm64 / Build (push) Failing after 37s
2025-01-23 20:39:35 +00:00
ecf3f0a7ce Update java test requirements
Some checks failed
Linux arm64 / Build (push) Failing after 23m34s
2025-01-23 20:13:22 +00:00
5e99cd92df network structure
Some checks failed
Linux arm64 / Build (push) Failing after 5m1s
2025-01-23 18:59:11 +01:00
Melvyn
6902321101 fix : passage de solve() en métode static
All checks were successful
Linux arm64 / Build (push) Successful in 5m9s
2025-01-23 16:29:54 +01:00
Melvyn
fc7ae02387 feat : Solver.solve() 2025-01-23 16:28:41 +01:00
b05351bc20 more menus
Some checks failed
Linux arm64 / Build (push) Failing after 14m21s
2025-01-23 15:50:10 +01:00
7ab1173fb3 change BaseMenu to BaseView
Some checks failed
Linux arm64 / Build (push) Failing after 5m2s
2025-01-23 14:41:40 +01:00
749f5c831d add menu logic
Some checks failed
Linux arm64 / Build (push) Failing after 5m1s
2025-01-23 12:50:00 +01:00
48fc88d8ab fix constraints
All checks were successful
Linux arm64 / Build (push) Successful in 5m12s
2025-01-23 10:37:50 +01:00
6c8bfad18d add SudokuRenderer
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-01-23 10:33:59 +01:00
ba65cb9ff5 rainbow
All checks were successful
Linux arm64 / Build (push) Successful in 5m42s
2025-01-22 22:41:47 +01:00
396abb30b3 Merge branch 'master' into gui 2025-01-22 20:51:12 +01:00
ea5afa66df basic grid display
All checks were successful
Linux arm64 / Build (push) Successful in 33s
2025-01-22 16:09:00 +01:00
a8359d2f69 comic
All checks were successful
Linux arm64 / Build (push) Successful in 53s
2025-01-21 22:12:23 +01:00
2d980ac816 non
All checks were successful
Linux arm64 / Build (push) Successful in 24s
2025-01-21 20:51:03 +01:00
fl.du.pr Grens
42d5bdc8d6 update title window
All checks were successful
Linux arm64 / Build (push) Successful in 28s
2025-01-21 20:50:33 +01:00
121c60ddef feneeeeeeeeeeetre
All checks were successful
Linux arm64 / Build (push) Successful in 26s
2025-01-21 19:59:24 +01:00
269 changed files with 34807 additions and 664 deletions

View File

@@ -13,13 +13,13 @@ jobs:
- uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
java-version: '21'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v4
- name: Build with Gradle
run: ./gradlew build
run: ./gradlew assemble
- name: Test
run: ./gradlew test

4
.gitignore vendored
View File

@@ -7,4 +7,6 @@ build
.vscode
.idea
output.puml
output.puml
imgui.ini

26
README.md Normal file
View File

@@ -0,0 +1,26 @@
# Sudoku 🧩
Une application de génération et résolution de MultiDoku.
## Features 🌟
- MultiDoku solvers
- Graphical User Interface (GUI)
- Sudoku saves
- Multiplayer
## Develop ☝🤓
**Pour plus de détails sur la conception et autres, regarder le 👉 [wiki](https://git.ale-pri.com/Ryuk/Sudoku/wiki)** 👈
### Run 🏃
```sh
./gradlew run
```
### Run tests 🗣️🔥
```sh
./gradlew test
```

View File

@@ -18,26 +18,38 @@ repositories {
dependencies {
// Use JUnit Jupiter for testing.
testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1'
// This dependency is used by the application.
implementation 'com.google.guava:guava:31.1-jre'
// uml
implementation 'com.github.javaparser:javaparser-symbol-solver-core:3.26.2'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
implementation 'org.json:json:20250107'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.18.2'
implementation "io.github.spair:imgui-java-app:1.88.0"
implementation "org.lwjgl:lwjgl-stb:3.3.4"
implementation "org.lwjgl:lwjgl-stb::natives-linux"
implementation "org.lwjgl:lwjgl-stb::natives-windows"
implementation "org.lwjgl:lwjgl-stb::natives-macos"
}
application {
// Define the main class for the application.
mainClass = 'sudoku.Main'
mainClass = 'gui.Main'
}
tasks.named('test') {
// Use JUnit Platform for unit tests.
// Add libraries into the final jar
jar {
archiveBaseName = rootProject.getName()
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
manifest {
attributes "Main-Class": application.mainClass
}
from {
configurations.compileClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}
test {
useJUnitPlatform()
}

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

0
app/save/.gitignore vendored Normal file
View File

View File

@@ -0,0 +1,27 @@
package common;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
public class ConsumerSignal<T> {
private final Set<Consumer<T>> listeners;
public ConsumerSignal() {
this.listeners = new HashSet<>();
}
public void connect(Consumer<T> listener) {
this.listeners.add(listener);
}
public void clear() {
this.listeners.clear();
}
public void emit(T arg) {
for (Consumer<T> listener : this.listeners) {
listener.accept(arg);
}
}
}

View File

@@ -0,0 +1,31 @@
package common;
import java.util.HashSet;
import java.util.Set;
public class Signal {
private final Set<Runnable> listeners;
public Signal() {
this.listeners = new HashSet<>();
}
public void connect(Runnable listener) {
this.listeners.add(listener);
}
public void clear() {
this.listeners.clear();
}
public void emit() {
for (Runnable listener : this.listeners) {
listener.run();
}
}
// public void disconnect(Runnable listener) {
// this.listeners.remove(listener);
// }
}

View File

@@ -0,0 +1,86 @@
package game;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import sudoku.structure.MultiDoku;
public class Game {
public static enum GameState {
GameNotStarted, GameGoing
}
private final Map<Integer, Player> players;
private final List<Player> leaderboard;
private GameState gameState;
private MultiDoku doku;
private Instant startTime = null;
private long gameDuration;
public Game() {
this.players = new HashMap<>();
this.leaderboard = new ArrayList<>();
this.gameState = GameState.GameNotStarted;
}
public Player getPlayerById(int id) {
return players.get(id);
}
public void addPlayer(Player player) {
players.put(player.getId(), player);
leaderboard.add(player);
}
public void setPlayerRemainingCells(Player player, int newScore) {
player.setRemainingCells(newScore);
Collections.sort(this.leaderboard,
(player1, player2) -> Integer.compare(player1.getRemainingCells(), player2.getRemainingCells()));
}
public void removePlayer(int id) {
this.leaderboard.remove(getPlayerById(id));
this.players.remove(id);
}
public Map<Integer, Player> getPlayers() {
return players;
}
public void startGame(MultiDoku doku, Instant startTime, long gameDuration) {
this.doku = doku;
this.gameState = GameState.GameGoing;
this.startTime = startTime;
this.gameDuration = gameDuration;
}
public void stopGame() {
this.gameState = GameState.GameNotStarted;
}
public GameState getGameState() {
return gameState;
}
public MultiDoku getDoku() {
return doku;
}
public List<Player> getLeaderboard() {
return leaderboard;
}
public Instant getStartTime() {
return startTime;
}
public long getGameDuration() {
return gameDuration;
}
}

View File

@@ -0,0 +1,35 @@
package game;
import java.io.Serializable;
public class Player implements Serializable {
static private final long serialVersionUID = 9999;
private final String pseudo;
private final int id;
private int score;
public Player(int id, String pseudo) {
this.pseudo = pseudo;
this.id = id;
this.score = 0;
}
public int getRemainingCells() {
return score;
}
void setRemainingCells(int score) {
this.score = score;
}
public String getPseudo() {
return this.pseudo;
}
public int getId() {
return this.id;
}
}

View File

@@ -0,0 +1,32 @@
package gui;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class AssetManager {
public static byte[] getResource(String name) {
// we first search it in files
File f = new File(name);
if (f.exists()){
FileInputStream fis;
try {
fis = new FileInputStream(f);
return fis.readAllBytes();
} catch (IOException e) {
e.printStackTrace();
}
}
// then in the jar
InputStream is = ClassLoader.getSystemResourceAsStream(name);
try {
return is.readAllBytes();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

View File

@@ -0,0 +1,70 @@
package gui;
import java.util.ArrayList;
import java.util.List;
public class ColorGenerator {
public static class Color {
public float r, g, b;
public Color(float r, float g, float b) {
this.r = r;
this.g = g;
this.b = b;
}
}
public static List<Color> greatPalette(int colorCount) {
List<Color> colors = greatScheme(colorCount);
List<Color> newOrder = new ArrayList<>();
int newIndex = 0;
while (!colors.isEmpty()) {
int randomIndex = newIndex % colors.size();
newOrder.add(colors.get(randomIndex));
colors.remove(randomIndex);
newIndex += Math.sqrt(colorCount) + 1;
}
return newOrder;
}
public static List<Color> greatScheme(int colorCount) {
List<Color> colors = new ArrayList<>();
for (int i = 0; i < colorCount; i++) {
colors.add(hslToRgb((float) (i) / (float) colorCount, 0.9f, 0.4f));
}
return colors;
}
public static Color hslToRgb(float h, float s, float l){
float r, g, b;
if (s == 0f) {
r = g = b = l; // achromatic
} else {
float q = l < 0.5f ? l * (1 + s) : l + s - l * s;
float p = 2 * l - q;
r = hueToRgb(p, q, h + 1f/3f);
g = hueToRgb(p, q, h);
b = hueToRgb(p, q, h - 1f/3f);
}
return new Color(r, g, b);
}
/** Helper method that converts hue to rgb */
public static float hueToRgb(float p, float q, float t) {
if (t < 0f)
t += 1f;
if (t > 1f)
t -= 1f;
if (t < 1f / 6f)
return p + (q - p) * 6f * t;
if (t < 1f / 2f)
return q;
if (t < 2f / 3f)
return p + (q - p) * (2f / 3f - t) * 6f;
return p;
}
}

View File

@@ -0,0 +1,46 @@
package gui;
import gui.constants.Fonts;
import gui.constants.Images;
import gui.menu.MainMenu;
import gui.menu.StateMachine;
import imgui.app.Application;
import imgui.app.Configuration;
public class Main extends Application {
private final StateMachine stateMachine = new StateMachine();
@Override
protected void configure(Configuration config) {
config.setTitle("Let's play sudoku!");
}
@Override
protected void disposeWindow() {
stateMachine.clear();
}
@Override
protected void initImGui(Configuration config) {
super.initImGui(config);
Fonts.createFonts();
stateMachine.pushState(new MainMenu(stateMachine));
}
@Override
protected void preRun() {
super.preRun();
Images.reloadImages();
}
@Override
public void process() {
stateMachine.render();
// ImGui.showDemoWindow();
}
public static void main(String[] args) {
launch(new Main());
}
}

View File

@@ -0,0 +1,189 @@
package gui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import sudoku.structure.Block;
import sudoku.structure.Cell;
import sudoku.structure.Coordinate;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
public class RenderableMultidoku {
private final MultiDoku doku;
private final List<Cell> cells;
private final List<Block> blocks;
private final int width;
private final int height;
private RenderableMultidoku(MultiDoku doku, List<Block> blocks, List<Cell> cells, int width, int height) {
this.cells = cells;
this.blocks = blocks;
this.width = width;
this.height = height;
this.doku = doku;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public List<Block> getBlocks() {
return this.blocks;
}
public Cell getCell(int x, int y) {
return getCell(y * width + x);
}
public Cell getCell(int index) {
return cells.get(index);
}
private static record PositionConstraint(Sudoku sudoku1, Sudoku sudoku2, Coordinate offset) {
}
private static Coordinate getConstraint(Sudoku sudoku1, Sudoku sudoku2) {
int blockWidth = sudoku1.getBlockWidth();
int blockHeight = sudoku1.getSize() / blockWidth;
for (int i = 0; i < sudoku1.getSize(); i++) {
for (int j = 0; j < sudoku2.getSize(); j++) {
Block block1 = sudoku1.getBlocks().get(i);
Block block2 = sudoku2.getBlocks().get(j);
if (block1 == block2) {
int block1X = i % blockHeight;
int block1Y = i / blockHeight;
int block2X = j % blockHeight;
int block2Y = j / blockHeight;
return new Coordinate((block1X - block2X) * blockWidth, (block1Y - block2Y) * blockHeight);
}
}
}
return null;
}
private static boolean hasContraint(Sudoku sudoku1, Sudoku sudoku2, List<PositionConstraint> positionConstraints) {
for (PositionConstraint constraint : positionConstraints) {
if ((constraint.sudoku1 == sudoku1 && constraint.sudoku2 == sudoku2)
|| (constraint.sudoku1 == sudoku2 && constraint.sudoku2 == sudoku1))
return true;
}
return false;
}
private static Coordinate getMinSudokuOffset(Map<Sudoku, Coordinate> sudokusOffset) {
Coordinate minCoordinate = null;
for (Coordinate coordinate : sudokusOffset.values()) {
if (minCoordinate == null)
minCoordinate = coordinate;
minCoordinate = new Coordinate(Math.min(minCoordinate.getX(), coordinate.getX()),
Math.min(minCoordinate.getY(), coordinate.getY()));
}
return minCoordinate;
}
private static Coordinate getMaxSudokuCoordinate(Map<Sudoku, Coordinate> sudokusOffset) {
int maxX = 0;
int maxY = 0;
Sudoku lastSudoku = null;
for (var entry : sudokusOffset.entrySet()) {
Coordinate coordinate = entry.getValue();
if (coordinate.getX() > maxX)
maxX = coordinate.getX();
if (coordinate.getY() > maxY)
maxY = coordinate.getY();
lastSudoku = entry.getKey();
}
Coordinate maxCoordinate = new Coordinate(maxX, maxY);
// tous les sudokus sont censés faire la même taille
int sudokuSize = lastSudoku.getSize();
return new Coordinate(maxCoordinate.getX() + sudokuSize, maxCoordinate.getY() + sudokuSize);
}
public static RenderableMultidoku fromMultidoku(MultiDoku doku) {
if (doku.getNbSubGrids() == 1) {
Sudoku sudoku = doku.getSubGrid(0);
return new RenderableMultidoku(doku, sudoku.getBlocks(), sudoku.getCells(), sudoku.getSize(),
sudoku.getSize());
}
Map<Sudoku, Coordinate> sudokusOffset = new HashMap<>();
// coordinates in cell
List<PositionConstraint> positionConstraints = new ArrayList<>();
for (Sudoku sudoku1 : doku.getSubGrids()) {
for (Sudoku sudoku2 : doku.getSubGrids()) {
if (sudoku1 == sudoku2)
continue;
Coordinate constraint = getConstraint(sudoku1, sudoku2);
if (constraint != null && !hasContraint(sudoku1, sudoku2, positionConstraints)) {
positionConstraints.add(new PositionConstraint(sudoku1, sudoku2, constraint));
}
}
}
for (PositionConstraint constraint : positionConstraints) {
if (!sudokusOffset.containsKey(constraint.sudoku1) && !sudokusOffset.containsKey(constraint.sudoku2)) {
sudokusOffset.put(constraint.sudoku1, new Coordinate(0, 0));
sudokusOffset.put(constraint.sudoku2, constraint.offset());
}
if (sudokusOffset.containsKey(constraint.sudoku1)) {
sudokusOffset.put(constraint.sudoku2, constraint.offset.add(sudokusOffset.get(constraint.sudoku1)));
} else {
sudokusOffset.put(constraint.sudoku1, constraint.offset.add(sudokusOffset.get(constraint.sudoku2)));
}
}
Coordinate minCoordinate = getMinSudokuOffset(sudokusOffset);
for (var entry : sudokusOffset.entrySet()) {
entry.setValue(entry.getValue().sub(minCoordinate));
}
Coordinate maxCoordinate = getMaxSudokuCoordinate(sudokusOffset);
List<Block> blocks = new ArrayList<>();
List<Cell> cells = new ArrayList<>(maxCoordinate.getX() * maxCoordinate.getY());
for (int i = 0; i < maxCoordinate.getX() * maxCoordinate.getY(); i++) {
cells.add(null);
}
for (var entry : sudokusOffset.entrySet()) {
Sudoku sudoku = entry.getKey();
Coordinate offset = entry.getValue();
for (int x = 0; x < sudoku.getSize(); x++) {
for (int y = 0; y < sudoku.getSize(); y++) {
Cell cell = sudoku.getCell(x, y);
int absoluteX = x + offset.getX();
int absoluteY = y + offset.getY();
cells.set(absoluteY * maxCoordinate.getX() + absoluteX, cell);
}
}
for (Block block : sudoku.getBlocks()) {
if (!blocks.contains(block)) {
blocks.add(block);
}
}
}
return new RenderableMultidoku(doku, blocks, cells, maxCoordinate.getX(), maxCoordinate.getY());
}
public MultiDoku getDoku() {
return doku;
}
}

View File

@@ -0,0 +1,33 @@
package gui.constants;
import gui.AssetManager;
import imgui.ImFont;
import imgui.ImFontConfig;
import imgui.ImFontGlyphRangesBuilder;
import imgui.ImGui;
public class Fonts {
public static ImFont ARIAL;
public static ImFont ARIAL_BOLD;
public static ImFont CHERI;
public static ImFont COMIC;
public static ImFont INFECTED;
public static ImFont EMOJIS;
public static void createFonts() {
ImFontGlyphRangesBuilder builder = new ImFontGlyphRangesBuilder();
builder.addRanges(ImGui.getIO().getFonts().getGlyphRangesDefault());
builder.addRanges(ImGui.getIO().getFonts().getGlyphRangesCyrillic());
ImFontConfig cfg = new ImFontConfig();
cfg.setGlyphRanges(builder.buildRanges());
COMIC = ImGui.getIO().getFonts().addFontFromMemoryTTF(AssetManager.getResource("comic.ttf"), 50.0f);
ARIAL_BOLD = ImGui.getIO().getFonts().addFontFromMemoryTTF(AssetManager.getResource("arial_bold.ttf"), 50.0f);
ARIAL = ImGui.getIO().getFonts().addFontFromMemoryTTF(AssetManager.getResource("arial.ttf"), 50.0f, cfg);
CHERI = ImGui.getIO().getFonts().addFontFromMemoryTTF(AssetManager.getResource("cheri.ttf"), 50.0f);
INFECTED = ImGui.getIO().getFonts().addFontFromMemoryTTF(AssetManager.getResource("INFECTED.ttf"), 50.0f);
}
}

View File

@@ -0,0 +1,44 @@
package gui.constants;
import java.nio.ByteBuffer;
import org.lwjgl.opengl.GL11;
import org.lwjgl.stb.STBImage;
import gui.AssetManager;
public class Images {
public static int BACKGROUND;
private static int loadTexture(byte[] imageData) {
int[] width = new int[1];
int[] height = new int[1];
int[] channelCount = new int[1];
ByteBuffer img = ByteBuffer.allocateDirect(imageData.length);
img.put(imageData);
img.flip();
ByteBuffer pixels = STBImage.stbi_load_from_memory(img, width, height, channelCount, 4);
int textureID = GL11.glGenTextures();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); // Not on WebGL/ES
GL11.glPixelStorei(GL11.GL_UNPACK_SKIP_PIXELS, 0); // Not on WebGL/ES
GL11.glPixelStorei(GL11.GL_UNPACK_SKIP_ROWS, 0); // Not on WebGL/ES
GL11.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, 0); // Not on WebGL/ES
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, width[0], height[0], 0,
GL11.GL_RGBA,
GL11.GL_UNSIGNED_BYTE, pixels);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
return textureID;
}
public static void reloadImages() {
BACKGROUND = loadTexture(AssetManager.getResource(Options.BackgroundPath));
}
}

View File

@@ -0,0 +1,9 @@
package gui.constants;
public class Options {
public static Symbols Symboles = Symbols.Numbers;
public static float BackgroundSpeed = 1.0f;
public static String BackgroundPath = "background.png";
}

View File

@@ -0,0 +1,67 @@
package gui.constants;
import java.util.List;
import sudoku.constraint.IConstraint;
import sudoku.structure.MultiDoku;
import sudoku.structure.SudokuFactory;;
public enum SudokuType {
Square("Carré", 1,
(constraints, params) -> SudokuFactory.createBasicEmptySquareDoku(params[0], constraints)),
Rectangle("Rectangle", 2,
(constraints, params) -> SudokuFactory.createBasicEmptyRectangleDoku(params[0], params[1], constraints)),
RandomBloc("Blocs aléatoires", 1,
(constraints, params) -> SudokuFactory.createBasicEmptyRandomBlockDoku(params[0], constraints)),
MultiDokuXSquare("Multidoku carré (X)", 1,
(constraints, params) -> SudokuFactory.createBasicXShapedMultidoku(params[0], constraints)),
MultidokuXRectangle("Multidoku rectangle (X)", 2,
(constraints, params) -> SudokuFactory.createBasicXShapedMultidoku(params[0], params[1], constraints)),
MultiDokuPlusSquare("Multidoku carré (+)", 1,
(constraints, params) -> SudokuFactory.createBasicPlusShapedMultidoku(params[0], constraints)),
MultidokuPlusRectangle("Multidoku rectangle (+)", 2,
(constraints, params) -> SudokuFactory.createBasicXShapedMultidoku(params[0], params[1], constraints));
String displayName;
SudokuMaker maker;
int paramCount;
private SudokuType(String displayName, int paramCount, SudokuMaker maker) {
this.displayName = displayName;
this.maker = maker;
this.paramCount = paramCount;
}
public String getDisplayName() {
return this.displayName;
}
public MultiDoku createDoku(List<IConstraint> constraints, int... params) {
return maker.makeSudoku(constraints, params);
}
public int getMakerParamCount() {
return this.paramCount;
}
@FunctionalInterface
private static interface SudokuMaker {
MultiDoku makeSudoku(List<IConstraint> constraints, int... params);
}
private static final String[] dokuNames;
static {
SudokuType[] types = SudokuType.values();
dokuNames = new String[types.length];
for (int i = 0; i < types.length; i++) {
dokuNames[i] = types[i].getDisplayName();
}
}
public static String[] getTypeNames() {
return dokuNames;
}
}

View File

@@ -0,0 +1,83 @@
package gui.constants;
import java.util.ArrayList;
import java.util.List;
public enum Symbols {
Numbers("Nombres", getNumbers()),
Letters("Lettres", getLetters()),
Russian("Cyrilique", getRussian()),
Emojis("Emojis (Console uniquement)", getEmojis());
String displayName;
List<String> symbols;
private Symbols(String displayName, List<String> symbols) {
this.symbols = symbols;
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
public List<String> getSymbols() {
return symbols;
}
private static List<String> getNumbers() {
List<String> sym = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
sym.add(Integer.toString(i));
}
return sym;
}
private static List<String> getLetters() {
List<String> sym = new ArrayList<>();
for (int i = 0; i < 100; i++) {
int currentOffset = i;
String letter = "";
while (currentOffset >= 26) {
letter += Character.toString((char) ('A' + currentOffset % 26));
currentOffset /= 26;
currentOffset--;
}
letter += Character.toString((char) ('A' + currentOffset % 26));
sym.add(new StringBuilder(letter).reverse().toString());
}
return sym;
}
private static List<String> getRussian() {
List<String> sym = new ArrayList<>();
for (int i = 0; i < 100; i++) {
sym.add(new String(Character.toChars(0X0400 + i)));
}
return sym;
}
private static List<String> getEmojis() {
List<String> sym = new ArrayList<>();
for (int i = 0; i < 100; i++) {
sym.add(new String(Character.toChars(0X1F600 + i)));
}
return sym;
}
private static final String[] symbolNames;
static {
Symbols[] symbols = Symbols.values();
symbolNames = new String[symbols.length];
for (int i = 0; i < symbols.length; i++) {
symbolNames[i] = symbols[i].getDisplayName();
}
}
public static String[] getSymbolsNames() {
return symbolNames;
}
}

View File

@@ -0,0 +1,33 @@
package gui.menu;
import imgui.ImGui;
public abstract class BaseView {
protected final StateMachine stateMachine;
public BaseView(StateMachine stateMachine) {
this.stateMachine = stateMachine;
}
public abstract void render();
public void cleanResources() {}
public void closeMenu(int count) {
for (int i = 0; i < count; i++) {
this.stateMachine.popState();
}
}
public void closeMenu() {
closeMenu(1);
}
protected void renderReturnButton() {
if (ImGui.button("Retour")) {
closeMenu();
}
}
}

View File

@@ -0,0 +1,106 @@
package gui.menu;
import java.io.IOException;
import java.net.UnknownHostException;
import imgui.ImGui;
import network.client.Client;
import network.server.Server;
public class ConnexionStatusView extends BaseView {
private Client client;
private Server server;
private String displayText = "Connecting ...";
public ConnexionStatusView(StateMachine stateMachine, String pseudo, String address, short port)
throws UnknownHostException, IOException {
super(stateMachine);
Thread t = new Thread(() -> {
try {
this.client = new Client(pseudo, address, port);
bindListeners();
} catch (IOException e) {
e.printStackTrace();
onDisconnect();
}
});
t.start();
}
public ConnexionStatusView(StateMachine stateMachine, String pseudo, short port)
throws UnknownHostException, IOException {
super(stateMachine);
Thread t = new Thread(() -> {
try {
this.server = new Server(port);
this.client = new Client(pseudo, "localhost", port);
bindListeners();
} catch (IOException e) {
e.printStackTrace();
onDisconnect();
}
});
t.start();
}
private void bindListeners() {
this.client.onConnect.connect(this::onConnect);
this.client.onClosed.connect(this::onLeave);
this.client.onDisconnect.connect(this::onDisconnect);
}
private ConnexionStatusView(StateMachine stateMachine, Server server, Client client) {
super(stateMachine);
this.client = client;
this.server = server;
}
public void onConnect() {
this.stateMachine.pushState(new MultiPlayerView(stateMachine, client, server));
}
public void onDisconnect() {
if (client != null) {
String reason = client.getDisconnectReason();
if (reason == null)
displayText = "Le serveur a fermé la connexion !";
else
displayText = "Vous avez été déconnecté ! Raison : " + client.getDisconnectReason();
} else {
displayText = "La connexion a échoué !";
}
}
public void onLeave() {
this.client = null;
// on passe le menu de la connexion
this.closeMenu();
}
@Override
public void render() {
ImGui.text(displayText);
renderReturnButton();
}
@Override
public void closeMenu() {
super.closeMenu();
cleanResources();
}
@Override
public void cleanResources() {
// System.out.println("Bye bye !");
if (this.server != null) {
this.server.stop();
}
if (this.client != null) {
this.client.stop();
}
}
}

View File

@@ -0,0 +1,49 @@
package gui.menu;
import game.Player;
import gui.ColorGenerator;
import gui.widget.SudokuRenderer;
import imgui.ImGui;
import imgui.ImVec4;
import sudoku.structure.MultiDoku;
public class EndGameView extends BaseView {
private final Player winner;
private float time = 0;
private static final ImVec4 YELLOW = new ImVec4(1, 1, 0, 1);
private final SudokuRenderer sudokuRenderer;
public EndGameView(StateMachine stateMachine, MultiDoku resolved, Player winner) {
super(stateMachine);
this.winner = winner;
this.sudokuRenderer = new SudokuRenderer(resolved);
}
private ImVec4 getPseudoColor() {
time += ImGui.getIO().getDeltaTime();
float factor = (float) Math.cos(time);
var color = ColorGenerator.hslToRgb(factor * factor, 0.9f, 0.4f);
return new ImVec4(color.r, color.g, color.b, 1.0f);
}
private void renderWinText() {
String winText = " a gagné !";
String text = winner.getPseudo() + winText;
float textWidth = ImGui.calcTextSizeX(text);
ImGui.setCursorPosX(ImGui.getIO().getDisplaySizeX() / 2.0f - textWidth / 2.0f);
ImGui.textColored(getPseudoColor(), winner.getPseudo());
ImGui.sameLine();
ImGui.textColored(YELLOW, winText);
}
@Override
public void render() {
renderWinText();
this.sudokuRenderer.render();
renderReturnButton();
}
}

View File

@@ -0,0 +1,37 @@
package gui.menu;
import imgui.ImGui;
import imgui.ImVec2;
public class MainMenu extends BaseView {
public MainMenu(StateMachine stateMachine) {
super(stateMachine);
}
@Override
public void render() {
var displaySize = ImGui.getIO().getDisplaySize();
ImVec2 buttonSize = new ImVec2(500, 150);
int paddingHeight = 20;
float centerX = displaySize.x / 2.0f - buttonSize.x / 2.0f;
float centerY = displaySize.y / 2.0f - buttonSize.y / 2.0f;
ImGui.setCursorPos(centerX, centerY - buttonSize.y - paddingHeight);
if (ImGui.button("Mode histoire", buttonSize)) {
this.stateMachine.pushState(new SoloMenu(this.stateMachine));
}
ImGui.setCursorPos(centerX, centerY);
if (ImGui.button("Multijoueur", buttonSize)) {
this.stateMachine.pushState(new MultiMenu(this.stateMachine));
}
ImGui.setCursorPos(centerX, centerY + buttonSize.y + paddingHeight);
if (ImGui.button("Options", buttonSize)) {
this.stateMachine.pushState(new OptionsMenu(this.stateMachine));
}
}
}

View File

@@ -0,0 +1,73 @@
package gui.menu;
import java.io.IOException;
import java.util.Random;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.type.ImInt;
import imgui.type.ImString;
public class MultiMenu extends BaseView {
private final ImInt port = new ImInt(25565);
private final ImString address = new ImString("localhost");
private final ImString pseudo = new ImString("Joueur" + new Random().nextInt());
public MultiMenu(StateMachine stateMachine) {
super(stateMachine);
address.resize(20);
}
private void renderCreate() {
ImVec2 displaySize = ImGui.getIO().getDisplaySize();
ImGui.beginChild("##CreateGame", new ImVec2(displaySize.x / 2.0f, displaySize.y * 8.0f / 9.0f));
if (ImGui.inputInt("Port", port))
port.set(Math.clamp(port.get(), 1, 65535));
ImGui.inputText("Pseudo", pseudo);
if (ImGui.button("Créer")) {
try {
this.stateMachine.pushState(new ConnexionStatusView(stateMachine, pseudo.get(), (short) port.get()));
} catch (IOException e) {
e.printStackTrace();
}
}
ImGui.endChild();
}
private void renderJoin() {
ImVec2 displaySize = ImGui.getIO().getDisplaySize();
ImGui.beginChild("##JoinGame", new ImVec2(displaySize.x / 2.0f, displaySize.y * 8.0f / 9.0f));
ImGui.inputText("Adresse", address);
if (ImGui.inputInt("Port", port))
port.set(Math.clamp(port.get(), 1, 65535));
ImGui.inputText("Pseudo", pseudo);
if (ImGui.button("Rejoindre")) {
try {
this.stateMachine.pushState(new ConnexionStatusView(stateMachine, pseudo.get(), address.get(), (short) port.get()));
} catch (IOException e) {
e.printStackTrace();
}
}
ImGui.endChild();
}
@Override
public void render() {
renderCreate();
ImGui.sameLine();
renderJoin();
ImVec2 displaySize = ImGui.getIO().getDisplaySize();
ImVec2 buttonSize = new ImVec2(500, 70.0f);
float centerX = displaySize.x / 2.0f - buttonSize.x / 2.0f;
ImGui.setCursorPosX(centerX);
if (ImGui.button("Retour", buttonSize)) {
closeMenu();
}
}
}

View File

@@ -0,0 +1,68 @@
package gui.menu;
import game.Player;
import gui.widget.LeaderboardRenderer;
import gui.widget.MultiPlayerCompleteProgress;
import gui.widget.SudokuRenderer;
import gui.widget.TimerRenderer;
import imgui.ImGui;
import network.client.Client;
import network.server.Server;
import sudoku.solver.BacktrackingSolver;
import sudoku.solver.Solver;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
public class MultiPlayerDokuView extends BaseView {
private final Client client;
private final Server server;
private final SudokuRenderer sudokuRenderer;
private final LeaderboardRenderer leaderboardRenderer;
private final TimerRenderer timerRenderer;
private final MultiPlayerCompleteProgress completeProgress;
public MultiPlayerDokuView(StateMachine stateMachine, Client client, Server server) {
super(stateMachine);
this.client = client;
this.server = server;
this.sudokuRenderer = new SudokuRenderer(this.client.getGame().getDoku());
this.leaderboardRenderer = new LeaderboardRenderer(client.getGame(), client.getPlayer());
this.sudokuRenderer.onCellChange.connect(this::onCellChange);
this.client.onDisconnect.connect(this::onDisconnect);
this.client.onGameEnd.connect(this::onGameEnd);
this.timerRenderer = new TimerRenderer(this.client.getGame().getStartTime(), this.client.getGame().getGameDuration());
this.completeProgress = new MultiPlayerCompleteProgress(this.client.getGame());
}
private void onGameEnd(Player winner) {
MultiDoku doku = this.client.getGame().getDoku();
doku.clearMutableCells();
Solver solver = new BacktrackingSolver();
solver.solve(doku);
this.stateMachine.overrideState(new EndGameView(stateMachine, doku, winner));
}
private void onCellChange(Cell cell) {
this.client.sendCellChange(cell);
}
public void onDisconnect() {
if (server == null) {
closeMenu();
}
}
@Override
public void render() {
this.timerRenderer.render();
this.leaderboardRenderer.render();
this.completeProgress.render();
this.sudokuRenderer.render();
if (ImGui.button("Quitter")) {
this.client.stop();
this.closeMenu(3);
}
}
}

View File

@@ -0,0 +1,86 @@
package gui.menu;
import game.Player;
import gui.widget.SudokuSelector;
import imgui.ImGui;
import imgui.type.ImInt;
import network.client.Client;
import network.server.Server;
import sudoku.structure.MultiDoku;
public class MultiPlayerView extends BaseView {
private final Client client;
private final Server server;
private final SudokuSelector selector;
private ImInt gameDurationMinutes = new ImInt(10);
private MultiDoku doku = null;
public MultiPlayerView(StateMachine stateMachine, Client client, Server server) {
super(stateMachine);
this.client = client;
this.server = server;
this.selector = new SudokuSelector(false, "Sélectionner le sudoku");
this.selector.onSelect.connect(this::onSelected);
this.client.onDisconnect.connect(this::onDisconnect);
this.client.onGameStarted
.connect(() -> this.stateMachine.pushState(new MultiPlayerDokuView(stateMachine, client, server)));
}
@Override
public void closeMenu() {
this.client.forceDisconnect();
super.closeMenu();
}
public void onDisconnect() {
this.stateMachine.popState();
}
private void onSelected(MultiDoku doku) {
this.doku = doku;
}
public void renderGameStatus() {
if (this.server == null) {
ImGui.text("En attente de l'administrateur du serveur ...");
} else {
renderTimer();
ImGui.beginDisabled(this.doku == null);
if (ImGui.button("Démarrer")) {
this.server.startGame(this.doku, this.gameDurationMinutes.get() * 60);
}
ImGui.endDisabled();
selector.render();
}
}
private void renderPlayers() {
ImGui.text("Joueurs :");
{
for (Player player : this.client.getGame().getPlayers().values()) {
ImGui.bulletText(player.getPseudo());
}
}
}
private void renderTimer() {
if (ImGui.inputInt("Temps de la partie (minutes)", gameDurationMinutes))
gameDurationMinutes.set(Math.clamp(gameDurationMinutes.get(), 1, 90));
}
@Override
public void render() {
renderPlayers();
renderGameStatus();
}
@Override
public void cleanResources() {
this.selector.clean();
}
}

View File

@@ -0,0 +1,57 @@
package gui.menu;
import gui.constants.Images;
import gui.constants.Options;
import gui.constants.Symbols;
import imgui.ImGui;
import imgui.extension.imguifiledialog.ImGuiFileDialog;
import imgui.extension.imguifiledialog.flag.ImGuiFileDialogFlags;
import imgui.type.ImInt;
public class OptionsMenu extends BaseView {
private ImInt currentValue = new ImInt();
private float backgroundSpeed[] = new float[] { Options.BackgroundSpeed };
public OptionsMenu(StateMachine stateMachine) {
super(stateMachine);
}
private void renderImageSelectDialog() {
if (ImGuiFileDialog.display("browse-img", ImGuiFileDialogFlags.None)) {
if (ImGuiFileDialog.isOk()) {
var selection = ImGuiFileDialog.getSelection();
for (var entry : selection.entrySet()) {
try {
String filePath = entry.getValue();
Options.BackgroundPath = filePath;
Images.reloadImages();
} catch (Exception e) {
e.printStackTrace();
}
}
}
ImGuiFileDialog.close();
}
}
private void renderImageSelectButton() {
if (ImGui.button("Changer de fond d'écran"))
ImGuiFileDialog.openDialog("browse-img", "Choisissez un fichier", ".png,.jpg,.jpeg", ".");
renderImageSelectDialog();
}
@Override
public void render() {
ImGui.text("Options");
if (ImGui.combo("Jeu de symboles", currentValue, Symbols.getSymbolsNames())) {
Options.Symboles = Symbols.values()[currentValue.get()];
}
if (ImGui.sliderFloat("Vitesse d'animation de l'arrière plan", backgroundSpeed, 0.0f, 10.0f)) {
Options.BackgroundSpeed = backgroundSpeed[0];
}
renderImageSelectButton();
renderReturnButton();
}
}

View File

@@ -0,0 +1,33 @@
package gui.menu;
import gui.widget.SudokuSelector;
import imgui.ImGui;
import sudoku.structure.MultiDoku;
public class SoloMenu extends BaseView {
private final SudokuSelector sudokuSelector;
public SoloMenu(StateMachine stateMachine) {
super(stateMachine);
this.sudokuSelector = new SudokuSelector(true, "Résoudre le sudoku");
this.sudokuSelector.onSelect.connect(this::pushSudokuState);
}
private void pushSudokuState(MultiDoku doku) {
this.stateMachine.pushState(new SudokuView(stateMachine, doku));
}
@Override
public void render() {
ImGui.text("Solo");
sudokuSelector.render();
renderReturnButton();
}
@Override
public void cleanResources() {
this.sudokuSelector.clean();
}
}

View File

@@ -0,0 +1,61 @@
package gui.menu;
import java.util.Stack;
import gui.widget.AnimatedBackground;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.flag.ImGuiKey;
import imgui.flag.ImGuiWindowFlags;
public class StateMachine {
private final Stack<BaseView> menus;
private final AnimatedBackground background;
public StateMachine() {
this.menus = new Stack<>();
this.background = new AnimatedBackground();
}
public void clear() {
for (BaseView view : menus) {
view.cleanResources();
}
menus.clear();
}
public void pushState(BaseView menu) {
menus.add(menu);
}
public void overrideState(BaseView menu) {
menus.getLast().cleanResources();
menus.set(menus.size() - 1, menu);
}
public void popState() {
menus.getLast().cleanResources();
menus.pop();
}
private void checkEscape() {
if (ImGui.isKeyPressed(ImGuiKey.Escape) && menus.size() > 1) {
menus.getLast().closeMenu();
}
}
public void render() {
var displaySize = ImGui.getIO().getDisplaySize();
this.background.render();
ImGui.setNextWindowPos(new ImVec2(0.0f, 0.0f));
ImGui.setNextWindowSize(displaySize);
ImGui.begin("##Main Window", null, ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.NoMove
| ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoBackground);
menus.get(menus.size() - 1).render();
ImGui.end();
// ImGui.showDemoWindow();
checkEscape();
}
}

View File

@@ -0,0 +1,184 @@
package gui.menu;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import gui.widget.SudokuRenderer;
import imgui.ImGui;
import imgui.ImGuiStyle;
import sudoku.io.SudokuSerializer;
import sudoku.solver.BacktrackingSolver;
import sudoku.solver.HintHelper;
import sudoku.solver.HumanSolver;
import sudoku.solver.MixedSolver;
import sudoku.solver.Solver;
import sudoku.solver.SolverStep;
import sudoku.solver.HintHelper.Hint;
import sudoku.structure.MultiDoku;
public class SudokuView extends BaseView {
private final SudokuRenderer sudokuRenderer;
private Thread resolveThread;
private final MultiDoku doku;
private String lastSavePath = null;
private boolean resolved = false;
// if the solver can't solve
private volatile boolean unresolved = false;
public SudokuView(StateMachine stateMachine, MultiDoku doku) {
super(stateMachine);
this.doku = doku;
this.sudokuRenderer = new SudokuRenderer(doku);
this.sudokuRenderer.onResolve.connect(this::onResolve);
}
private void onResolve() {
this.resolved = true;
}
private void stopResolve() {
if (resolveThread != null && resolveThread.isAlive()) {
resolveThread.interrupt();
resolveThread = null;
}
}
boolean centeredButton(String label) {
ImGuiStyle style = ImGui.getStyle();
float size = ImGui.calcTextSizeX(label) + style.getFramePaddingX() * 2.0f;
float avail = ImGui.getContentRegionAvailX();
float off = (avail - size) * 0.5f;
if (off > 0.0f)
ImGui.setCursorPosX(ImGui.getCursorPosX() + off);
return ImGui.button(label);
}
private void renderCancelButton() {
boolean wantsToStop = false;
if (resolveThread != null && resolveThread.isAlive()) {
// ImGui.endDisabled();
if (centeredButton("Annuler")) {
// we can't stop the Thread right now
wantsToStop = true;
}
}
if (resolveThread != null && !resolveThread.isAlive()) {
resolveThread.start();
}
if (wantsToStop)
stopResolve();
}
private void renderHintButton() {
if (!this.resolved && centeredButton("Indice")) {
Hint hint = HintHelper.getHint(this.doku, new BacktrackingSolver());
assert (hint != null);
hint.cell().setSymbolIndex(hint.newValue());
if (this.doku.isSolved())
this.sudokuRenderer.onResolve.emit();
}
}
private void renderUnsolvableText() {
if (this.unresolved)
ImGui.text("Impossible de résoudre avec l'algorithme actuel !");
}
private void startSolve(Solver solver) {
this.doku.clearMutableCells();
resolveThread = new Thread(() -> {
List<SolverStep> steps = new ArrayList<>();
try {
unresolved = !solver.solve(this.doku, steps);
} catch (CancellationException e) {
System.out.println("The user is bored !");
}
stopResolve();
});
}
private void renderResolvedText() {
if (this.resolved)
ImGui.text("Bravo !");
}
private void renderSolvePopup() {
if (ImGui.beginPopup("solve")) {
if (ImGui.button("Résoudre avec backtrace")) {
startSolve(new BacktrackingSolver());
ImGui.closeCurrentPopup();
}
if (ImGui.button("Résoudre avec déduction")) {
startSolve(new HumanSolver());
ImGui.closeCurrentPopup();
}
if (ImGui.button("Résoudre avec déduction et backtrace")) {
startSolve(new MixedSolver());
ImGui.closeCurrentPopup();
}
ImGui.endPopup();
}
}
private void renderSolveButton() {
if (resolveThread != null)
ImGui.beginDisabled();
if (!this.resolved && centeredButton("Résoudre")) {
ImGui.openPopup("solve");
}
if (resolveThread != null)
ImGui.endDisabled();
renderResolvedText();
renderUnsolvableText();
renderSolvePopup();
}
private void renderSaveButton() {
if (ImGui.button("Sauvegarder l'état de la grille")) {
lastSavePath = SudokuSerializer.saveMultiDoku(doku);
ImGui.openPopup("saveDone");
}
if (ImGui.beginPopup("saveDone")) {
ImGui.text("Sudoku sauvegardé dans ");
ImGui.text(lastSavePath);
ImGui.endPopup();
}
}
private void renderClearButton() {
if (centeredButton("Effacer")) {
this.doku.clearMutableCells();
this.resolved = false;
this.unresolved = false;
}
}
@Override
public void render() {
sudokuRenderer.render();
renderHintButton();
renderClearButton();
renderSolveButton();
renderSaveButton();
renderCancelButton();
renderReturnButton();
}
@Override
public void closeMenu() {
super.closeMenu();
stopResolve();
}
}

View File

@@ -0,0 +1,32 @@
package gui.widget;
import gui.constants.Images;
import gui.constants.Options;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.flag.ImGuiWindowFlags;
public class AnimatedBackground {
private float backgroundOffset = 0;
private static final float defaultSpeed = 0.05f;
public AnimatedBackground() {
}
public void render() {
backgroundOffset += ImGui.getIO().getDeltaTime() * defaultSpeed * Options.BackgroundSpeed;
var displaySize = ImGui.getIO().getDisplaySize();
ImGui.setNextWindowPos(new ImVec2(0.0f, 0.0f));
ImGui.setNextWindowSize(displaySize);
ImGui.begin("Background", null, ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.NoMove
| ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoBackground
| ImGuiWindowFlags.NoBringToFrontOnFocus | ImGuiWindowFlags.NoInputs);
ImGui.image(Images.BACKGROUND, displaySize, new ImVec2(backgroundOffset, backgroundOffset),
new ImVec2(1.0f + backgroundOffset, 1.0f + backgroundOffset));
ImGui.end();
}
}

View File

@@ -0,0 +1,73 @@
package gui.widget;
import game.Game;
import game.Player;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.ImVec4;
import imgui.flag.ImGuiCol;
import imgui.flag.ImGuiStyleVar;
public class LeaderboardRenderer {
private final Game game;
private final Player currentPlayer;
private final float cellHeight = 75;
private final ImVec2 cellSize = new ImVec2(12 * cellHeight, cellHeight);
private final ImVec2 rankSize = new ImVec2(cellHeight, cellHeight);
private final ImVec2 scoreSize = rankSize;
private final ImVec2 nameSize = new ImVec2(cellSize.x - cellHeight * 2.0f, cellHeight);
private final ImVec4 cellColorPlayer = new ImVec4(0.20f, 0.67f, 1.0f, 0.5f);
private final ImVec4 cellColorEnemy = new ImVec4(1.0f, 0.0f, 0.0f, 0.5f);
private final int maxPlayersShowed = 2;
private final int emptyCellCount;
public LeaderboardRenderer(Game game, Player player) {
this.game = game;
this.currentPlayer = player;
this.emptyCellCount = game.getDoku().getEmptyCells().size();
}
private void renderRank(int rank) {
ImGui.button(Integer.toString(rank), rankSize);
}
private void renderName(String name) {
ImGui.button(name, nameSize);
}
private void renderScore(int score) {
ImGui.button(Integer.toString(score), scoreSize);
}
private void renderCell(Player player, int rank, ImVec4 color) {
ImGui.pushStyleColor(ImGuiCol.Button, color);
ImGui.pushStyleColor(ImGuiCol.ButtonHovered, color);
ImGui.pushStyleColor(ImGuiCol.ButtonActive, color);
ImGui.beginChild(player.getPseudo() + "##" + player.getId(), cellSize);
renderRank(rank);
ImGui.sameLine();
renderName(player.getPseudo());
ImGui.sameLine();
renderScore(emptyCellCount - player.getRemainingCells());
ImGui.endChild();
ImGui.popStyleColor(3);
}
public void render() {
var displaySize = ImGui.getIO().getDisplaySize();
ImGui.setCursorPosX(displaySize.x / 2.0f - cellSize.x / 2.0f);
ImGui.beginChild("Leaderboard", new ImVec2(cellSize.x + 15.0f, cellHeight * maxPlayersShowed));
ImGui.pushStyleVar(ImGuiStyleVar.ItemSpacing, new ImVec2());
ImGui.pushStyleVar(ImGuiStyleVar.FrameBorderSize, 3.0f);
for (int i = 0; i < game.getLeaderboard().size(); i++) {
Player player = game.getLeaderboard().get(i);
renderCell(player, i + 1, player == currentPlayer ? cellColorPlayer : cellColorEnemy);
}
ImGui.popStyleVar(2);
ImGui.endChild();
}
}

View File

@@ -0,0 +1,28 @@
package gui.widget;
import game.Game;
import game.Player;
import imgui.ImGui;
import imgui.ImVec2;
public class MultiPlayerCompleteProgress {
private final Game game;
private final int emptyCellCount;
private final ImVec2 progressSize = new ImVec2(700, 50);
private final SmoothProgressBar progressBar;
public MultiPlayerCompleteProgress(Game game) {
this.game = game;
this.emptyCellCount = game.getDoku().getEmptyCells().size();
this.progressBar = new SmoothProgressBar();
}
public void render() {
Player firstPlayer = game.getLeaderboard().getFirst();
ImGui.setCursorPosX(ImGui.getIO().getDisplaySizeX() / 2.0f - progressSize.x / 2.0f);
String progressText = firstPlayer.getPseudo() + " - " + (emptyCellCount - firstPlayer.getRemainingCells()) + "/" + emptyCellCount;
this.progressBar.render(progressText, progressSize, 1.0f - firstPlayer.getRemainingCells() / (float) emptyCellCount);
}
}

View File

@@ -0,0 +1,30 @@
package gui.widget;
import imgui.ImGui;
import imgui.ImVec2;
public class SmoothProgressBar {
private float lastProgress = 0;
private final float speed = 2.0f;
private final float clipConstant = 0.001f;
private void updateProgress(float newProgress) {
float delta = newProgress - lastProgress;
if (Math.abs(delta) < clipConstant)
lastProgress = newProgress;
else
lastProgress = lastProgress + delta * ImGui.getIO().getDeltaTime() * speed;
}
public void render(String label, ImVec2 size, float progress) {
updateProgress(progress);
ImGui.progressBar(lastProgress, size, label);
}
public void render(float progress) {
updateProgress(progress);
ImGui.progressBar(lastProgress);
}
}

View File

@@ -0,0 +1,157 @@
package gui.widget;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import common.ConsumerSignal;
import common.Signal;
import gui.ColorGenerator;
import gui.ColorGenerator.Color;
import gui.RenderableMultidoku;
import gui.constants.Fonts;
import gui.constants.Options;
import gui.constants.Symbols;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.ImVec4;
import imgui.flag.ImGuiCol;
import imgui.flag.ImGuiStyleVar;
import sudoku.constraint.Constraint;
import sudoku.structure.Block;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
public class SudokuRenderer {
private final RenderableMultidoku doku;
private Cell currentCell = null;
private final Map<Block, Color> colorPalette;
private static final ImVec4 BLACK = new ImVec4(0, 0, 0, 1);
private static final ImVec4 TRANSPARENT = new ImVec4();
private static final ImVec4 WHITE = new ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
private static final ImVec2 cellSize = new ImVec2(50, 50);
private final Set<Cell> diagonals = new HashSet<>();
public final Signal onResolve = new Signal();
public final ConsumerSignal<Cell> onCellChange = new ConsumerSignal<>();
public SudokuRenderer(MultiDoku doku) {
this.doku = RenderableMultidoku.fromMultidoku(doku);
this.colorPalette = initColors();
initDiagonals();
}
private void initDiagonals() {
for (Sudoku sudoku : this.doku.getDoku().getSubGrids()) {
if (sudoku.hasConstraint(Constraint.Diagonal)) {
for (int i = 0; i < sudoku.getSize(); i++) {
this.diagonals.add(sudoku.getCell(i, i));
this.diagonals.add(sudoku.getCell(sudoku.getSize() - i - 1, i));
}
}
}
}
private Map<Block, Color> initColors() {
List<Color> colors = ColorGenerator.greatPalette(doku.getBlocks().size());
Map<Block, Color> colorPalette = new HashMap<>();
int index = 0;
for (Block block : doku.getBlocks()) {
colorPalette.put(block, colors.get(index));
index++;
}
return colorPalette;
}
private void renderPopup() {
if (ImGui.beginPopup("editPopup")) {
Block block = currentCell.getBlock();
int symbolCount = block.getCells().size();
for (int i = 0; i < symbolCount; i++) {
if ((i + 1) % (int) (Math.sqrt(symbolCount)) != 1)
ImGui.sameLine();
if (currentCell.getSymbolIndex() == i) {
if (ImGui.button("X", cellSize)) {
currentCell.setSymbolIndex(Cell.NOSYMBOL);
this.onCellChange.emit(currentCell);
ImGui.closeCurrentPopup();
}
} else {
if (ImGui.button(Options.Symboles.getSymbols().get(i), cellSize)) {
currentCell.setSymbolIndex(i);
this.onCellChange.emit(currentCell);
if (this.doku.getDoku().isSolved())
this.onResolve.emit();
ImGui.closeCurrentPopup();
}
}
}
ImGui.endPopup();
}
}
public void render() {
if (Options.Symboles == Symbols.Russian) {
ImGui.pushFont(Fonts.ARIAL);
}
final float sudokuViewWidth = cellSize.x * doku.getWidth();
final float displayWidth = ImGui.getIO().getDisplaySizeX();
float offsetX = displayWidth / 2.0f - sudokuViewWidth / 2.0f;
// if the grid is too big, don't offset it
if (offsetX > 0) {
ImGui.setCursorPosX(offsetX);
}
ImGui.beginChild("sudokuChild", new ImVec2(cellSize.x * doku.getWidth(), cellSize.y * doku.getHeight()));
ImGui.pushStyleVar(ImGuiStyleVar.FrameBorderSize, 2.0f);
ImGui.pushStyleVar(ImGuiStyleVar.ItemSpacing, new ImVec2(0.0f, 0.0f));
for (int y = 0; y < doku.getHeight(); y++) {
for (int x = 0; x < doku.getWidth(); x++) {
if (x > 0)
ImGui.sameLine();
int index = y * doku.getWidth() + x;
Cell cell = doku.getCell(x, y);
ImGui.beginDisabled(cell == null);
if (cell == null) {
ImGui.pushStyleColor(ImGuiCol.Border, TRANSPARENT);
ImGui.pushStyleColor(ImGuiCol.Button, TRANSPARENT);
ImGui.button("##" + index, cellSize);
} else {
if (diagonals.contains(cell)) {
ImGui.pushStyleColor(ImGuiCol.Border, WHITE);
} else {
ImGui.pushStyleColor(ImGuiCol.Border, BLACK);
}
int symbol = cell.getSymbolIndex();
Color blockColor = colorPalette.get(cell.getBlock());
if (!cell.isMutable()) {
blockColor = new Color(blockColor.r - 0.20f, blockColor.g - 0.20f, blockColor.b - 0.20f);
}
ImGui.pushStyleColor(ImGuiCol.Button, new ImVec4(blockColor.r, blockColor.g, blockColor.b, 1.0f));
String cellText = "";
if (symbol != -1)
cellText += Options.Symboles.getSymbols().get(symbol);
if (ImGui.button(cellText + "##" + index, cellSize) && cell.isMutable()) {
ImGui.openPopup("editPopup");
currentCell = cell;
}
}
ImGui.endDisabled();
ImGui.popStyleColor(2);
}
}
ImGui.popStyleVar(2);
renderPopup();
ImGui.endChild();
if (Options.Symboles == Symbols.Russian) {
ImGui.popFont();
}
}
}

View File

@@ -0,0 +1,176 @@
package gui.widget;
import java.util.ArrayList;
import java.util.List;
import common.ConsumerSignal;
import gui.constants.SudokuType;
import imgui.ImGui;
import imgui.extension.imguifiledialog.ImGuiFileDialog;
import imgui.extension.imguifiledialog.flag.ImGuiFileDialogFlags;
import imgui.type.ImBoolean;
import imgui.type.ImInt;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import sudoku.structure.Difficulty;
import sudoku.structure.MultiDoku;
import sudoku.structure.SudokuFactory;
public class SudokuSelector {
public final ConsumerSignal<MultiDoku> onSelect = new ConsumerSignal<>();
private MultiDoku doku;
private final boolean canGenEmptyGrid;
private final ImInt sudokuType = new ImInt(0);
private final ImInt difficulty = new ImInt(Difficulty.Easy.ordinal());
private final List<ImBoolean> contraints = new ArrayList<>();
private final ImInt sudokuSize = new ImInt(3);
private final ImInt sudokuWidth = new ImInt(3);
private final ImInt sudokuHeight = new ImInt(3);
private final String confirmMessage;
private Thread genThread = null;
private final SmoothProgressBar genProgressBar;
private volatile boolean genDone = false;
public SudokuSelector(boolean canGenEmptyGrid, String confirmMessage) {
this.canGenEmptyGrid = canGenEmptyGrid;
this.confirmMessage = confirmMessage;
initConstraints();
this.genProgressBar = new SmoothProgressBar();
}
private List<IConstraint> getConstraints() {
List<IConstraint> constraints = new ArrayList<>();
for (int i = 0; i < this.contraints.size(); i++) {
if (this.contraints.get(i).get())
constraints.add(Constraint.values()[i].getConstraint());
}
return constraints;
}
private void initConstraints() {
for (Constraint cons : Constraint.values()) {
contraints.add(new ImBoolean(SudokuFactory.DEFAULT_CONSTRAINTS.contains(cons.getConstraint())));
}
}
private void stopGenThread() {
if (this.genThread != null) {
this.genThread.interrupt();
this.genThread = null;
}
}
private void renderGenProgress() {
if (ImGui.beginPopup("genProgress")) {
ImGui.text("Chargement de la grille ...");
int filled = this.doku.getFilledCells().size();
int total = this.doku.getCells().size();
this.genProgressBar.render(filled / (float) total);
if (genDone)
ImGui.closeCurrentPopup();
ImGui.endPopup();
} else {
stopGenThread();
}
}
private void selectSudoku(MultiDoku doku, boolean empty) {
this.doku = doku;
this.genDone = false;
ImGui.openPopup("genProgress");
this.genThread = new Thread(() -> {
try {
if (!empty) {
SudokuFactory.fillDoku(doku, Difficulty.values()[difficulty.get()]);
}
this.genDone = true;
this.onSelect.emit(this.doku);
} catch (Exception e) {
e.printStackTrace();
}
});
this.genThread.start();
}
public void renderFileDialog() {
if (ImGuiFileDialog.display("browse-sudoku", ImGuiFileDialogFlags.None)) {
if (ImGuiFileDialog.isOk()) {
var selection = ImGuiFileDialog.getSelection();
for (var entry : selection.entrySet()) {
try {
String filePath = entry.getValue();
this.doku = SudokuFactory.fromfile(filePath);
if (this.doku != null)
this.onSelect.emit(this.doku);
} catch (Exception e) {
e.printStackTrace();
}
}
}
ImGuiFileDialog.close();
}
}
public void render() {
ImGui.combo("Difficulté", difficulty, Difficulty.getDifficultyNames());
if (ImGui.treeNode("Constraintes")) {
for (Constraint cons : Constraint.values()) {
ImGui.checkbox(cons.getDisplayName(), contraints.get(cons.ordinal()));
}
ImGui.treePop();
}
ImGui.combo("Type de Sudoku", sudokuType, SudokuType.getTypeNames());
SudokuType currentType = SudokuType.values()[sudokuType.get()];
switch (currentType.getMakerParamCount()) {
case 1:
if (ImGui.inputInt("Taille", sudokuSize))
sudokuSize.set(Math.clamp(sudokuSize.get(), 1, 10));
if (ImGui.button(confirmMessage)) {
selectSudoku(currentType.createDoku(getConstraints(), sudokuSize.get()), false);
}
if (canGenEmptyGrid && ImGui.button("Générer une grille vide")) {
selectSudoku(currentType.createDoku(getConstraints(), sudokuSize.get()), true);
}
break;
case 2:
if (ImGui.inputInt("Longueur", sudokuWidth))
sudokuWidth.set(Math.clamp(sudokuWidth.get(), 1, 10));
if (ImGui.inputInt("Hauteur", sudokuHeight))
sudokuHeight.set(Math.clamp(sudokuHeight.get(), 1, 10));
if (ImGui.button(confirmMessage)) {
selectSudoku(currentType.createDoku(getConstraints(), sudokuWidth.get(), sudokuHeight.get()),
false);
}
if (canGenEmptyGrid && ImGui.button("Générer une grille vide")) {
selectSudoku(currentType.createDoku(getConstraints(), sudokuWidth.get(), sudokuHeight.get()), true);
}
break;
default:
assert (false);
break;
}
if (ImGui.button("À partir d'un fichier")) {
ImGuiFileDialog.openDialog("browse-sudoku", "Choisissez un fichier", ".json", ".");
}
renderGenProgress();
renderFileDialog();
}
public void clean() {
stopGenThread();
}
}

View File

@@ -0,0 +1,29 @@
package gui.widget;
import java.time.Instant;
import imgui.ImGui;
public class TimerRenderer {
private final long endTime;
public TimerRenderer(Instant startTime, long duration) {
this.endTime = startTime.getEpochSecond() + duration;
}
private long getTimeRemaining() {
long currentTime = Instant.now().getEpochSecond();
return endTime - currentTime;
}
public void render() {
long seconds = getTimeRemaining();
long minutes = seconds / 60;
String text = String.format("%02d:%02d", minutes, seconds % 60);
var textSize = ImGui.calcTextSize(text);
ImGui.setCursorPosX(ImGui.getIO().getDisplaySizeX() / 2.0f - textSize.x / 2.0f);
ImGui.text(text);
}
}

View File

@@ -0,0 +1,54 @@
package network;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
public abstract class Connexion implements PacketVisitor {
protected final DatagramSocket socket;
protected final InetSocketAddress address;
public Connexion(DatagramSocket socket, InetSocketAddress address) {
this.socket = socket;
this.address = address;
}
public static record ReadInfo(Packet packet, InetSocketAddress address) {}
public static ReadInfo readPacket(final DatagramSocket socket)
throws IOException, ClassNotFoundException {
byte[] buffer = new byte[65535];
DatagramPacket dataPacket = new DatagramPacket(buffer, buffer.length);
socket.receive(dataPacket);
InetSocketAddress address = new InetSocketAddress(dataPacket.getAddress(), dataPacket.getPort());
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(dataPacket.getData()));
Packet packet = (Packet) ois.readObject();
return new ReadInfo(packet, address);
}
public void sendPacket(Packet packet) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(stream);
oos.writeObject(packet);
oos.flush();
byte[] data = stream.toByteArray();
DatagramPacket dataPacket = new DatagramPacket(data, data.length, this.address.getAddress(),
this.address.getPort());
this.socket.send(dataPacket);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,78 @@
package network.client;
import java.io.IOException;
import java.net.UnknownHostException;
import common.ConsumerSignal;
import common.Signal;
import game.Game;
import game.Player;
import network.protocol.packets.ChangeCellPacket;
import network.protocol.packets.LoginPacket;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
public class Client {
private final ClientConnexion clientConnection;
private final Game game;
public final Signal onConnect = new Signal();
public final Signal onDisconnect = new Signal();
public final Signal onClosed = new Signal();
public final Signal onGameStarted = new Signal();
public final ConsumerSignal<Player> onGameEnd = new ConsumerSignal<>();
Player player;
String disconnectReason = null;
public Client(String pseudo, String address, short port) throws UnknownHostException, IOException {
this.clientConnection = new ClientConnexion(address, port, this);
this.game = new Game();
login(pseudo);
}
public void login(String pseudo) {
System.out.println("Logging in with pseudo " + pseudo + " ...");
this.clientConnection.sendPacket(new LoginPacket(pseudo));
}
public void stop() {
this.clientConnection.close();
}
public void addPlayer(Player player) {
this.game.addPlayer(player);
}
public Game getGame() {
return game;
}
public String getDisconnectReason() {
return disconnectReason;
}
public void forceDisconnect() {
this.onClosed.emit();
stop();
}
public void sendCellChange(Cell cell) {
MultiDoku doku = getGame().getDoku();
for (int sudokuIndex = 0; sudokuIndex < doku.getNbSubGrids(); sudokuIndex++) {
Sudoku sudoku = doku.getSubGrid(sudokuIndex);
int cellIndex = sudoku.getCells().indexOf(cell);
if (cellIndex != -1) {
this.clientConnection.sendPacket(new ChangeCellPacket(sudokuIndex, cellIndex, cell.getSymbolIndex()));
return;
}
}
}
public Player getPlayer() {
return player;
}
}

View File

@@ -0,0 +1,118 @@
package network.client;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import game.Player;
import network.Connexion;
import network.protocol.Packet;
import network.protocol.packets.ChangeCellPacket;
import network.protocol.packets.ConnexionInfoPacket;
import network.protocol.packets.DisconnectPacket;
import network.protocol.packets.EndGamePacket;
import network.protocol.packets.KeepAlivePacket;
import network.protocol.packets.LoginPacket;
import network.protocol.packets.PlayerJoinPacket;
import network.protocol.packets.PlayerLeavePacket;
import network.protocol.packets.StartGamePacket;
import network.protocol.packets.UpdatePlayerScorePacket;
import sudoku.io.SudokuSerializer;
public class ClientConnexion extends Connexion {
private final Client client;
private final Thread readThread;
public ClientConnexion(String address, short port, Client client) throws UnknownHostException, IOException {
super(new DatagramSocket(), new InetSocketAddress(address, port));
this.client = client;
this.readThread = new Thread(this::readPackets);
this.readThread.start();
}
private void readPackets() {
while (!Thread.interrupted()) {
try {
Packet packet = Connexion.readPacket(this.socket).packet();
visit(packet);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public void close() {
if (!this.socket.isClosed()) {
sendPacket(new DisconnectPacket(""));
client.onDisconnect.emit();
this.readThread.interrupt();
this.socket.close();
}
}
@Override
public void visitPacket(ConnexionInfoPacket packet) {
this.client.player = this.client.getGame().getPlayerById(packet.getConnectionId());
client.onConnect.emit();
}
@Override
public void visitPacket(KeepAlivePacket packet) {
// we just send the packet back to the server
sendPacket(packet);
}
@Override
public void visitPacket(DisconnectPacket packet) {
this.client.disconnectReason = packet.getReason();
close();
}
@Override
public void visitPacket(LoginPacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketLogin'");
}
@Override
public void visitPacket(PlayerJoinPacket packet) {
this.client.addPlayer(packet.getPlayer());
System.out.println("[Client] " + packet.getPlayer().getPseudo() + " joined the game !");
}
@Override
public void visitPacket(PlayerLeavePacket packet) {
this.client.getGame().removePlayer(packet.getPlayer());
}
@Override
public void visitPacket(StartGamePacket packet) {
this.client.getGame().startGame(SudokuSerializer.deserializeSudoku(packet.getSerializedSudoku()),
packet.getInstant(), packet.getGameDuration());
this.client.onGameStarted.emit();
}
@Override
public void visitPacket(EndGamePacket packet) {
Player winner = this.client.getGame().getLeaderboard().getFirst();
this.client.getGame().stopGame();
this.client.onGameEnd.emit(winner);
}
@Override
public void visitPacket(UpdatePlayerScorePacket packet) {
Player player = this.client.getGame().getPlayerById(packet.getPlayerId());
assert (player != null);
this.client.getGame().setPlayerRemainingCells(player, packet.getCellsLeft());
}
@Override
public void visitPacket(ChangeCellPacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketChangeCell'");
}
}

View File

@@ -0,0 +1,11 @@
package network.protocol;
import java.io.Serializable;
public abstract class Packet implements Serializable {
// public abstract int getId();
public abstract void accept(PacketVisitor packetVisitor);
}

View File

@@ -0,0 +1,31 @@
package network.protocol;
import network.protocol.packets.ChangeCellPacket;
import network.protocol.packets.ConnexionInfoPacket;
import network.protocol.packets.DisconnectPacket;
import network.protocol.packets.EndGamePacket;
import network.protocol.packets.KeepAlivePacket;
import network.protocol.packets.LoginPacket;
import network.protocol.packets.PlayerJoinPacket;
import network.protocol.packets.PlayerLeavePacket;
import network.protocol.packets.StartGamePacket;
import network.protocol.packets.UpdatePlayerScorePacket;
public interface PacketVisitor {
default void visit(Packet packet) {
packet.accept(this);
}
void visitPacket(ConnexionInfoPacket packet);
void visitPacket(DisconnectPacket packet);
void visitPacket(KeepAlivePacket packet);
void visitPacket(LoginPacket packet);
void visitPacket(PlayerJoinPacket packet);
void visitPacket(PlayerLeavePacket packet);
void visitPacket(StartGamePacket packet);
void visitPacket(EndGamePacket packet);
void visitPacket(UpdatePlayerScorePacket packet);
void visitPacket(ChangeCellPacket packet);
}

View File

@@ -0,0 +1,7 @@
package network.protocol;
public enum Packets {
ConnectionInfo, KeepAlive, Disconnect, Login, PlayerJoin, PlayerLeave, StartGame, ChangeCell, EndGame, UpdatePlayerScore
}

View File

@@ -0,0 +1,38 @@
package network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
public class ChangeCellPacket extends Packet {
static private final long serialVersionUID = Packets.ChangeCell.ordinal();
private final int sudokuIndex;
private final int cellIndex;
private final int newValue;
public ChangeCellPacket(int sudokuIndex, int cellIndex, int newValue) {
this.sudokuIndex = sudokuIndex;
this.cellIndex = cellIndex;
this.newValue = newValue;
}
public int getSudokuIndex() {
return sudokuIndex;
}
public int getCellIndex() {
return cellIndex;
}
public int getNewValue() {
return newValue;
}
@Override
public void accept(PacketVisitor packetVisitor) {
packetVisitor.visitPacket(this);
}
}

View File

@@ -0,0 +1,25 @@
package network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
public class ConnexionInfoPacket extends Packet {
static private final long serialVersionUID = Packets.ConnectionInfo.ordinal();
private final int connectionId;
public ConnexionInfoPacket(int connectionId) {
this.connectionId = connectionId;
}
public int getConnectionId() {
return connectionId;
}
@Override
public void accept(PacketVisitor packetVisitor) {
packetVisitor.visitPacket(this);
}
}

View File

@@ -0,0 +1,26 @@
package network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
public class DisconnectPacket extends Packet {
static private final long serialVersionUID = Packets.Disconnect.ordinal();
private final String reason;
public DisconnectPacket(String reason) {
this.reason = reason;
}
public String getReason() {
return reason;
}
@Override
public void accept(PacketVisitor packetVisitor) {
packetVisitor.visitPacket(this);
}
}

View File

@@ -0,0 +1,18 @@
package network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
public class EndGamePacket extends Packet {
static private final long serialVersionUID = Packets.EndGame.ordinal();
public EndGamePacket() { }
@Override
public void accept(PacketVisitor packetVisitor) {
packetVisitor.visitPacket(this);
}
}

View File

@@ -0,0 +1,26 @@
package network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
public class KeepAlivePacket extends Packet {
static private final long serialVersionUID = Packets.KeepAlive.ordinal();
private final long keepAliveId;
public KeepAlivePacket(long keepAliveId) {
this.keepAliveId = keepAliveId;
}
public long getKeepAliveId() {
return keepAliveId;
}
@Override
public void accept(PacketVisitor packetVisitor) {
packetVisitor.visitPacket(this);
}
}

View File

@@ -0,0 +1,26 @@
package network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
public class LoginPacket extends Packet {
static private final long serialVersionUID = Packets.Login.ordinal();
private final String pseudo;
public LoginPacket(String pseudo) {
this.pseudo = pseudo;
}
public String getPseudo() {
return pseudo;
}
@Override
public void accept(PacketVisitor packetVisitor) {
packetVisitor.visitPacket(this);
}
}

View File

@@ -0,0 +1,29 @@
package network.protocol.packets;
import game.Player;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
public class PlayerJoinPacket extends Packet{
static private final long serialVersionUID = Packets.PlayerJoin.ordinal();
private final Player player;
public PlayerJoinPacket(Player player) {
this.player = player;
}
public Player getPlayer() {
return player;
}
@Override
public void accept(PacketVisitor packetVisitor) {
packetVisitor.visitPacket(this);
}
}

View File

@@ -0,0 +1,28 @@
package network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
public class PlayerLeavePacket extends Packet{
static private final long serialVersionUID = Packets.PlayerLeave.ordinal();
private final int playerId;
public PlayerLeavePacket(int playerId) {
this.playerId = playerId;
}
public int getPlayer() {
return playerId;
}
@Override
public void accept(PacketVisitor packetVisitor) {
packetVisitor.visitPacket(this);
}
}

View File

@@ -0,0 +1,41 @@
package network.protocol.packets;
import java.time.Instant;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
public class StartGamePacket extends Packet {
static private final long serialVersionUID = Packets.StartGame.ordinal();
private final String serializedSudoku;
// used to resume game
private final Instant instant;
private final long gameDuration;
public StartGamePacket(String serializedSudoku, Instant instant, long gameDuration) {
this.serializedSudoku = serializedSudoku;
this.instant = instant;
this.gameDuration = gameDuration;
}
public String getSerializedSudoku() {
return serializedSudoku;
}
public Instant getInstant() {
return instant;
}
public long getGameDuration() {
return gameDuration;
}
@Override
public void accept(PacketVisitor packetVisitor) {
packetVisitor.visitPacket(this);
}
}

View File

@@ -0,0 +1,32 @@
package network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
public class UpdatePlayerScorePacket extends Packet {
static private final long serialVersionUID = Packets.UpdatePlayerScore.ordinal();
private final int playerId;
private final int cellsLeft;
public UpdatePlayerScorePacket(int playerId, int cellsLeft) {
this.playerId = playerId;
this.cellsLeft = cellsLeft;
}
public int getPlayerId() {
return playerId;
}
public int getCellsLeft() {
return cellsLeft;
}
@Override
public void accept(PacketVisitor packetVisitor) {
packetVisitor.visitPacket(this);
}
}

View File

@@ -0,0 +1,49 @@
package network.server;
import java.util.Random;
import network.protocol.packets.KeepAlivePacket;
public class KeepAliveHandler {
private final ServerConnexion serverConnexion;
private static final int KEEP_ALIVE_COOLDOWN = 5 * 1000;
private long lastKeepAlive = 0;
private long lastSend = 0;
private volatile boolean keepAliveRecieved = false;
public KeepAliveHandler(ServerConnexion serverConnexion) {
this.serverConnexion = serverConnexion;
sendKeepAlive();
}
public boolean update() {
var currentTime = System.currentTimeMillis();
if (currentTime - lastSend > KEEP_ALIVE_COOLDOWN) {
if (keepAliveRecieved) {
sendKeepAlive();
} else {
System.out.println("Zombie");
serverConnexion.close();
return false;
}
}
return true;
}
public void recievedKeepAlive(long keepAliveId) {
if (lastKeepAlive == keepAliveId)
this.keepAliveRecieved = true;
}
private void sendKeepAlive() {
Random r = new Random();
lastKeepAlive = r.nextLong();
lastSend = System.currentTimeMillis();
keepAliveRecieved = false;
this.serverConnexion.sendPacket(new KeepAlivePacket(lastKeepAlive));
}
}

View File

@@ -0,0 +1,105 @@
package network.server;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import game.Game;
import game.Game.GameState;
import game.Player;
import network.protocol.Packet;
import network.protocol.packets.EndGamePacket;
import network.protocol.packets.StartGamePacket;
import sudoku.io.SudokuSerializer;
import sudoku.structure.MultiDoku;
public class Server {
final DatagramSocket serverSocket;
final Map<InetSocketAddress, ServerConnexion> connexions;
private final ServerReadThread acceptThread;
private final ServerLogicThread logicThread;
private final Game game;
private int nextPlayerId = 0;
public Server(short port) throws IOException {
this.serverSocket = new DatagramSocket(port);
this.connexions = new HashMap<>();
this.acceptThread = new ServerReadThread(this);
this.acceptThread.start();
this.logicThread = new ServerLogicThread(this);
this.logicThread.start();
this.game = new Game();
}
public void broadcastPacket(Packet packet) {
for (ServerConnexion connexion : this.connexions.values()) {
connexion.sendPacket(packet);
}
}
private void checkTimer() {
if (getGame() == null || getGame().getGameState() != GameState.GameGoing)
return;
long now = Instant.now().getEpochSecond();
long end = getGame().getStartTime().getEpochSecond() + getGame().getGameDuration();
if (now > end)
stopGame();
}
private void checkConnexions() {
for (var it = connexions.entrySet().iterator(); it.hasNext();) {
var entry = it.next();
ServerConnexion connexion = entry.getValue();
if (!connexion.update()) {
connexion.close();
connexion.nukeConnection();
it.remove();
}
}
}
public void update() {
checkTimer();
checkConnexions();
}
public void stop() {
this.acceptThread.cancel();
this.logicThread.cancel();
for (ServerConnexion connexion : this.connexions.values()) {
connexion.nukeConnection();
}
this.serverSocket.close();
}
public Player addPlayer(String pseudo) {
Player p = new Player(nextPlayerId, pseudo);
this.game.addPlayer(p);
nextPlayerId++;
return p;
}
public Game getGame() {
return game;
}
public void startGame(MultiDoku doku, long gameDuration) {
Instant now = Instant.now();
this.game.startGame(doku, now, gameDuration);
for (ServerConnexion connexion : this.connexions.values()) {
connexion.setSudoku(doku.clone());
}
broadcastPacket(new StartGamePacket(SudokuSerializer.serializeSudoku(doku).toString(), now, gameDuration));
}
public void stopGame() {
// we don't need to specify the winner since it has to be the first
broadcastPacket(new EndGamePacket());
getGame().stopGame();
}
}

View File

@@ -0,0 +1,162 @@
package network.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import game.Game;
import game.Game.GameState;
import game.Player;
import network.Connexion;
import network.protocol.packets.ChangeCellPacket;
import network.protocol.packets.ConnexionInfoPacket;
import network.protocol.packets.DisconnectPacket;
import network.protocol.packets.EndGamePacket;
import network.protocol.packets.KeepAlivePacket;
import network.protocol.packets.LoginPacket;
import network.protocol.packets.PlayerJoinPacket;
import network.protocol.packets.PlayerLeavePacket;
import network.protocol.packets.StartGamePacket;
import network.protocol.packets.UpdatePlayerScorePacket;
import sudoku.io.SudokuSerializer;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
public class ServerConnexion extends Connexion {
private final Server server;
private final KeepAliveHandler keepAliveHandler;
private boolean shouldClose = false;
private Player player = null;
private MultiDoku doku;
public ServerConnexion(InetSocketAddress remoteAddress, Server server) throws IOException {
super(server.serverSocket, remoteAddress);
this.server = server;
this.keepAliveHandler = new KeepAliveHandler(this);
}
public boolean update() {
if (shouldClose)
return false;
return this.keepAliveHandler.update();
}
public void nukeConnection() {
if (player != null) {
sendPacket(new DisconnectPacket("Le serveur a été fermé !"));
this.server.broadcastPacket(new PlayerLeavePacket(player.getId()));
this.server.getGame().removePlayer(player.getId());
}
}
private void finishLogin() {
// send players that have already joined (excluding this one)
for (Player p : this.server.getGame().getPlayers().values()) {
if (p.getId() != player.getId()) {
sendPacket(new PlayerJoinPacket(p));
sendPacket(new UpdatePlayerScorePacket(p.getId(), p.getRemainingCells()));
}
}
this.server.broadcastPacket(new PlayerJoinPacket(player));
sendPacket(new ConnexionInfoPacket(player.getId()));
Game game = this.server.getGame();
if (game.getGameState() == GameState.GameGoing) {
setSudoku(game.getDoku().clone());
sendPacket(
new StartGamePacket(SudokuSerializer.serializeSudoku(game.getDoku()).toString(),
game.getStartTime(), game.getGameDuration()));
}
}
@Override
public void visitPacket(KeepAlivePacket packet) {
this.keepAliveHandler.recievedKeepAlive(packet.getKeepAliveId());
}
@Override
public void visitPacket(DisconnectPacket packet) {
//TODO: close connexion
}
@Override
public void visitPacket(LoginPacket packet) {
if (this.player != null)
return;
this.player = this.server.addPlayer(packet.getPseudo());
finishLogin();
}
@Override
public void visitPacket(ConnexionInfoPacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketConnexionInfo'");
}
@Override
public void visitPacket(PlayerJoinPacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketPlayerJoin'");
}
@Override
public void visitPacket(PlayerLeavePacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketPlayerLeave'");
}
@Override
public void visitPacket(StartGamePacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketStartGame'");
}
@Override
public void visitPacket(EndGamePacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacket'");
}
@Override
public void visitPacket(UpdatePlayerScorePacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacket'");
}
@Override
public void visitPacket(ChangeCellPacket packet) {
Cell cell = this.doku.getSubGrid(packet.getSudokuIndex()).getCell(packet.getCellIndex());
if (cell.getSymbolIndex() == Cell.NOSYMBOL && packet.getNewValue() == Cell.NOSYMBOL)
return;
if (cell.getSymbolIndex() != Cell.NOSYMBOL && packet.getNewValue() != Cell.NOSYMBOL) {
cell.trySetValue(packet.getNewValue());
return;
}
if (cell.getSymbolIndex() != Cell.NOSYMBOL && packet.getNewValue() == Cell.NOSYMBOL) {
cell.empty();
this.server.getGame().setPlayerRemainingCells(player, player.getRemainingCells() + 1);
this.server.broadcastPacket(new UpdatePlayerScorePacket(player.getId(), player.getRemainingCells()));
return;
}
// on rajoute un chiffre à la grille
if (cell.trySetValue(packet.getNewValue())) {
this.server.getGame().setPlayerRemainingCells(player, player.getRemainingCells() - 1);
this.server.broadcastPacket(new UpdatePlayerScorePacket(player.getId(), player.getRemainingCells()));
}
checkWin();
}
private void checkWin() {
if (this.player.getRemainingCells() == 0) {
this.server.stopGame();
}
}
public void setSudoku(MultiDoku doku) {
this.doku = doku;
assert (player != null);
this.server.getGame().setPlayerRemainingCells(player, this.doku.getEmptyCells().size());
this.server.broadcastPacket(new UpdatePlayerScorePacket(player.getId(), player.getRemainingCells()));
}
public void close() {
this.shouldClose = true;
}
}

View File

@@ -0,0 +1,28 @@
package network.server;
public class ServerLogicThread extends Thread {
private final Server server;
public ServerLogicThread(Server server) {
this.server = server;
}
public void cancel() {
interrupt();
}
@Override
public void run() {
while (!interrupted()) {
server.update();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}
}

View File

@@ -0,0 +1,43 @@
package network.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import network.Connexion;
import network.protocol.Packet;
public class ServerReadThread extends Thread {
private final Server server;
public ServerReadThread(Server server) {
this.server = server;
}
public void cancel() {
this.server.serverSocket.close();
interrupt();
}
@Override
public void run() {
try {
while (!interrupted()) {
Connexion.ReadInfo read = Connexion.readPacket(this.server.serverSocket);
Packet packet = read.packet();
InetSocketAddress address = read.address();
if (!this.server.connexions.containsKey(address)) {
this.server.connexions.put(address, new ServerConnexion(address, server));
}
this.server.connexions.get(address).visit(packet);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

View File

@@ -1,34 +0,0 @@
package sudoku;
import java.util.ArrayList;
import java.util.List;
public class Block {
private final List<Cell> cells;
public Block(List<Cell> cells) {
this.cells = cells;
}
public Block() {
this.cells = new ArrayList<>();
}
public List<Cell> getCells() {
return cells;
}
void addCell(Cell newCell) {
this.cells.add(newCell);
}
public boolean containsSymbol(int symbolIndex) {
for (Cell cell : getCells()) {
if (cell.getSymbolIndex() == symbolIndex)
return true;
}
return false;
}
}

View File

@@ -1,94 +0,0 @@
package sudoku;
import org.checkerframework.checker.units.qual.C;
import java.util.ArrayList;
import java.util.List;
public abstract class Cell {
protected static int NOSYMBOL = -1;
protected int symbolIndex;
protected Block block = null;
//protected List<Block> blockContainers = null;
//protected List<Sudoku> sudokuContainers = null;
public Cell(int symbolIndex) {
this.symbolIndex = symbolIndex;
}
/**
* @brief Default constructor, empty square
*/
public Cell() {
this(NOSYMBOL);
}
/*
public Cell(Cell cell) {
this.symbolIndex = cell.symbolIndex;
this.sudokuContainers = cell.sudokuContainers;
this.blockContainers = cell.blockContainers;
}
public Cell(List<Sudoku> sudokuContainers, List<Block> blockContainers) {
super();
this.sudokuContainers = new ArrayList<>(sudokuContainers);
this.blockContainers = new ArrayList<>(blockContainers);
}
*/
public int getSymbolIndex() {
return symbolIndex;
}
public Block getBlock() {
return this.block;
}
/*
public List<Block> getBlockContainers() {
return this.blockContainers;
}
public void setBlockContainers(List<Block> block) {
this.blockContainers = block;
}
public List<Sudoku> getSudokuContainers() {
return this.sudokuContainers;
}
*/
// only SudokuFactory and SudokuSerializer should access this
public void setBlock(Block block) {
this.block = block;
}
/*
public void setSudokuContainers(List<Sudoku> sudoku) {
this.sudokuContainers = sudoku;
}
*/
public boolean equalsValue(Cell otherCell) {
return otherCell.getSymbolIndex() == this.getSymbolIndex();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("| ");
if (this.symbolIndex != NOSYMBOL){
sb.append(this.symbolIndex);
}
else {
sb.append(" ");
}
sb.append(" |");
return sb.toString();
}
}

View File

@@ -1,33 +0,0 @@
package sudoku;
public class Coordinate {
private int x;
private int y;
public Coordinate(int row, int col) {
this.x = row;
this.y = col;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int calculateIndex(int size) {
return this.y * size + this.x;
}
}

View File

@@ -1,9 +0,0 @@
package sudoku;
public class ImmutableCell extends Cell {
public ImmutableCell(int symbolIndex) {
super(symbolIndex);
}
}

View File

@@ -3,52 +3,48 @@
*/
package sudoku;
import sudoku.constraint.BlockConstraint;
import sudoku.constraint.ColumnConstraint;
import sudoku.constraint.IConstraint;
import sudoku.constraint.LineConstraint;
import gui.RenderableMultidoku;
import gui.constants.Symbols;
import sudoku.io.ConsoleInterface;
import sudoku.io.SudokuPrinter;
import sudoku.io.SudokuSerializer;
import sudoku.solver.Solver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import sudoku.solver.RandomSolver;
import sudoku.structure.MultiDoku;
import sudoku.structure.SudokuFactory;
public class Main {
public String getGreeting() {
return "Hello World!";
}
public static void voidTest(){
MultiDoku md = SudokuFactory.createBasicXShapedMultidoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
SudokuPrinter.printMultiDoku(RenderableMultidoku.fromMultidoku(md), Symbols.Numbers, 3, 3);
SudokuSerializer.saveMultiDoku(md);
}
public static void filledTest(){
MultiDoku md = SudokuFactory.createBasicXShapedMultidoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
new RandomSolver().solve(md);
SudokuPrinter.printMultiDoku(RenderableMultidoku.fromMultidoku(md), Symbols.Numbers, 3, 3);
SudokuSerializer.saveMultiDoku(md);
}
public static void overwriteTest(int n){
MultiDoku md = SudokuFactory.createBasicXShapedMultidoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
new RandomSolver().solve(md);
SudokuPrinter.printMultiDoku(RenderableMultidoku.fromMultidoku(md), Symbols.Numbers, 3, 3);
SudokuSerializer.saveMultiDoku(md, n);
}
public static void main(String[] args) {
System.out.println(new Main().getGreeting());
int blockWidth = 2;
int blockHeight = 2;
var multidoku = SudokuFactory.createBasicEmptyRectangleSudoku(blockWidth, blockHeight);
var sudoku = multidoku.getSubGrid(0);
if(!sudoku.setCellsSymbol(Arrays.asList(0,1,2,3, 2,3,1,1, 1,0,3,2, 3,2,1,1))){
System.out.println("At least one of those values does not respect the constraints.");
}
//sudoku.setCellSymbol(8,3,0);
SudokuPrinter.printRectangleSudoku(multidoku.getSubGrid(0), blockWidth , blockHeight);
ConsoleInterface console = new ConsoleInterface();
/*
Solver solver = new Solver();
ArrayList<IConstraint> constraints = new ArrayList<>();
constraints.add(new LineConstraint());
constraints.add(new ColumnConstraint());
constraints.add(new BlockConstraint());
try {
solver.solve(multidoku, constraints);
} catch (Exception e) {
System.out.println(e);
}
voidTest();
filledTest();
overwriteTest(0);
overwriteTest(17)
*/
console.welcome();
}
}

View File

@@ -1,53 +0,0 @@
package sudoku;
import sudoku.constraint.IConstraint;
import java.util.ArrayList;
import java.util.List;
/**
* @class MultiDoku
* @brief Représente une grille de Multidoku.
* Une grille de sudoku est un multidoku avec un seul sous-sudoku
*/
public class MultiDoku {
private final List<Sudoku> subGrids;
public MultiDoku(List<Sudoku> subGrids) {
this.subGrids = subGrids;
}
public int getNbSubGrids(){
return subGrids.size();
}
public Sudoku getSubGrid(int i){
return subGrids.get(i);
}
public List<MutableCell> getMutableCells(){
List<MutableCell> mutableCells = new ArrayList<>();
for (Sudoku sudoku : subGrids){
mutableCells.addAll(sudoku.getMutableCells());
}
return mutableCells;
}
public void updateSymbolsPossibilities() throws Exception {
for (Sudoku sudoku : subGrids){
sudoku.updateSymbolsPossibilities();
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Multidoku {");
for (Sudoku sudoku : subGrids){
sb.append("\n\t").append(sudoku.toString());
}
sb.append("\n}");
return sb.toString();
}
}

View File

@@ -1,47 +0,0 @@
package sudoku;
import java.util.ArrayList;
import java.util.List;
public class MutableCell extends Cell{
private final List<Integer> possibleSymbols;
public MutableCell() {
super();
this.possibleSymbols = new ArrayList<>();
}
public MutableCell(int symbolIndex) {
super(symbolIndex);
this.possibleSymbols = new ArrayList<>();
}
public void setSymbolIndex(int symbolIndex) {
this.symbolIndex = symbolIndex;
}
public void setPossibleSymbols(List<Integer> possibleSymbols) {
this.possibleSymbols.clear();
this.possibleSymbols.addAll(possibleSymbols);
}
/**
* Remove the current symbolIndex and returns it
* @return integer symbolIndex cleared
*/
public int clearCurrentSymbol() {
int i = this.symbolIndex;
setSymbolIndex(NOSYMBOL);
return i;
}
public void removeSymbolFromPossibilities(int indexSymbol) {
possibleSymbols.remove(indexSymbol);
}
public List<Integer> getPossibleSymbols() {
return this.possibleSymbols;
}
}

View File

@@ -1,165 +0,0 @@
package sudoku;
import sudoku.constraint.IConstraint;
import java.util.ArrayList;
import java.util.List;
/**
* @class Sudoku
* @brief Represents a sudoku
*/
public class Sudoku {
private final List<Block> blocks;
private final List<Cell> cells;
private final List<IConstraint> constraints;
public Sudoku(List<Cell> cells, List<Block> blocks, List<IConstraint> constraints) {
this.cells = cells;
this.blocks = blocks;
this.constraints = constraints;
}
/**
* @return wether the coords are in the sudoku
*/
public boolean isValidCoords(int x, int y) {
int index = y * getSize() + x;
return index < getSize() * getSize();
}
/**
* Try to place a cell at the given coordinate
*
* @return false if it can't be done
*/
public boolean setCellSymbol(int x, int y, int value) {
assert (isValidCoords(x, y));
for (IConstraint constraint : this.constraints) {
if (!constraint.canBePlaced(this, x, y, value)) {
return false;
}
}
Cell cell = getCell(x, y);
if (cell instanceof MutableCell mCell) {
mCell.setSymbolIndex(value);
return true;
}
return false;
}
public boolean setCellsSymbol(List<Integer> values) {
if (values.size() > this.cells.size()) {
return false;
}
for (int i = 0; i < values.size(); i++) {
int x = i%this.blocks.size();
int y = (i-x)/this.blocks.size();
int value = values.get(i);
if (!this.setCellSymbol(x, y, value)) {
return false;
}
}
return true;
}
public Cell getCell(int x, int y) {
int index = y * getSize() + x;
assert (isValidCoords(x, y));
return this.cells.get(index);
}
public Cell getCell(int i) {
return this.cells.get(i);
}
public List<IConstraint> getConstraints() {
return constraints;
}
public int getSize() {
return this.blocks.size();
}
public List<Cell> getCells() {
return this.cells;
}
public List<Block> getBlocks() {
return this.blocks;
}
public List<MutableCell> getMutableCells() {
List<MutableCell> mutableCells = new ArrayList<>();
for (Cell cell : this.cells) {
if (cell instanceof MutableCell) {
mutableCells.add((MutableCell) cell);
}
}
return mutableCells;
}
public boolean contains(Cell cell) {
return this.cells.contains(cell);
}
private Coordinate getCoordinateCell(Cell c) throws Exception {
int x = 0, y = 0;
int size = this.getSize();
if (!this.contains(c)) {
throw new Exception("The given cell is not in this sudoku.");
}
for (Cell cell : this.cells) {
if (cell == c) {
return new Coordinate(x, y);
}
if (x == size - 1) {
y += 1;
x = 0;
} else {
x += 1;
}
}
return new Coordinate(x, y);
}
public void updateSymbolsPossibilities() throws Exception {
for (IConstraint constraint : constraints) {
List<MutableCell> mutableCells = this.getMutableCells();
for (MutableCell cell : mutableCells) {
Coordinate coord = null;
try {
coord = this.getCoordinateCell(cell);
} catch (Exception e) {
throw new RuntimeException(e);
}
List<Integer> newPossibleSymbols = cell.getPossibleSymbols();
newPossibleSymbols.retainAll(constraint.getPossibleSymbols(this, coord.getX(), coord.getY()));
cell.setPossibleSymbols(newPossibleSymbols);
if (cell.getPossibleSymbols().isEmpty()) {
throw new Exception("Rollback bitch");
}
}
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Sudoku {");
for (int i = 0; i < getSize(); i++) {
sb.append("\n\t");
for (int j = 0; j < getSize(); j++) {
Cell cell = getCell(i, j);
sb.append(cell.toString()).append(" ");
}
}
sb.append("\n}");
return sb.toString();
}
}

View File

@@ -1,62 +0,0 @@
package sudoku;
import sudoku.constraint.BlockConstraint;
import sudoku.constraint.ColumnConstraint;
import sudoku.constraint.IConstraint;
import sudoku.constraint.LineConstraint;
import java.util.ArrayList;
import java.util.List;
public class SudokuFactory {
private static List<Cell> initCells(int size) {
List<Cell> cells = new ArrayList<>(size * size);
for (int i = 0; i < size * size; i++) {
cells.add(new MutableCell());
}
return cells;
}
private static List<Block> initRectangleBlocs(List<Cell> cells, int width, int height) {
List<Block> blocs = new ArrayList<>();
int size = width * height;
for (int i = 0; i < size; i++) {
Block newBlock = new Block();
int blockX = i % height;
int blockY = i / height;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int index = ((y + blockY * height) * size + (x + blockX * width));
Cell blockCell = cells.get(index);
blockCell.setBlock(newBlock);
// List<Block> blockContainers = new ArrayList<>();
// blockContainers.add(newBlock);
// blockCell.setBlockContainers(blockContainers);
newBlock.addCell(blockCell);
}
}
blocs.add(newBlock);
}
return blocs;
}
public static MultiDoku createBasicEmptyRectangleSudoku(int widthBlock, int heightBlock) {
int symbolCount = widthBlock * heightBlock;
List<Cell> cases = initCells(symbolCount);
List<Block> blocs = initRectangleBlocs(cases, widthBlock, heightBlock);
List<IConstraint> constraints = new ArrayList<>();
constraints.add(new ColumnConstraint());
constraints.add(new LineConstraint());
constraints.add(new BlockConstraint());
Sudoku s = new Sudoku(cases, blocs, constraints);
List<Sudoku> subSudoku = new ArrayList<>();
subSudoku.add(s);
return new MultiDoku(subSudoku);
}
public static MultiDoku createBasicEmptySquareSudoku(int size) {
return createBasicEmptyRectangleSudoku(size, size);
}
}

View File

@@ -1,14 +1,17 @@
package sudoku.constraint;
import sudoku.Block;
import sudoku.Sudoku;
import sudoku.structure.Block;
import sudoku.structure.Sudoku;
/**
* Contrainte de bloc
*/
public class BlockConstraint implements IConstraint{
@Override
public boolean canBePlaced(final Sudoku s, int x, int y, int newSymbolIndex) {
Block bloc = s.getCell(x, y).getBlock();
return !bloc.containsSymbol(newSymbolIndex);
Block block = s.getCell(x, y).getBlock();
return !block.containsSymbol(newSymbolIndex);
}
}

View File

@@ -1,16 +1,22 @@
package sudoku.constraint;
import sudoku.Sudoku;
import sudoku.structure.Cell;
import sudoku.structure.Sudoku;
/**
* Contrainte de colonne
*/
public class ColumnConstraint implements IConstraint {
@Override
public boolean canBePlaced(final Sudoku s, int x, int y, int newSymbolIndex) {
for (int i = 0; i < s.getSize(); i++) {
if (s.getCell(x, newSymbolIndex).getSymbolIndex() == newSymbolIndex)
Cell cell = s.getCell(x, i);
int symbol = cell.getSymbolIndex();
if (symbol == newSymbolIndex) {
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,40 @@
package sudoku.constraint;
/**
* Enumération utilisée afin de simplifier l'affichage en graphique.
* Un sudoku peut tout de même contenir des contraintes qui ne sont pas dans cette énumération.
*/
public enum Constraint {
Block("Bloc", new BlockConstraint()),
Column("Colonne", new ColumnConstraint()),
Line("Ligne", new LineConstraint()),
Diagonal("Diagonale", new DiagonalConstraint());
String displayName;
IConstraint constraint;
private Constraint(String displayName, IConstraint contraint) {
this.constraint = contraint;
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
public IConstraint getConstraint() {
return constraint;
}
private static final String[] constraintNames;
static {
Constraint[] cons = Constraint.values();
constraintNames = new String[cons.length];
for (int i = 0; i < cons.length; i++) {
constraintNames[i] = cons[i].getDisplayName();
}
}
}

View File

@@ -0,0 +1,27 @@
package sudoku.constraint;
import sudoku.structure.Sudoku;
/**
* Contrainte de diagonale
*/
public class DiagonalConstraint implements IConstraint {
@Override
public boolean canBePlaced(Sudoku s, int x, int y, int newSymbolIndex) {
if (x == y) {
for (int i = 0; i < s.getSize(); i++) {
if (s.getCell(i, i).getSymbolIndex() == newSymbolIndex)
return false;
}
} else if (s.getSize() - x == y) {
for (int i = 0; i < s.getSize(); i++) {
if (s.getCell(s.getSize() - i - 1, i).getSymbolIndex() == newSymbolIndex)
return false;
}
}
// not in diagonal
return true;
}
}

View File

@@ -1,22 +1,12 @@
package sudoku.constraint;
import java.util.ArrayList;
import java.util.List;
import sudoku.Sudoku;
import sudoku.structure.Sudoku;
/**
* Interface de base pour la déclaration d'une contrainte
* Elle est en théorie assez générique pour implémenter n'importe quelle
* contrainte
*/
public interface IConstraint {
boolean canBePlaced(final Sudoku s, int x, int y, int newSymbolIndex);
default List<Integer> getPossibleSymbols(final Sudoku s, int x, int y) {
List<Integer> possibilities = new ArrayList<>();
for (int i = 0; i < s.getSize(); i++) {
if (canBePlaced(s, x, y, i)) {
possibilities.add(i);
}
}
return possibilities;
}
}

View File

@@ -1,13 +1,16 @@
package sudoku.constraint;
import sudoku.Sudoku;
import sudoku.structure.Sudoku;
/**
* Contrainte de ligne
*/
public class LineConstraint implements IConstraint {
@Override
public boolean canBePlaced(final Sudoku s, int x, int y, int newSymbolIndex) {
for (int i = 0; i < s.getSize(); i++) {
if (s.getCell(newSymbolIndex, y).getSymbolIndex() == newSymbolIndex)
if (s.getCell(i, y).getSymbolIndex() == newSymbolIndex)
return false;
}
return true;

View File

@@ -0,0 +1,535 @@
package sudoku.io;
import gui.RenderableMultidoku;
import gui.constants.Symbols;
import sudoku.constraint.*;
import sudoku.solver.*;
import sudoku.structure.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ConsoleInterface {
private final Scanner reader = new Scanner(System.in);
/**
* Début de la séquence console, affiche un message de bienvenue et les crédits
* du projet
* puis donne à l'utilisateur le choix de récupérer un doku sauvegardé
* ou d'en créer un nouveau.
*/
public void welcome() {
System.out.println("Welcome to our Sudoku Solver!");
System.out.println("This is the project of Melvyn Bauvent, Lilas Grenier and Simon Pribylski.");
System.out.println("Do you have a save sudoku you would like to continue? (y/n, default n)");
if (reader.next().equalsIgnoreCase("y")) {
useSavedDoku();
} else {
createDoku();
}
}
/**
* Demande à l'utilisateur un fichier de sauvegarde et le laisse jouer au
* MultiDoku.
* qui y est sauvegardé
*/
private void useSavedDoku() {
System.out.println("What save should we use? Please enter the save number.");
MultiDoku md = getSavedDoku();
int blockWidth = md.getSubGrid(0).getBlockWidth();
int blockHeight = md.getSubGrid(0).getBlocks().getFirst().getCells().size() / blockWidth;
List<String> listSymbols = pickSymbols(blockWidth * blockHeight);
System.out.println("This is the saved sudoku:");
showMultidoku(md, listSymbols, blockWidth, blockHeight);
do {
turn(md, listSymbols, blockWidth, blockHeight);
} while (!md.isSolved());
congrats();
}
/**
* Demande à l'utilisateur les paramètres du doku à générer.
*/
private void createDoku() {
System.out.println("First of all, you need to tell me the size of the sudoku you want to generate.");
int width = getBlockWidth();
int height = getBlockHeight();
System.out.println("Your sudoku will have blocks of a " + width + " x " + height + " format.");
int numberOfSymbols = width * height;
List<String> listSymbols = pickSymbols(numberOfSymbols);
List<IConstraint> listConstraints = getListConstraints();
System.out.println("Now that we have the size of our sudoku, " +
"would you rather have a single grid ('one', default), " +
"or a a multidoku composed of 5 subgrids ('multi') ?");
MultiDoku doku;
if (reader.next().equalsIgnoreCase("multi")) {
doku = SudokuFactory.createBasicXShapedMultidoku(width, height, listConstraints);
} else {
doku = SudokuFactory.createBasicEmptyRectangleDoku(width, height, listConstraints);
}
System.out.println("Your sudoku will look like this:");
showMultidoku(doku, listSymbols, width, height);
System.out.println(
"You can now manually fill this sudoku ('fill'), or generate a playable one from this template ('generate', default):");
if (reader.next().equalsIgnoreCase("fill")) {
findSolution(doku, listSymbols, width, height);
} else {
playableDoku(doku, listSymbols, width, height);
}
}
/**
* Remplit un doku vide en fonction de la difficulté que l'utilisateur
* renseigne,
* et le laisse jouer.
*
* @param doku MultiDoku, MultiDoku vide à remplir
* @param listSymbols List~String~, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
*/
private void playableDoku(MultiDoku doku, List<String> listSymbols, int width, int height) {
System.out.println("We will now fill this sudoku.");
System.out.println("What level of difficulty would you like?" +
" ('very easy', 'easy', 'medium' (default), 'hard', 'full' (sudoku fully completed))");
String difficulty = reader.next().toLowerCase();
if (difficulty.equals("full")) {
generateFullDoku(doku);
System.out.println("Here's your sudoku !");
showMultidoku(doku, listSymbols, width, height);
exit();
} else {
generatePartialDoku(doku, difficulty);
System.out.println("Here's your sudoku !");
showMultidoku(doku, listSymbols, width, height);
do {
turn(doku, listSymbols, width, height);
} while (!doku.isSolved());
congrats();
}
}
/**
* Permet à l'utilisateur de remplir manuellement un sudoku vide, et de le
* remplir
* quand souhaité.
*
* @param doku MultiDoku, MultiDoku vide à remplir
* @param listSymbols List~String~, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
*/
private void findSolution(MultiDoku doku, List<String> listSymbols, int width, int height) {
do {
turn(doku, listSymbols, width, height);
} while (!doku.isSolved());
System.out.println("This doku can be solved like this :");
showMultidoku(doku, listSymbols, width, height);
exit();
}
/**
* Message de félicitation quand l'utilisateur a rempli son doku.
*/
private void congrats() {
System.out.println("Congrats! You've solved this sudoku! We hope this was fun! Let's play together again!");
System.exit(0);
}
/**
* Renvoie un MultiDoku préenregistré, dont le numéro de sauvegarde est
* renseigné
* par l'utilisateur.
*
* @return Mutidoku, multidoku enregistré à la sauveagrde de numéro donné.
*/
private MultiDoku getSavedDoku() {
int nbSave;
MultiDoku md = null;
do {
nbSave = reader.nextInt();
if (nbSave == -1) {
System.exit(0);
}
try {
md = SudokuSerializer.getSavedMultiDoku(nbSave);
} catch (Exception e) {
System.out.println(
"There seems to be a problem with this save, please try again or write '-1' to abort.");
}
} while (md == null);
return md;
}
/**
* Demande à l'utilisateur la largeur d'un bloc du sudoku à générer.
*
* @return int, largeur d'un bloc du sudoku
*/
private int getBlockWidth() {
System.out.println("Width of a block: ");
int widthBlock = reader.nextInt();
checkValidSize(widthBlock);
while (!checkValidSize(widthBlock)) {
System.out.println("That is not a valid width for a block. Try again:");
widthBlock = reader.nextInt();
}
System.out.println("You have chose a width of " + widthBlock + ".");
return widthBlock;
}
/**
* Demande à l'utilisateur la hauteur d'un bloc du sudoku à générer.
*
* @return int, hauteur d'un bloc du sudoku
*/
private int getBlockHeight() {
System.out.println("Height of a block: ");
int heightBlock = reader.nextInt();
checkValidSize(heightBlock);
while (!checkValidSize(heightBlock)) {
System.out.println("That is not a valid height for a block. Try again:");
heightBlock = reader.nextInt();
}
System.out.println("You have chose a height of " + heightBlock + ".");
return heightBlock;
}
/**
* Vérifie si la taille passée en paramètres est une taille valide.
*
* @param size int, longueur à vérifier
* @return true si size>0, false sinon.
*/
private Boolean checkValidSize(int size) {
return (size > 0);
}
/**
* Permet à l'utilisateur de choisir les symboles qu'il souhaite utiliser pour
* l'affichage.
*
* @param numberOfSymbols int, nombre de symboles à choisir
* @return LIst~String~, liste des symboles à utiliser
*/
private List<String> pickSymbols(int numberOfSymbols) {
System.out.println("Would you like to pick the " + numberOfSymbols
+ " symbols from the sudoku? (y/n, default 'no')");
if (reader.next().equalsIgnoreCase("y")) {
List<String> listSymbols = new ArrayList<>();
System.out.println("You have chosen to pick your own symbols.");
for (int i = 0; i < numberOfSymbols; i++) {
System.out.println("Choose for the symbol number " + i + ": ");
String newSymbol = reader.next();
while (listSymbols.contains(newSymbol)) {
System.out.println("This symbol has already been given. Try again:");
newSymbol = reader.next();
}
listSymbols.add(newSymbol);
}
System.out.println("You chose the symbols: " + listSymbols.toString());
return listSymbols;
} else {
System.out.println(
"What existing sets of symbols do you want to use? Numbers ('n', default), letters ('l'), or emojis ('e', may not work on all consoles)?");
return switch (reader.next().toLowerCase()) {
case "l" -> Symbols.Letters.getSymbols();
case "e" -> Symbols.Emojis.getSymbols();
default -> Symbols.Numbers.getSymbols();
};
}
}
/**
* Permet à l'utilisateur de choisir les contraintes qu'il souhaite utiliser
* pour son sudoku.
*
* @return List~IConstraint~, liste des contraintes à utiliser
*/
private List<IConstraint> getListConstraints() {
List<IConstraint> listConstraints = SudokuFactory.DEFAULT_CONSTRAINTS;
System.out.println(
"The sudoku have constraints of blocks, lines and columns. Would you like to add the diagonal constraints ? (y/n, default 'no')");
if (reader.next().equalsIgnoreCase("y")) {
listConstraints.add(Constraint.Diagonal.getConstraint());
}
return listConstraints;
}
/**
* Remplit un sudoku selon la difficulté passée en paramètre.
*
* @param doku MultiDoku, doku vide à remplir selon la difficulté.
* @param difficultyName String, difficulté de résolution du doku à remplir.
*/
private void generatePartialDoku(MultiDoku doku, String difficultyName) {
Difficulty difficulty;
switch (difficultyName) {
case "very easy":
difficulty = Difficulty.VeryEasy;
case "easy":
difficulty = Difficulty.Easy;
case "hard":
difficulty = Difficulty.Hard;
default:
difficulty = Difficulty.Medium;
}
try {
SudokuFactory.fillDoku(doku, difficulty);
} catch (Exception e) {
System.out.println("There seems to be a problem with those settings. Let's start again.");
}
}
/**
* Remplit entièrement le doku passé en paramètre.
*
* @param doku MultiDoku, doku à remplir
*/
private void generateFullDoku(MultiDoku doku) {
new RandomSolver().solve(doku);
}
/**
* Affiche le doku passé en paramètre.
*
* @param doku MultiDoku, MultiDoku à afficher
* @param listSymbols List~String~, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
*/
private void showMultidoku(MultiDoku doku, List<String> listSymbols, int width, int height) {
showMultiDoku(RenderableMultidoku.fromMultidoku(doku), listSymbols, width, height);
}
/**
* Affiche le doku passé en paramètre.
*
* @param doku RenderableMultiDoku, MultiDoku à afficher
* @param listSymbols List~String~, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
*/
private void showMultiDoku(RenderableMultidoku doku, List<String> listSymbols, int width, int height) {
SudokuPrinter.printMultiDokuWithIndex(doku, listSymbols, width, height);
}
/**
* Permet à l'utilisateur de sauvegarder l'état de son doku, soit dans un
* nouveau fichier
* de sauvegarde, soit en écrasant une sauvegarde précédente.
*
* @param doku MultiDoku, MultiDoku à sauvegarder
*/
private void saveMultiDoku(MultiDoku doku) {
System.out.println("Number of the file to overwrite ('-1' or unused save file number to create a new save) :");
int n = reader.nextInt();
String path = SudokuSerializer.saveMultiDoku(doku, n);
System.out.println("The path to your save is: " + path);
}
/**
* Tour de jeu de l'utilisateur, présenté avec les choix de remplir une case du
* doku,
* de sauvegarder son état actuel dans un fichier de sauvegarde,
* de le résoudre tel qu'il est,
* ou de quitter l'application.
*
* @param doku MultiDoku, MultiDoku actuel
* @param listSymbols List~String~, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
*/
private void turn(MultiDoku doku, List<String> listSymbols, int width, int height) {
System.out.println(
"You can now put a number in a cell ('play', default), show a solution ('solution'), save the grid ('save') or exit the program ('exit').");
switch (reader.next()) {
case "save":
saveMultiDoku(doku);
break;
case "solution":
solve(doku, listSymbols, width, height);
break;
case "exit":
exit();
break;
default:
play(doku, listSymbols, width, height);
break;
}
}
/**
* Applique l'étape passée en paramètre.
*
* @param step SolverStep, étape à appliquer
*/
private void applyStep(SolverStep step) {
step.getCell().setSymbolIndex(step.getNewValue());
}
/**
* Permet d'afficher une étape de résolution du doku complété.
*
* @param doku MultiDoku, MultiDoku actuel
* @param listSymbols List~String~, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
* @param step SolverStep, étape de résolution à afficher
* @return boolean, valant true si l'utilisateur veut afficher l'étape, false
* sinon
*/
private boolean showStep(MultiDoku doku, List<String> listSymbols, int width, int height, SolverStep step) {
System.out.println("Here is the step : \n");
showMultidoku(doku, listSymbols, width, height);
applyStep(step);
System.out.println("\nTurns into :\n");
showMultidoku(doku, listSymbols, width, height);
System.out.println("Do you want to see the next step ? (y/n, default n)");
return reader.next().equals("y");
}
/**
* Permet d'afficher les étapes de résolution du doku complété si l'utilisateur
* le souhaite.
*
* @param doku MultiDoku, MultiDoku actuel
* @param listSymbols List~String~, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
* @param steps List~SolverStep~, liste des étapes de résolution
*/
private void showSolveSteps(MultiDoku doku, List<String> listSymbols, int width, int height,
List<SolverStep> steps) {
System.out.println("Would you like to see the steps of the solver ? (y/n, default n)");
doku.getStateManager().popState();
if (reader.next().equalsIgnoreCase("y")) {
int stepCount = 0;
while (stepCount < steps.size() && showStep(doku, listSymbols, width, height, steps.get(stepCount))) {
stepCount++;
}
}
}
/**
* Résout le doku en fonction du solver que choisit l'utilisateur.
*
* @param doku MultiDoku, MultiDoku actuel
* @param listSymbols List~String~, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
*/
private void solve(MultiDoku doku, List<String> listSymbols, int width, int height) {
System.out.println(
"Pick a solver to use : random ('random', default), human ('human') or mixed solver ('mixed').");
List<SolverStep> steps = new ArrayList<>();
doku.getStateManager().pushState();
switch (reader.next()) {
case "human":
new HumanSolver().solve(doku, steps);
break;
case "mixed":
new MixedSolver().solve(doku, steps);
break;
default:
new RandomSolver().solve(doku, steps);
break;
}
showMultidoku(doku, listSymbols, width, height);
showSolveSteps(doku, listSymbols, width, height, steps);
}
/**
* Remplissage d'une Cell du doku en fonction des coordonnées et du symboles que
* l'utilisateur choisit.
*
* @param doku MultiDoku, MultiDoku actuel
* @param listSymbols List~String~, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
*/
private void play(MultiDoku doku, List<String> listSymbols, int width, int height) {
int x, y;
RenderableMultidoku rdoku = RenderableMultidoku.fromMultidoku(doku);
do {
System.out.println("Line of the cell to fill:");
y = reader.nextInt();
System.out.println("Column of the cell to fill:");
x = reader.nextInt();
} while (!isValidCoordinates(rdoku, width, height, x - 1, y - 1));
Cell cell = rdoku.getCell(x - 1, y - 1);
System.out.println("Character to put in the (" + x + ", " + y + ") cell:");
String character = reader.next();
while (!isValidSymbol(character, listSymbols, width * height)) {
System.out.println("This is not a valid symbol; try again:");
character = reader.next();
}
cell.setSymbolIndex(indexOfSymbol(character, listSymbols, width * height));
showMultiDoku(rdoku, listSymbols, width, height);
}
/**
* Vérifie que la Cell identifiée par les coordonées x et y dans le
* RenderableMultiDOku fourni
* existe et est modifiable.
*
* @param doku RenderableMultiDoku, MultiDoku actuel
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
* @param x int, abscisse de la Cell à vérifier
* @param y int, ordonnée de la Cell à vérifier
* @return Boolean true si la Cell aux coordonéees données peut être modifiée,
* false sinon
*/
private boolean isValidCoordinates(RenderableMultidoku doku, int width, int height, int x, int y) {
Cell cell = doku.getCell(x, y);
return ((cell != null) && cell.isMutable());
}
/**
* Renvoie l'index du symbole passé en paramètre.
*
* @param symbol String, symbole dont on veut l'index
* @param listSymbols List~String~, liste des symboles possibles
* @param nbSymbols int, nombre de symboles possibles
* @return int, index du symbole si celui-ci est valide, Cell.NOSYMBOL sinon.
*/
private int indexOfSymbol(String symbol, List<String> listSymbols, int nbSymbols) {
for (int i = 0; i < nbSymbols; i++) {
if (listSymbols.get(i).equals(symbol)) {
return i;
}
}
return Cell.NOSYMBOL;
}
/**
* Vérifie que le symbol passé en paramètre est valide.
*
* @param symbol String, symbole dont on vérifie la validité
* @param listSymbols List~String~, liste des symboles possibles
* @param size int, nombre de symboles possibles
* @return boolean, valant true si le symbole est valide, false sinon.
*/
private boolean isValidSymbol(String symbol, List<String> listSymbols, int size) {
for (int i = 0; i < size; i++) {
if (listSymbols.get(i).equals(symbol)) {
return true;
}
}
return false;
}
/**
* Affiche un message d'aurevoir et ferme l'application.
*/
private void exit() {
System.out.println("Thank you for playing!");
System.exit(0);
}
}

View File

@@ -1,9 +0,0 @@
package sudoku.io;
import sudoku.MultiDoku;
public class SudokuFile {
}

View File

@@ -1,17 +1,39 @@
package sudoku.io;
import sudoku.Sudoku;
import gui.RenderableMultidoku;
import gui.constants.Symbols;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
import java.util.List;
public class SudokuPrinter {
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static void printRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight) {
public static void printRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight, Symbols symbols) {
printRectangleSudoku(s, blockWidth, blockHeight, symbols.getSymbols());
}
public static void printRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight, List<String> listSymbols) {
for (int y = 0; y < s.getSize(); y++) {
if (y % blockHeight == 0 && y > 0) {
System.out.println();
}
StringBuilder line = new StringBuilder("[ ");
for (int x = 0; x < s.getSize(); x++) {
line.append((s.getCell(x, y).getSymbolIndex() + 1)).append(" ");
Cell c = s.getCell(x, y);
if (c.getSymbolIndex() == Cell.NOSYMBOL) {
line.append(" ");
} else {
line.append(listSymbols.get(c.getSymbolIndex())).append(" ");
}
if (x % blockWidth == blockWidth - 1 && x != blockWidth * blockHeight - 1) {
line.append("| ");
}
@@ -20,4 +42,161 @@ public class SudokuPrinter {
System.out.println(line);
}
}
public static void printRectangleSudokuWithIndex(final Sudoku s, int blockWidth, int blockHeight,
List<String> listSymbols) {
StringBuilder header = new StringBuilder("");
header.append(" ");
for (int x = 0; x < blockWidth*blockHeight; x++) {
header.append(x + 1).append(" ");
if (x % blockWidth == blockWidth - 1 && x != blockWidth * blockHeight - 1) {
header.append(" ");
}
}
header.append("\n");
System.out.println(header);
for (int y = 0; y < s.getSize(); y++) {
if (y % blockHeight == 0 && y > 0) {
System.out.println();
}
StringBuilder line = new StringBuilder(y + 1);
line.append(" [ ");
for (int x = 0; x < s.getSize(); x++) {
Cell c = s.getCell(x, y);
if (c.getSymbolIndex() == Cell.NOSYMBOL) {
line.append(" ");
} else {
line.append(listSymbols.get(c.getSymbolIndex())).append(" ");
}
if (x % blockWidth == blockWidth - 1 && x != blockWidth * blockHeight - 1) {
line.append("| ");
}
}
line.append("]");
System.out.println(line);
}
}
public static void printMultiDoku(final RenderableMultidoku rm, Symbols symbols, int blockWidth, int blockHeight) {
printMultiDoku(rm, symbols.getSymbols(), blockWidth, blockHeight);
}
public static void printMultiDoku(final RenderableMultidoku rm, List<String> listSymbols, int blockWidth,
int blockHeight) {
StringBuilder line = new StringBuilder("\n");
int nBlockInWidth = rm.getWidth() / blockWidth;
for (int y = 0; y < rm.getHeight(); y++) {
if (y % blockHeight == 0) {
line.append("__".repeat(Math.max(0, rm.getWidth() + nBlockInWidth))).append("_\n");
}
line.append("[ ");
for (int x = 0; x < rm.getWidth(); x++) {
if (x % blockWidth == 0 && x > 0) {
line.append("| ");
}
Cell cell = rm.getCell(x, y);
if (cell != null) {
if (cell.getSymbolIndex() == Cell.NOSYMBOL) {
line.append("- ");
} else {
line.append(listSymbols.get(cell.getSymbolIndex())).append(" ");
}
} else {
line.append(" ");
}
}
line.append("]\n");
}
line.append("__".repeat(Math.max(0, rm.getWidth() + nBlockInWidth))).append("_\n");
System.out.println(line);
}
public static void printMultiDokuWithIndex(final RenderableMultidoku rm, List<String> listSymbols, int blockWidth,
int blockHeight) {
StringBuilder line = new StringBuilder("\n");
line.append(" ");
for (int x = 0; x < rm.getWidth(); x++) {
line.append(x + 1).append(" ");
if (x % blockWidth == blockWidth - 1 && x != blockWidth * blockHeight - 1) {
line.append(" ");
}
}
line.append("\n");
int nBlockInWidth = rm.getWidth() / blockWidth;
for (int y = 0; y < rm.getHeight(); y++) {
if (y % blockHeight == 0) {
line.append(" ").append("__".repeat(Math.max(0, rm.getWidth() + nBlockInWidth))).append("_\n");
}
line.append(y+1).append(" [ ");
for (int x = 0; x < rm.getWidth(); x++) {
if (x % blockWidth == 0 && x > 0) {
line.append("| ");
}
Cell cell = rm.getCell(x, y);
if (cell != null) {
if (cell.getSymbolIndex() == Cell.NOSYMBOL) {
line.append("- ");
} else {
line.append(listSymbols.get(cell.getSymbolIndex())).append(" ");
}
} else {
line.append(" ");
}
}
line.append("]\n");
}
line.append(" ").append("__".repeat(Math.max(0, rm.getWidth() + nBlockInWidth))).append("_\n");
System.out.println(line);
}
public static String toStringRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight, Symbols symbols) {
return toStringRectangleSudoku(s, blockWidth, blockHeight, symbols.getSymbols());
}
public static String toStringRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight,
List<String> listSymbols) {
StringBuilder result = new StringBuilder();
for (int y = 0; y < s.getSize(); y++) {
// Ajouter une ligne vide entre les blocs horizontaux
if (y % blockHeight == 0 && y > 0) {
result.append("\n");
}
StringBuilder line = new StringBuilder("[ ");
for (int x = 0; x < s.getSize(); x++) {
// Ajouter la valeur de la cellule
Cell cell = s.getCell(x, y);
if (cell.getSymbolIndex() == Cell.NOSYMBOL) {
line.append(" ");
} else {
line.append(listSymbols.get(cell.getSymbolIndex())).append(" ");
}
// Ajouter un séparateur vertical entre les blocs
if (x % blockWidth == blockWidth - 1 && x != s.getSize() - 1) {
line.append("| ");
}
}
line.append("]");
result.append(line).append("\n");
}
return result.toString();
}
public static void printMultiDoku(final MultiDoku doku, int blockWidth, int blockHeight, Symbols symbols) {
if (doku.getNbSubGrids() == 1) {
printRectangleSudoku(doku.getSubGrid(0), blockWidth, blockHeight, symbols);
} else {
printMultiDoku(RenderableMultidoku.fromMultidoku(doku), symbols, blockWidth, blockHeight);
}
}
public static void printMultiDokuWithIndex(final MultiDoku doku, int blockWidth, int blockHeight, Symbols symbols) {
if (doku.getNbSubGrids() == 1) {
printRectangleSudokuWithIndex(doku.getSubGrid(0), blockWidth, blockHeight, symbols.getSymbols());
} else {
printMultiDokuWithIndex(RenderableMultidoku.fromMultidoku(doku), symbols.getSymbols(), blockWidth,
blockHeight);
}
}
}

View File

@@ -1,17 +0,0 @@
package sudoku.io;
import sudoku.MultiDoku;
public class SudokuSave {
public static enum AlgoResolution {
Backtracking,
NoBacktring
}
// private final MultiDoku sudoku;
// private final AlgoResolution resolution;
}

View File

@@ -1,21 +1,35 @@
package sudoku.io;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import sudoku.Block;
import sudoku.Cell;
import sudoku.ImmutableCell;
import sudoku.MultiDoku;
import sudoku.MutableCell;
import sudoku.Sudoku;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import sudoku.structure.Block;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
/**
* Classe permettant d'effectuer des opérations sur les sudokus afin de les
* charger/sauvegarder
*/
public class SudokuSerializer {
public static String serializeSudoku(final MultiDoku multidoku) {
/**
* Convertit un sudoku en object JSON
* @param multidoku le sudoku à sérialiser
* @return le JSON
*/
public static JSONObject serializeSudoku(final MultiDoku multidoku) {
List<Cell> cellIds = new ArrayList<>();
List<Block> blockIds = new ArrayList<>();
@@ -29,10 +43,10 @@ public class SudokuSerializer {
// init cells
for (Cell cell : sudoku.getCells()) {
if (!cellIds.contains(cell)) {
cellIds.add(cell);
if (cellIds.contains(cell))
continue;
}
cellIds.add(cell);
Block block = cell.getBlock();
if (!blockIds.contains(block)) {
@@ -40,12 +54,13 @@ public class SudokuSerializer {
}
int blockID = blockIds.indexOf(block);
int symboleIndex = cell.getSymbolIndex();
assert (blockID >= 0);
int symbolIndex = cell.getSymbolIndex();
JSONObject cellJsonObject = new JSONObject();
cellJsonObject.put("blockID", blockID);
cellJsonObject.put("symboleIndex", symboleIndex);
if (cell instanceof ImmutableCell) {
cellJsonObject.put("symbolIndex", symbolIndex);
if (!cell.isMutable()) {
cellJsonObject.put("immutable", true);
}
jsonCells.put(cellJsonObject);
@@ -55,12 +70,12 @@ public class SudokuSerializer {
// init blocks
for (int i = 0; i < blockIds.size(); i++) {
for (Block blockId : blockIds) {
JSONObject blockJsonObject = new JSONObject();
JSONArray cellsJsonArray = new JSONArray();
Block block = blockIds.get(i);
for (Cell cell : block.getCells()) {
for (Cell cell : blockId.getCells()) {
int cellID = cellIds.indexOf(cell);
assert (cellID >= 0);
cellsJsonArray.put(cellID);
}
blockJsonObject.put("cellIDs", cellsJsonArray);
@@ -72,6 +87,7 @@ public class SudokuSerializer {
JSONObject jsonSudoku = new JSONObject();
JSONArray cellsJsonArray = new JSONArray();
JSONArray blocksJsonArray = new JSONArray();
JSONArray constraintsJsonArray = new JSONArray();
Sudoku sudoku = multidoku.getSubGrid(i);
@@ -79,6 +95,7 @@ public class SudokuSerializer {
for (Cell cell : sudoku.getCells()) {
int cellID = cellIds.indexOf(cell);
assert (cellID >= 0);
cellsJsonArray.put(cellID);
}
@@ -86,22 +103,133 @@ public class SudokuSerializer {
for (Block block : sudoku.getBlocks()) {
int blockID = blockIds.indexOf(block);
assert (blockID >= 0);
blocksJsonArray.put(blockID);
}
// serialize constraints
for (IConstraint cons : sudoku.getConstraints()) {
boolean constraintSerialized = false;
for (Constraint enumCons : Constraint.values()) {
if (cons.getClass().isAssignableFrom(enumCons.getConstraint().getClass())) {
constraintSerialized = true;
constraintsJsonArray.put(enumCons.ordinal());
}
}
if (!constraintSerialized) {
System.out.println("La contrainte " + cons.getClass() + " n'a pas pu être sérialisé !");
}
}
jsonSudoku.put("constraints", constraintsJsonArray);
jsonSudoku.put("cells", cellsJsonArray);
jsonSudoku.put("blocks", blocksJsonArray);
jsonSudoku.put("blockWidth", sudoku.getBlockWidth());
jsonSudokus.put(i, jsonSudoku);
}
jsonRoot.put("multidoku", jsonSudokus);
jsonRoot.put("cells", jsonCells);
jsonRoot.put("blocks", jsonBlocks);
return jsonRoot.toString();
return jsonRoot;
}
public static MultiDoku deserializeSudoku(final String data) {
JSONObject jsonObject = new JSONObject(data);
/**
* Crée le répertoire save afin d'y sauvegarder les sudokus
*/
private static void createSaveDir() {
File f = new File("save");
f.mkdir();
}
/**
* Save a serialized MultiDoku in a JSON file.
*
* @param doku MultiDoku, MultiDoku to save.
* @return String, the path of the save.
*/
public static String saveMultiDoku(final MultiDoku doku) {
createSaveDir();
JSONObject jsonRoot = serializeSudoku(doku);
File f = new File("save", "save.json");
int i = 0;
while (f.exists()) {
String newName = "save-" + ++i + ".json";
f = new File("save", newName);
}
try (FileWriter file = new FileWriter(f)) {
file.write(jsonRoot.toString(3));
} catch (IOException e) {
e.printStackTrace();
}
return f.getAbsolutePath();
}
public static String saveMultiDoku(final MultiDoku doku, final int saveToOverwrite) {
createSaveDir();
File f;
if (saveToOverwrite == 0) {
f = new File("save", "save.json");
} else {
f = new File("save", "save-" + saveToOverwrite + ".json");
}
if (!f.exists()) {
return saveMultiDoku(doku);
} else {
try (FileWriter file = new FileWriter(f)) {
file.write(serializeSudoku(doku).toString(3));
} catch (IOException e) {
e.printStackTrace();
}
return f.getAbsolutePath();
}
}
/**
* Get a MultiDoku from a pre-existing json save file.
*
* @param numberSave int, number of the save file to open.
* @return MultiDoku, MultiDoku contained in the file.
* @throws Exception when the given save file does not exist.
*/
public static MultiDoku getSavedMultiDoku(int numberSave) throws Exception {
String fileName;
if (numberSave < 1) {
fileName = "save.json";
} else {
fileName = "save-" + numberSave + ".json";
}
File f = new File("save", fileName);
String fileContent;
if (!f.exists()) {
throw new Exception("This save does not exist.");
} else {
fileContent = new String(Files.readAllBytes(Paths.get("save/" + fileName)));
return deserializeSudoku(fileContent);
}
}
/**
* Construit un sudoku à partir d'un String en JSON
* @param json le sudoku sérialisé
* @return le sudoku désérialisé
*/
public static MultiDoku deserializeSudoku(final String json) {
JSONObject jsonRoot = new JSONObject(json);
return deserializeSudoku(jsonRoot);
}
/**
* Désérialise un sudoku d'un objet JSON
* @param jsonObject l'objet à désérialiser
* @return le sudoku correspondant
*/
public static MultiDoku deserializeSudoku(final JSONObject jsonObject) {
List<Cell> cells = new ArrayList<>();
List<Block> blocks = new ArrayList<>();
@@ -111,11 +239,11 @@ public class SudokuSerializer {
JSONArray cellsJson = jsonObject.getJSONArray("cells");
for (int i = 0; i < cellsJson.length(); i++) {
JSONObject entry = cellsJson.getJSONObject(i);
int symboleIndex = entry.getInt("symboleIndex");
int symbolIndex = entry.getInt("symbolIndex");
if (entry.has("immutable")) {
cells.add(new ImmutableCell(symboleIndex));
cells.add(new Cell(symbolIndex, false));
} else {
cells.add(new MutableCell(symboleIndex));
cells.add(new Cell(symbolIndex));
}
}
@@ -140,9 +268,11 @@ public class SudokuSerializer {
JSONObject sudokuJsonObject = multidokuJsonObject.getJSONObject(i);
JSONArray sudokuCellsJsonArray = sudokuJsonObject.getJSONArray("cells");
JSONArray sudokuBlocksJsonArray = sudokuJsonObject.getJSONArray("blocks");
JSONArray sudokuConstraintsJsonArray = sudokuJsonObject.getJSONArray("constraints");
List<Cell> sudokuCells = new ArrayList<>();
List<Block> sudokuBlocks = new ArrayList<>();
List<IConstraint> sudokuConstraints = new ArrayList<>();
for (int j = 0; j < sudokuCellsJsonArray.length(); j++) {
int cellID = sudokuCellsJsonArray.getInt(j);
@@ -154,7 +284,17 @@ public class SudokuSerializer {
sudokuBlocks.add(blocks.get(blockID));
}
sudokus.add(new Sudoku(sudokuCells, sudokuBlocks, null));
for (int j = 0; j < sudokuConstraintsJsonArray.length(); j++) {
int constraintID = sudokuConstraintsJsonArray.getInt(j);
sudokuConstraints.add(Constraint.values()[constraintID].getConstraint());
}
Sudoku s = new Sudoku(sudokuCells, sudokuBlocks, sudokuConstraints);
s.setBlockWidth(sudokuJsonObject.getInt("blockWidth"));
for (Block block : s.getBlocks()) {
block.getSudokus().add(s);
}
sudokus.add(s);
}
return new MultiDoku(sudokus);

View File

@@ -0,0 +1,49 @@
package sudoku.solver;
import java.util.List;
import java.util.concurrent.CancellationException;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
public class BacktrackingSolver implements Solver {
/**
* Résout le MultiDoku passé en paramètre, avec backtracking.
*
* @param doku MultiDoku, MultiDoku à résoudre.
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
*/
@Override
public boolean solve(MultiDoku doku, List<SolverStep> steps) {
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
if (doku.isSolved()) {
return true;
}
Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) {
return false;
}
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
if (possibleSymbols.isEmpty()) {
return false;
}
for (int symbol : possibleSymbols) {
cellToFill.setSymbolIndex(symbol);
addStep(cellToFill, steps);
if (this.solve(doku, steps)) {
return true;
} else {
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
addStep(cellToFill, steps);
}
}
return false;
}
}

View File

@@ -0,0 +1,59 @@
package sudoku.solver;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
public class HintHelper {
public record Hint(Cell cell, int newValue) {}
/**
* Si possible, donne un indice sur la résolution du doku passé en paramètre,
* selon la méthode de résolution rensaignée.
* @param doku MultiDoku, multidoku pour lequel on veut un indice
* @param solver Solver, méthode de résolution souhaitée
* @return Hint, indice sur une case à remplir, valant null si le doku n'a pas de solution.
*/
public static Hint getHint(MultiDoku doku, Solver solver) {
doku.getStateManager().pushState();
doku.clearMutableCells();
if (!solver.solve(doku))
return null;
var stateSolved = doku.getStateManager().popAndGetState();
// find differences
Map<Cell, Integer> newValues = new HashMap<>();
for (var entry : stateSolved.entrySet()) {
Cell cell = entry.getKey();
// we only want the cells that can be filled
if (!cell.isMutable())
continue;
int oldValue = cell.getSymbolIndex();
int newValue = stateSolved.get(cell);
if (oldValue == newValue)
continue;
// we have to clear the cell
if (newValue == Cell.NOSYMBOL)
return new Hint(cell, newValue);
// we have to change the cell value
if (oldValue != Cell.NOSYMBOL)
return new Hint(cell, newValue);
// there is a valid move
newValues.put(cell, newValue);
}
// this is too complex just for fetching a random entry, but whatever ...
Random r = new Random();
List<Cell> cells = new ArrayList<>(newValues.keySet());
Cell randomCell = cells.get(r.nextInt(cells.size()));
int randomCellValue = newValues.get(randomCell);
return new Hint(randomCell, randomCellValue);
}
}

View File

@@ -0,0 +1,39 @@
package sudoku.solver;
import java.util.List;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
public class HumanSolver implements Solver {
/**
* Résout le MultiDoku passé en paramètre, avec règles de déduction.
*
* @param doku MultiDoku, MultiDoku à résoudre.
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
*/
@Override
public boolean solve(MultiDoku doku, List<SolverStep> steps) {
while (!doku.isSolved()) {
boolean filledCell = false;
for (Cell cell : doku.getCells()) {
if (!cell.isMutable() || !cell.isEmpty())
continue;
List<Integer> possibleSymbols = cell.getPossibleSymbols();
if (possibleSymbols.size() == 1) {
cell.setSymbolIndex(possibleSymbols.getFirst());
addStep(cell, steps);
filledCell = true;
}
}
// on ne peut plus remplir de cases, on abandonne
if (!filledCell)
return false;
}
return true;
}
}

View File

@@ -0,0 +1,90 @@
package sudoku.solver;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
public class MixedSolver implements Solver {
private List<Cell> findCellsToBacktrack(MultiDoku doku, int maxPossibilities) {
List<Cell> cells = new ArrayList<>();
for (Cell cell : doku.getCells()) {
if (!cell.isMutable() || !cell.isEmpty())
continue;
List<Integer> possibleSymbols = cell.getPossibleSymbols();
if (possibleSymbols.size() == maxPossibilities) {
cells.add(cell);
}
// une cellule nous empêche de continuer
if (possibleSymbols.size() == 0)
return null;
}
return cells;
}
/**
* Résout le MultiDoku passé en paramètre, avec règles de déduction et
* backtracking.
*
* @param doku MultiDoku, MultiDoku à résoudre.
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
*/
@Override
public boolean solve(MultiDoku doku, List<SolverStep> steps) {
if (Thread.interrupted()) {
throw new CancellationException("User wants to stop the solver");
}
if (doku.isSolved())
return true;
if (findCellsToBacktrack(doku, 0) == null)
return false;
for (Cell cell : doku.getCells()) {
if (!cell.isMutable() || !cell.isEmpty())
continue;
List<Integer> possibleSymbols = cell.getPossibleSymbols();
if (possibleSymbols.size() == 1) {
cell.setSymbolIndex(possibleSymbols.getFirst());
addStep(cell, steps);
if (solve(doku, steps))
return true;
cell.setSymbolIndex(Cell.NOSYMBOL);
addStep(cell, steps);
return false;
}
}
// on ne peut plus remplir de cases, on tente de backtrack
int maxPossibilities = 2;
List<Cell> backtrackCells = new ArrayList<>();
while (backtrackCells.isEmpty()) {
backtrackCells = findCellsToBacktrack(doku, maxPossibilities);
if (backtrackCells == null || maxPossibilities > doku.getSubGrid(0).getSize())
return false;
maxPossibilities++;
}
// on fait du backtracking
for (Cell backtrackCell : backtrackCells) {
List<Integer> possibilities = backtrackCell.getPossibleSymbols();
for (int symbol : possibilities) {
backtrackCell.setSymbolIndex(symbol);
addStep(backtrackCell, steps);
if (solve(doku, steps))
return true;
}
backtrackCell.setSymbolIndex(Cell.NOSYMBOL);
addStep(backtrackCell, steps);
}
return false;
}
}

View File

@@ -0,0 +1,55 @@
package sudoku.solver;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CancellationException;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
public class RandomSolver implements Solver {
/**
* Résout, si possible, le multidoku passé en paramètre
* en testant toutes les possibilités, de manière aléatoire, avec un algorithme
* de backtracking.
*
* @param doku Multidoku, à résoudre
* @return boolean, true s'il est résolu ou false s'il ne l'est pas.
*/
@Override
public boolean solve(MultiDoku doku, List<SolverStep> steps) {
Random rand = new Random();
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
if (doku.isSolved()) {
return true;
}
Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) {
return false;
}
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
while (!possibleSymbols.isEmpty()) {
int nextPossibleSymbolIndex = rand.nextInt(possibleSymbols.size());
int nextSymbol = possibleSymbols.get(nextPossibleSymbolIndex);
cellToFill.setSymbolIndex(nextSymbol);
addStep(cellToFill, steps);
if (this.solve(doku, steps)) {
return true;
}
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
addStep(cellToFill, steps);
possibleSymbols.remove(nextPossibleSymbolIndex);
}
return false;
}
}

View File

@@ -1,42 +1,68 @@
package sudoku.solver;
import sudoku.MultiDoku;
import sudoku.MutableCell;
import sudoku.constraint.IConstraint;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Stack;
import java.util.logging.Logger;
public class Solver {
Stack<MutableCell> stack;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
public Solver() {}
public interface Solver {
private void rollBack() {
stack.pop();
/**
* Log du Solver, qui garde trace des actions réalisées.
*/
public static final Logger logger = Logger.getLogger("SolverLogger");
boolean solve(MultiDoku doku, List<SolverStep> solverSteps);
default boolean solve(MultiDoku doku) {
return solve(doku, null);
}
public MultiDoku solve(MultiDoku doku, List<IConstraint> constraints) throws Exception {
List<MutableCell> allMutableCells = doku.getMutableCells();
List<MutableCell> remainingCellsToCheck = new ArrayList<>(allMutableCells);
Random rand = new Random();
while (!remainingCellsToCheck.isEmpty()) {
int indexCurrentCell = rand.nextInt(remainingCellsToCheck.size());
MutableCell currentCell = remainingCellsToCheck.get(indexCurrentCell);
/**
* Compte le nombre de solutions possibles au MultiDoku passé en paramètres.
*
* @param doku MultiDoku, MultiDoku dont on veut le nombre de solutions.
* @return int, nombre de solutions possibles.
*/
default int countSolution(MultiDoku doku) {
int result = 0;
int symbol = currentCell.getPossibleSymbols().get(0);
currentCell.setSymbolIndex(symbol);
// stack.push(new MutableCell(currentCell));
try {
doku.updateSymbolsPossibilities();
} catch (Exception e) {
this.rollBack();
System.out.println(this.stack);
}
remainingCellsToCheck.remove(indexCurrentCell);
if (doku.isSolved()) {
return 1;
}
return doku;
Cell cellToFill = doku.getFirstEmptyCell();
assert (cellToFill != null);
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
for (int symbol : possibleSymbols) {
doku.getStateManager().pushState();
cellToFill.setSymbolIndex(symbol);
if (solve(doku)) {
result++;
if (result > 1) {
doku.getStateManager().popState();
return result;
}
}
doku.getStateManager().popState();
}
return result;
}
/**
* Méthode utilisée en interne afin de rajouter une étape si l'utilisateur le
* souhaite (steps non null)
*
* @param cell la cellule qui a été modifiée
* @param steps la liste d'étape à mettre à jour
*/
default void addStep(Cell cell, List<SolverStep> steps) {
if (steps == null)
return;
steps.add(new SolverStep(cell));
}
}

View File

@@ -0,0 +1,23 @@
package sudoku.solver;
import sudoku.structure.Cell;
public class SolverStep {
private final Cell cell;
private final int newValue;
public SolverStep(Cell cell) {
this.cell = cell;
this.newValue = cell.getSymbolIndex();
}
public int getNewValue() {
return newValue;
}
public Cell getCell() {
return cell;
}
}

View File

@@ -0,0 +1,54 @@
package sudoku.solver;
import java.util.List;
import java.util.concurrent.CancellationException;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
/**
* Class de test non utilisé
*/
public class StupidSolver implements Solver{
private boolean solve(Sudoku sudoku, int index, List<SolverStep> steps) {
// mécanisme d'abandon
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
// si tout est bon avant, on a gagné
if (!sudoku.isValidCoords(index))
return true;
// si la case n'est pas modifiable, on passe à la suivante
if (!sudoku.getCell(index).isMutable())
return solve(sudoku, index + 1, steps);
for (int symbol = 0; symbol < sudoku.getSize(); symbol++) {
if (sudoku.getCell(index).trySetValue(symbol)) {
addStep(sudoku.getCell(index), steps);
// on tente de placer sur la case suivante
if (solve(sudoku, index + 1, steps)) {
return true;
}
}
}
// on a tout essayé et rien n'a fonctionné
sudoku.getCell(index).empty();
addStep(sudoku.getCell(index), steps);
return false;
}
@Override
public boolean solve(MultiDoku doku, List<SolverStep> steps) {
if (doku.isSolved())
return true;
for (Sudoku sudoku : doku.getSubGrids()) {
if (!solve(sudoku, 0, steps))
return false;
}
return true;
}
}

View File

@@ -0,0 +1,77 @@
package sudoku.structure;
import java.util.ArrayList;
import java.util.List;
/**
* Class qui représente les Block de chaque Sudoku,
* Un Block étant un ensemble de cellule avec une contrainte de block qui lui
* ait associé.
*/
public class Block {
// <editor-fold defaultstate="collapsed" desc="ATTRIBUTS">
/**
* L'ensemble des cellules du block.
*/
private final List<Cell> cells;
/**
* Liste de Sudoku qui contiennent le block
* Pour un accès plus rapide aux sudokus.
*/
private final List<Sudoku> sudokus;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="METHODES">
/**
* Crée un Block avec une liste de Cell donnée.
* @param cells List~Cell~
*/
public Block(List<Cell> cells) {
this.cells = cells;
this.sudokus = new ArrayList<>();
}
/**
* Crée un Block avec une liste de Cell vide.
*/
public Block() {
this(new ArrayList<>());
}
public List<Cell> getCells() {
return cells;
}
public List<Sudoku> getSudokus() {
return sudokus;
}
/**
* Ajoute une Cell au Block
*
* @param newCell Cell, à ajouter
*/
public void addCell(Cell newCell) {
this.cells.add(newCell);
}
/**
* Cherche si le Block contient déjà un symbole donné.
*
* @param symbolIndex int, un index de symbole
* @return boolean, true s'il contient le symbole et false sinon
*/
public boolean containsSymbol(int symbolIndex) {
for (Cell cell : getCells()) {
if (cell.getSymbolIndex() == symbolIndex)
return true;
}
return false;
}
// </editor-fold>
}

View File

@@ -0,0 +1,160 @@
package sudoku.structure;
import java.util.ArrayList;
import java.util.List;
/**
* Représente une case d'un, ou plusieurs, sudoku qui à comme valeur un index de symbole.
* Celui ci pourra être remplacer par un symbole en temps voulu.
*/
public class Cell {
// <editor-fold defaultstate="collapsed" desc="ATTRIBUTS">
/**
* Constante de valeur d'index de symbole quand il n'y en a pas,
* soit que la Cell est vide.
*/
public static int NOSYMBOL = -1;
/**
* Block dans lequel est la Cell.
*/
private Block blockContainer;
/**
* L'index du symbole que contient la Cell.
* Il est initialisé à Cell.NOSYMBOL.
*/
private int symbolIndex = Cell.NOSYMBOL;
/**
* Si cette Cell peut être modififié ou non.
*/
private boolean isMutable = true;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="METHODES">
public Cell() {
this(Cell.NOSYMBOL);
}
public Cell(int symbolIndex) {
this.symbolIndex = symbolIndex;
}
public Cell(int symbolIndex, boolean isMutable) {
this.symbolIndex = symbolIndex;
this.isMutable = isMutable;
}
public int getSymbolIndex() {
return this.symbolIndex;
}
/**
* Renvoie le Block qui la contient.
* @return Block.
*/
public Block getBlock() {
return this.blockContainer;
}
/**
* Renvoie si la Cell est modifiable
* @return boolean, true si elle est modifiable ou false sinon.
*/
public boolean isMutable() {
return this.isMutable;
}
public void setSymbolIndex(int symbolIndex) {
this.symbolIndex = symbolIndex;
}
/**
* Rend la Cell immuable.
*/
public void setImmutable() {
this.isMutable = false;
}
public void setBlock(Block block) {
this.blockContainer = block;
}
/**
* Vide la Cell.
*/
public void clearCurrentSymbol() {
setSymbolIndex(NOSYMBOL);
}
/**
* Renvoie si la Cell est vide ou non.
* @return boolean, true si la Cell est vide, false sinon.
*/
public boolean isEmpty() {
return this.symbolIndex == Cell.NOSYMBOL;
}
/**
* Vide la Cell, en renvoie l'ancien index du symbole qui était dedans.
* @return int, index du symbole anciennement contenue dans la Cell.
*/
public int empty() {
int oldSymbol = this.symbolIndex;
this.symbolIndex = Cell.NOSYMBOL;
return oldSymbol;
}
/**
* Vérifie si la Cell peut prendre ce symbole par rapport aux contraintes de ses Sudokus.
* @param value int, index du symbole
* @return boolean, true si elle peut, false sinon.
*/
public boolean canHaveValue(int value) {
for (Sudoku s :getBlock().getSudokus()) {
int cellIndex = s.getCells().indexOf(this);
// la cellule existe
if (cellIndex != -1) {
int cellX = cellIndex % s.getSize();
int cellY = cellIndex / s.getSize();
if (!s.canBePlaced(cellX, cellY, value)) {
return false;
}
}
}
return true;
}
/**
* Renvoie les symboles que peut prendre cette Cell par rapport aux contraintes de ses Sudokus.
* @return List~Integer~, la liste des symboles possibles.
*/
public List<Integer> getPossibleSymbols() {
List<Integer> result = new ArrayList<>();
for (int i = 0; i < getBlock().getSudokus().get(0).getSize(); i++) {
if (canHaveValue(i))
result.add(i);
}
return result;
}
/**
* Essaye de placer la valeur et renvoie false si ce n'est pas possible.
* @param newValue int, valeur à placer.
* @return boolean, true si la Cell à pris la valeur newValue, false sinon.
*/
public boolean trySetValue(int newValue) {
if (!isMutable())
return false;
if (!canHaveValue(newValue))
return false;
setSymbolIndex(newValue);
return true;
}
// </editor-fold>
}

View File

@@ -0,0 +1,63 @@
package sudoku.structure;
/**
* Représente les coordonnées d'une Cell.
*/
public class Coordinate {
// <editor-fold defaultstate="collapsed" desc="ATTRIBUTS">
/**
* L'abscisse de la Cell.
*/
private int x;
/**
* L'ordonnée de la Cell.
*/
private int y;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="METHODES">
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
/**
* Ajoute la Coordiante donnée à celle-ci.
* @param other Coordiante, à ajouter.
* @return Coordinate, le résultat de l'addition.
*/
public Coordinate add(Coordinate other) {
return new Coordinate(this.x + other.x, this.y + other.y);
}
/**
* Soustrait la Coordiante donnée à celle-ci.
* @param other Coordiante, à soustraire.
* @return Coordinate, le résultat de la soustraction.
*/
public Coordinate sub(Coordinate other) {
return new Coordinate(this.x - other.x, this.y - other.y);
}
// </editor-fold>
}

View File

@@ -0,0 +1,52 @@
package sudoku.structure;
/**
* Les difficultés d'un Sudoku,
* représente le nombre de cases à enlever, en proportion, à un Sudoku.
* Par exemple, avec 0.1 de factor, on enlevera 10% des cases.
*/
public enum Difficulty {
VeryEasy("Très facile", 0.1),
Easy("Facile", 0.25),
Medium("Moyen", 0.5),
Hard("Difficile", 0.75),
VeryHard("Impossible", 0.78);
/**
* Le pourcentage de Cell à enlever.
*/
final double factor;
/**
* Le nom de la difficulté.
*/
final String displayName;
Difficulty(String displayName, double factor) {
this.factor = factor;
this.displayName = displayName;
}
private static final String[] difficultyNames;
static {
Difficulty[] diffs = Difficulty.values();
difficultyNames = new String[diffs.length];
for (int i = 0; i < diffs.length; i++) {
difficultyNames[i] = diffs[i].getDisplayName();
}
}
public String getDisplayName() {
return displayName;
}
public double getFactor() {
return factor;
}
public static String[] getDifficultyNames() {
return difficultyNames;
}
}

View File

@@ -0,0 +1,208 @@
package sudoku.structure;
import sudoku.io.SudokuSerializer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Class : MultiDoku
* Brief : Représente une grille de Multidoku.
* Une grille de sudoku est un multidoku avec un seul sous-sudoku.
*/
public class MultiDoku {
// <editor-fold defaultstate="collapsed" desc="ATTRIBUTS">
/**
* Liste des sous-Sudoku contenue dans le multidoku.
*/
private final List<Sudoku> subGrids;
/**
* Pile, qui contient des états du MultiDoku,
* utile pour la résolution.
*/
private final StateManager stateManager;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="METHODES">
public MultiDoku(List<Sudoku> subGrids) {
this.subGrids = subGrids;
this.stateManager = new StateManager(this);
}
/**
* Check si le MultiDoku est résolu, c'est à dire complet et cohérent avec ses contraintes.
*
* @return boolean, true s'il est résolu et false sinon.
*/
public boolean isSolved() {
for (Sudoku sudoku : this.subGrids) {
if (!sudoku.isSolved())
return false;
}
return true;
}
/**
* Renvoie la liste des Cells préalablement remplies du MultiDoku.
*
* @return List~Cell~, vide si aucune Cell n'est remplie.
*/
public List<Cell> getFilledCells() {
List<Cell> result = new ArrayList<>();
for (Cell cell : this.getCells()) {
if (!cell.isEmpty()) {
result.add(cell);
}
}
return result;
}
/**
* Renvoie la liste des Cells vides du MultiDoku.
*
* @return List~Cell~, vide si aucune Cell ne l'est.
*/
public List<Cell> getEmptyCells() {
List<Cell> result = new ArrayList<>();
for (Cell cell : this.getCells()) {
if (cell.isEmpty()) {
result.add(cell);
}
}
return result;
}
/**
* Renvoie la 1re Cell vide des sous-Sudoku.
*
* @return Cell, une Cell vide, ou null s'il n'y en a pas.
*/
public Cell getFirstEmptyCell() {
for (Sudoku sudoku : this.subGrids) {
Cell cellTmp = sudoku.getFirstEmptyCell();
if (cellTmp != null) {
return cellTmp;
}
}
return null;
}
/**
* Renvoie le nombre de sudoku contenu dans ce MultiDoku.
*
* @return int
*/
public int getNbSubGrids() {
return subGrids.size();
}
/**
* Renvoie la ie sudoku contenue dans ce MultiDoku.
*
* @param i int, indice du sudoku à renvoyer.
* @return Sudoku, ie Sudoku
*/
public Sudoku getSubGrid(int i) {
return subGrids.get(i);
}
/**
* Renvoie la liste des Cells contenue dans ce MultiDoku,
* soit les Cells contenues de chaques sous-Sudoku.
*
* @return List~Cell~
*/
public List<Cell> getCells() {
Set<Cell> cellsSet = new HashSet<>();
for (Sudoku sudoku : subGrids) {
cellsSet.addAll(sudoku.getCells());
}
return new ArrayList<>(cellsSet);
}
/**
* Renvoie le nombre de Cell contenue dans le MultiDoku.
*
* @return int, nombre de Cell dans le MultiDoku.
*/
public int getNbCells() {
return getCells().size();
}
/**
* Change les Cells de ce MultiDoku avec des symboles, en Cells immuables.
*/
public void setFilledCellsImmutable() {
for (Cell filledCell : getFilledCells()) {
filledCell.setImmutable();
}
}
/**
* Vide les Cells modifiable.
*/
public void clearMutableCells() {
for (Sudoku s : getSubGrids()) {
for (Cell cell : s.getCells()) {
if (cell.isMutable())
cell.clearCurrentSymbol();
}
}
}
/**
* Renvoie les sous-Sudoku
*
* @return List~Sudoku~
*/
public List<Sudoku> getSubGrids() {
return this.subGrids;
}
public StateManager getStateManager() {
return stateManager;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof MultiDoku otherDoku))
return false;
if (this.getNbSubGrids() != otherDoku.getNbSubGrids())
return false;
for (int i = 0; i < this.getNbSubGrids(); i++) {
Sudoku sudoku = this.getSubGrid(i);
Sudoku otherSudoku = otherDoku.getSubGrid(i);
if (sudoku.getSize() != otherSudoku.getSize())
return false;
for (int j = 0; j < sudoku.getSize() * sudoku.getSize(); j++) {
if (sudoku.getCell(i).getSymbolIndex() != otherSudoku.getCell(i).getSymbolIndex())
return false;
}
}
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Multidoku {");
for (Sudoku sudoku : subGrids) {
sb.append("\n\t").append(sudoku.toString());
}
sb.append("\n}");
return sb.toString();
}
public MultiDoku clone() {
return SudokuSerializer.deserializeSudoku(SudokuSerializer.serializeSudoku(this));
}
// </editor-fold>
}

View File

@@ -0,0 +1,59 @@
package sudoku.structure;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* Une pile, qui réprésente les états d'un MultiDoku,
* utile pour les Solvers.
*/
public class StateManager {
/**
* Le MultiDoku auquel il est associé.
*/
private final MultiDoku doku;
/**
* La pile des états du MultiDoku associé.
*/
private final Stack<Map<Cell, Integer>> states;
public StateManager(MultiDoku doku) {
this.states = new Stack<>();
this.doku = doku;
}
public Map<Cell, Integer> pushState() {
states.add(saveState());
return states.getLast();
}
public void popState() {
assert (!states.isEmpty());
restoreState(states.pop());
}
public Map<Cell, Integer> popAndGetState() {
assert (!states.isEmpty());
var currentState = saveState();
restoreState(states.pop());
return currentState;
}
private void restoreState(Map<Cell, Integer> state) {
for (var entry : state.entrySet()) {
entry.getKey().setSymbolIndex(entry.getValue());
}
}
private Map<Cell, Integer> saveState() {
Map<Cell, Integer> state = new HashMap<>();
for (Cell cell : this.doku.getCells()) {
state.put(cell, cell.getSymbolIndex());
}
return state;
}
}

View File

@@ -0,0 +1,297 @@
package sudoku.structure;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import java.util.List;
/**
* Class : Sudoku
* Brief : Représent un Sudoku
*/
public class Sudoku {
// <editor-fold defaultstate="collapsed" desc="ATTRIBUTS">
/**
* Liste des Block contenus dans le Sudoku.
*/
private final List<Block> blocks;
/**
* Liste des Cells contenus dans le Sudoku.
*/
private final List<Cell> cells;
/**
* Liste des contraintes (TODO) du Sudoku.
*/
private final List<IConstraint> constraints;
/**
* Largeur des Blocks s'ils sont rectangulaires,
* valant 0 si ce n'est pas le cas.
*/
private int blockWidth;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="METHODES">
public Sudoku(List<Cell> cells, List<Block> blocks, List<IConstraint> constraints) {
this.cells = cells;
this.blocks = blocks;
this.constraints = constraints;
}
/**
* Transforme un index de Cell en Coordinate.
*
* @param index int, index d'une Cell.
* @return Coordinate, correspondante à l'index donné.
*/
public Coordinate toCoords(int index) {
return new Coordinate(index % getSize(), index / getSize());
}
/**
* Transforme des coordonées d'une Cell en index.
*
* @param x int, abscisse.
* @param y int, ordonnée.
* @return int, index correspondant.
*/
public int toIndex(int x, int y) {
return y * getSize() + x;
}
/**
* Vérifie que des coordonnées correspondent bien à une Cell dans le Sudoku.
*
* @return boolean, valant true si les coordonnées sont dans les bornes du
* Sudoku, false sinon.
*/
public boolean isValidCoords(int x, int y) {
int index = toIndex(x, y);
return isValidCoords(index);
}
/**
* Vérifie que l'index correspond bien à une Cell dans le Sudoku.
*
* @return boolean, valant true si l'index est dans les bornes du Sudoku, false
* sinon.
*/
public boolean isValidCoords(int index) {
return index < getSize() * getSize();
}
/**
* Teste si on peut placer la value dans la Cell aux coordonnées x, y d'après
* les contraintes du Sudoku.
*
* @param x int, abscisse de la Cell voulue.
* @param y int, ordonnée de la Cell voulue.
* @param value int, index du symbole qu'on veut placer.
* @return boolean, true si on peut la placer et false sinon.
*/
public boolean canBePlaced(int x, int y, int value) {
for (IConstraint constraint : this.constraints) {
if (!constraint.canBePlaced(this, x, y, value)) {
return false;
}
}
return true;
}
/**
* Vérifie si le Sudoku est résolue, soit complet et cohérent avec ses
* contraintes.
*
* @return boolean, valant true si le Sudoku est résolu, false sinon.
*/
public boolean isSolved() {
boolean isComplete = isComplete();
boolean isValid = isValid();
return isComplete && isValid;
}
/**
* Vérifie que le Sudoku est complet, soit qu'il n'y ait aucune case vide.
*
* @return boolean, true si le Sudoku est complet, false sinon.
*/
private boolean isComplete() {
return getFirstEmptyCell() == null;
}
/**
* Vérifie si le Sudoku est valide, soit qu'il est cohérent avec ses
* contraintes.
*
* @return bollean, true si le Sudoku est valide, false sinon
*/
private boolean isValid() {
for (int i = 0; i < cells.size(); i++) {
Cell cell = getCell(i);
if (cell.isEmpty())
continue;
Coordinate coordinate = toCoords(i);
int symbolPlaced = cell.empty();
if (!canBePlaced(coordinate.getX(), coordinate.getY(), symbolPlaced)) {
cell.setSymbolIndex(symbolPlaced);
return false;
}
cell.setSymbolIndex(symbolPlaced);
}
return true;
}
/**
* Renvoie la Cell aux coordonées données.
*
* @param x int, abscisse.
* @param y int, ordonnée.
* @return Cell, si une Cell existe aux coordonnées données, null sinon.
*/
public Cell getCell(int x, int y) {
int index = toIndex(x, y);
assert (isValidCoords(x, y));
try {
return this.cells.get(index);
} catch (IndexOutOfBoundsException e) {
return null;
}
}
/**
* Renvoie la 1re Cell vide du Sudoku.
*
* @return Cell, une Cell vide, ou null s'il n'y en a pas.
*/
public Cell getFirstEmptyCell() {
for (Cell cell : this.cells) {
if (cell.isEmpty()) {
return cell;
}
}
return null;
}
/**
* Place le symbole d'index value dans la Cell de coordonnées précisées.
*
* @param x int, abscisse de la Cell voulue.
* @param y int, coordonnée de la Cell voulue.
* @param value int, index du symbole à placer.
* @return Cell, la Cell qui a été modifiée.
*/
public Cell setCellSymbol(int x, int y, int value) {
assert (isValidCoords(x, y));
for (IConstraint constraint : this.constraints) {
if (!constraint.canBePlaced(this, x, y, value)) {
return null;
}
}
Cell cell = getCell(x, y);
cell.setSymbolIndex(value);
return cell;
}
/**
* Place les symboles d'index contenus dans values dans les cases du Sudoku.
*
* @param values List~Integer~, liste des index des symboles à placer.
* @return boolean, vaut true si les symboles ont été placés, false sinon.
*/
public boolean setCellsSymbol(List<Integer> values) {
if (values.size() > this.cells.size()) {
return false;
}
for (int i = 0; i < values.size(); i++) {
int x = i % this.blocks.size();
int y = (i - x) / this.blocks.size();
int value = values.get(i);
this.setCellSymbol(x, y, value);
}
return true;
}
/**
* Place les symboles d'index contenus dans values dans les cases du Sudoku et
* rend ces cases immuables.
*
* @param values List~Integer~, liste des index des symboles à placer.
* @return boolean, vaut true si les symboles ont été placés, false sinon.
*/
public boolean setImmutableCellsSymbol(List<Integer> values) {
if (values.size() > this.cells.size()) {
return false;
}
for (int i = 0; i < values.size(); i++) {
int x = i % this.blocks.size();
int y = (i - x) / this.blocks.size();
int value = values.get(i);
if (value != Cell.NOSYMBOL) {
Cell cellPlaced = this.setCellSymbol(x, y, value);
if (cellPlaced == null) {
continue;
}
cellPlaced.setImmutable();
}
}
return true;
}
public boolean hasConstraint(Constraint constraint) {
return this.constraints.contains(constraint.getConstraint());
}
public Cell getCell(int i) {
return this.cells.get(i);
}
public int getSize() {
return this.blocks.size();
}
public List<Cell> getCells() {
return this.cells;
}
public List<Block> getBlocks() {
return this.blocks;
}
public List<IConstraint> getConstraints() {
return constraints;
}
public int getBlockWidth() {
return blockWidth;
}
public void setBlockWidth(int blockWidth) {
this.blockWidth = blockWidth;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Sudoku {");
for (int i = 0; i < getSize(); i++) {
sb.append("\n\t");
for (int j = 0; j < getSize(); j++) {
Cell cell = getCell(i, j);
sb.append(cell.toString()).append(" ");
}
}
sb.append("\n}");
return sb.toString();
}
// <editor-fold defaultstate="collapsed" desc="METHODES">
}

View File

@@ -0,0 +1,371 @@
package sudoku.structure;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import sudoku.io.SudokuSerializer;
import sudoku.solver.RandomSolver;
import sudoku.solver.Solver;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class SudokuFactory {
/**
* Générateur de nombre aléatoire.
*/
private static final Random random = new Random();
/**
* Liste des contraintes par défaut d'un Multi- ou Sudoku.
* Comprend les contraintes de blocs, de lignes, et de colonnes.
*/
public static List<IConstraint> DEFAULT_CONSTRAINTS = SudokuFactory
.fromConstraints(Arrays.asList(
Constraint.Block,
Constraint.Column,
Constraint.Line)
);
/**
* Créée des Cells et les met dans une liste de taille size.
*
* @param size int, nombre de Cells à initialiser.
* @return List~Cell~, liste des Cells initialisées.
*/
private static List<Cell> initCells(int size) {
List<Cell> cells = new ArrayList<>(size * size);
for (int i = 0; i < size * size; i++) {
cells.add(new Cell());
}
return cells;
}
/**
* Créée des Blocks de taille width par height à partir des cellules données, et
* les met dans une liste.
*
* @param cells List~Cell~, liste des Cells à découper en Blocks.
* @param width int, largeur des Blocks à créer.
* @param height int, hauteur des Blocks à créer.
* @return List~Block~, liste des Blocks créés.
*/
private static List<Block> initRectangleBlocs(List<Cell> cells, int width, int height) {
List<Block> blocs = new ArrayList<>();
int size = width * height;
for (int i = 0; i < size; i++) {
Block newBlock = new Block();
int blockX = i % height;
int blockY = i / height;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int index = ((y + blockY * height) * size + (x + blockX * width));
Cell blockCell = cells.get(index);
blockCell.setBlock(newBlock);
newBlock.addCell(blockCell);
}
}
blocs.add(newBlock);
}
return blocs;
}
/**
* Créée un MultiDoku vide dont les Blocks sont de taille widthBlock par
* heightBlock.
*
* @param widthBlock int, largeur des Blocks.
* @param heightBlock int, hauteur des Blocks.
* @return MultiDoku, MultiDoku vide.
*/
public static MultiDoku createBasicEmptyRectangleDoku(int widthBlock, int heightBlock,
List<IConstraint> constraints) {
return new MultiDoku(List.of(createRectangleSudoku(widthBlock, heightBlock, constraints)));
}
/**
* Créée un MultiDoku vide dont les Blocks sont carrés de longueur size.
*
* @param size int, taille des Blocks.
* @return MultiDoku, MultiDoku vide.
*/
public static MultiDoku createBasicEmptySquareDoku(int size, List<IConstraint> constraints) {
return new MultiDoku(List.of(createSquareSudoku(size, constraints)));
}
/**
* Créée un Sudoku vide dont les Blocks sont de taille widthBlock par
* heightBlock.
*
* @param widthBlock int, largeur des Blocks.
* @param heightBlock int, hauteur des Blocks.
* @return Sudoku, Sudoku vide.
*/
private static Sudoku createRectangleSudoku(int widthBlock, int heightBlock, List<IConstraint> constraints) {
int symbolCount = widthBlock * heightBlock;
List<Cell> cases = initCells(symbolCount);
List<Block> blocs = initRectangleBlocs(cases, widthBlock, heightBlock);
Sudoku s = new Sudoku(cases, blocs, constraints);
for (Block block : s.getBlocks()) {
block.getSudokus().add(s);
}
s.setBlockWidth(widthBlock);
return s;
}
/**
* Créée un Sudoku vide dont les Blocks sont carrés de longueur size.
*
* @param size int, taille des Blocks.
* @return Sudoku, Sudoku vide.
*/
private static Sudoku createSquareSudoku(int size, List<IConstraint> constraints) {
return createRectangleSudoku(size, size, constraints);
}
/**
* Connecte deux Sudokus selon la décalage offset fourni.
*
* @param sudoku1 Sudoku, premier sudoku à connecter.
* @param sudoku2 Sudoku, second sudoku à connecter.
* @param offset Coordinate, décalage entre les deux Sudokus.
*/
private static void linkRectangleSudokus(Sudoku sudoku1, Sudoku sudoku2, Coordinate offset) {
int blockWidth = sudoku1.getBlockWidth();
int blockHeight = sudoku1.getSize() / blockWidth;
for (int dx = 0; dx < blockHeight; dx++) {
for (int dy = 0; dy < blockWidth; dy++) {
int block1X = dx + offset.getX();
int block1Y = dy + offset.getY();
int block2X = dx;
int block2Y = dy;
if ((block1X < blockHeight) && (block1X >= 0) && (block1Y >= 0) && (block1Y < blockWidth)) {
Block block1 = sudoku1.getBlocks().get(block1Y * blockHeight + block1X);
Block block2 = sudoku2.getBlocks().get(block2Y * blockHeight + block2X);
// on remplace le bloc
sudoku2.getBlocks().set(block2Y * blockHeight + block2X, block1);
block1.getSudokus().add(sudoku2);
// on remplace les cellules
for (int i = 0; i < block1.getCells().size(); i++) {
Cell newCell = block1.getCells().get(i);
Cell oldCell = block2.getCells().get(i);
int oldCellIndex = sudoku2.getCells().indexOf(oldCell);
sudoku2.getCells().set(oldCellIndex, newCell);
}
}
}
}
}
/**
* Créée un MultiDoku de Blocks carrés de taille size composé de cinq Sudokus,
* dont un central qui partage chacun de ses Blockss d'angle avec un autre
* Sudoku.
* 2 3
* 1
* 4 5
*
* @param size int, largeur des Blocks unitraires des Sudokus à crééer.
* @return MultiDoku, MultiDoku de forme X.
*/
public static MultiDoku createBasicXShapedMultidoku(int size, List<IConstraint> constraints) {
assert (size > 1);
return createBasicXShapedMultidoku(size, size, constraints);
}
/**
* Créée un MultiDoku de Blocks rectangulaires de forme X, de taille width par height composé
* de cinq Sudokus,
* dont un central qui partage chacun de ses Blocks d'angle avec un autre
* Sudoku.
* 2 3
* 1
* 4 5
*
* @param width int, largeur des Blocks unitaires des Sudokus à crééer.
* @param height int, hauteur des Blocks unitaires des Sudokus à crééer.
* @return MultiDoku, MultiDoku de forme X.
*/
public static MultiDoku createBasicXShapedMultidoku(int width, int height, List<IConstraint> constraints) {
assert (width > 1 && height > 1);
Sudoku sudoku1 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku2 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku3 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku4 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku5 = createRectangleSudoku(width, height, constraints);
linkRectangleSudokus(sudoku1, sudoku2, new Coordinate(1 - height, 1 - width));
linkRectangleSudokus(sudoku1, sudoku3, new Coordinate(height - 1, 1 - width));
linkRectangleSudokus(sudoku1, sudoku4, new Coordinate(1 - height, width - 1));
linkRectangleSudokus(sudoku1, sudoku5, new Coordinate(height - 1, width - 1));
return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5));
}
/**
* Créée un MultiDoku de Blocks carrés de forme +, de taille size composé
* de cinq Sudokus,
* dont un central qui partage chacun de ses Blocks de bord avec un autre
* Sudoku.
* 3
* 2 1 4
* 5
*
* @param size int, largeur des Blocks unitaires des Sudokus à crééer.
* @return MultiDoku, MultiDoku de forme +.
*/
public static MultiDoku createBasicPlusShapedMultidoku(int size, List<IConstraint> constraints) {
assert (size > 1);
return createBasicPlusShapedMultidoku(size, size, constraints);
}
/**
* Créée un MultiDoku de Blocks rectangulaires de forme +, de taille width par height composé
* de cinq Sudokus,
* dont un central qui partage chacun de ses Blocks de bord avec un autre
* Sudoku.
* 3
* 2 1 4
* 5
*
* @param width int, largeur des Blocks unitaires des Sudokus à crééer.
* @param height int, hauteur des Blocks unitaires des Sudokus à crééer.
* @return MultiDoku, MultiDoku de forme +.
*/
public static MultiDoku createBasicPlusShapedMultidoku(int width, int height, List<IConstraint> constraints) {
assert (width > 1 && height > 1);
Sudoku sudoku1 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku2 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku3 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku4 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku5 = createRectangleSudoku(width, height, constraints);
linkRectangleSudokus(sudoku1, sudoku2, new Coordinate(1 - height, 0));
linkRectangleSudokus(sudoku1, sudoku3, new Coordinate(0, 1 - width));
linkRectangleSudokus(sudoku1, sudoku4, new Coordinate(height - 1, 0));
linkRectangleSudokus(sudoku1, sudoku5, new Coordinate(0, width - 1));
return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5));
}
/**
* Crée un Sudoku vide avec les Blocks aléatoires.
*
* @param blockSize int, la taille des Block.
* @param constraints List~IConstraint~, la liste des contraintes.
* @return MultiDoku, avec un seul Sudoku.
*/
public static MultiDoku createBasicEmptyRandomBlockDoku(int blockSize, List<IConstraint> constraints) {
int blockCellCount = blockSize * blockSize;
List<Cell> cells = initCells(blockCellCount);
List<Cell> homeLessCells = new ArrayList<>(cells);
List<Block> blocks = new ArrayList<>();
Random r = new Random();
for (int i = 0; i < blockCellCount; i++) {
Block b = new Block();
for (int j = 0; j < blockCellCount; j++) {
int cellIndex = r.nextInt(homeLessCells.size());
Cell cell = homeLessCells.remove(cellIndex);
b.addCell(cell);
cell.setBlock(b);
}
blocks.add(b);
}
Sudoku sudoku = new Sudoku(cells, blocks, constraints);
for (Block block : blocks) {
block.getSudokus().add(sudoku);
}
return new MultiDoku(List.of(sudoku));
}
/**
* Créée un MultiDoku de difficulté difficulty à partir d'un MultiDoku fourni.
*
* @param doku MultiDoku, MultiDoku dont on doit vider des Cells.
* @param nbCellsToEmpty int, nombre de cases à retirer.
* @return boolean, valant true si un MultiDoku de difficulté donnée peut être
* créée, false sinon.
* @throws Exception si la difficulté n'est pas compatible avec la taille du
* MultiDoku.
*/
public static boolean newDokuFromFilledOne(MultiDoku doku, int nbCellsToEmpty, Solver solver) throws Exception {
if (nbCellsToEmpty >= doku.getCells().size()) {
throw new Exception();
}
if (nbCellsToEmpty == 0) {
return true;
}
List<Cell> cellsThatCanBeEmptied = doku.getFilledCells();
int index = random.nextInt(cellsThatCanBeEmptied.size());
Cell cellToEmpty = cellsThatCanBeEmptied.get(index);
cellToEmpty.empty();
int nbDokuSultions = solver.countSolution(doku);
if (nbDokuSultions == 1) {
return newDokuFromFilledOne(doku, --nbCellsToEmpty, solver);
}
return false;
}
/**
* Rempli un MultiDoku donné par rapport à un difficulté.
*
* @param doku MultiDoku, vide.
* @param difficulty Difficulty, qui correspond au pourcentage de cases à enlever.
*/
public static void fillDoku(MultiDoku doku, Difficulty difficulty) throws Exception {
Solver solver = new RandomSolver();
solver.solve(doku);
int nbCellsToEmpty = (int) (difficulty.getFactor() * doku.getNbCells());
newDokuFromFilledOne(doku, nbCellsToEmpty, solver);
doku.setFilledCellsImmutable();
}
/**
* Génère un MultiDoku à partir d'un fichier de sauvegarde.
*
* @param filePath String, chemin du fichier.
* @return MultiDoku.
*/
public static MultiDoku fromfile(String filePath) {
try {
String content = Files.readString(Paths.get(filePath));
return SudokuSerializer.deserializeSudoku(content);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Transforme des Constraints en IConstraints correspondants.
* @param constraints List~Constraints~
* @return List~IConstraints~
*/
public static List<IConstraint> fromConstraints(List<Constraint> constraints) {
List<IConstraint> iconstraints = new ArrayList<>();
for (Constraint cons : constraints) {
iconstraints.add(cons.getConstraint());
}
return iconstraints;
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 399 KiB

Binary file not shown.

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More