1 Commits

Author SHA1 Message Date
b87bd5183e create package org.polytech.ryuk
All checks were successful
Linux arm64 / Build (push) Successful in 31s
2025-02-01 14:47:46 +01:00
104 changed files with 1699 additions and 2595 deletions

View File

@@ -19,7 +19,7 @@ jobs:
uses: gradle/actions/setup-gradle@v4
- name: Build with Gradle
run: ./gradlew assemble
run: ./gradlew build
- name: Test
run: ./gradlew test

View File

Before

Width:  |  Height:  |  Size: 399 KiB

After

Width:  |  Height:  |  Size: 399 KiB

View File

@@ -11,6 +11,8 @@ plugins {
id 'application'
}
project.ext.os = System.properties['os.name'].toLowerCase().split(" ")[0]
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
@@ -18,8 +20,7 @@ repositories {
dependencies {
// Use JUnit Jupiter for testing.
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1'
implementation 'org.json:json:20250107'
@@ -27,14 +28,12 @@ dependencies {
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"
runtimeOnly "org.lwjgl:lwjgl-stb::natives-$os"
}
application {
// Define the main class for the application.
mainClass = 'gui.Main'
mainClass = 'org.polytech.ryuk.gui.Main'
}
// Add libraries into the final jar
@@ -49,10 +48,6 @@ jar {
}
}
test {
useJUnitPlatform()
}
run {
enableAssertions = true
}

View File

@@ -6,32 +6,24 @@
},
{
"blockID": 0,
"symbolIndex": -1
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 0,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"immutable": true,
"symbolIndex": 2
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 2,
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
@@ -39,9 +31,12 @@
"symbolIndex": -1
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 8
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 0,
@@ -52,244 +47,237 @@
"blockID": 0,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"immutable": true,
"symbolIndex": 0
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 0,
"symbolIndex": -1
},
{
"blockID": 0,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 4,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 4,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 4,
"immutable": true,
"symbolIndex": 0
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"immutable": true,
"symbolIndex": 7
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 7,
"symbolIndex": -1
},
{
"blockID": 7,
"symbolIndex": -1
},
{
"blockID": 7,
"symbolIndex": -1
},
{
"blockID": 8,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": 0
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 0,
"symbolIndex": -1
},
{
"blockID": 1,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"immutable": true,
"symbolIndex": 7
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 2
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 2
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 4,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"immutable": true,
"symbolIndex": 7
},
{
"blockID": 4,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 7,
"symbolIndex": -1
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 8,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 8,
"symbolIndex": -1
},
{
@@ -298,14 +286,49 @@
"symbolIndex": 6
},
{
"blockID": 8,
"blockID": 6,
"immutable": true,
"symbolIndex": 7
"symbolIndex": 1
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 7,
"symbolIndex": -1
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 6,
"immutable": true,
@@ -315,13 +338,10 @@
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 7,
"symbolIndex": -1
"immutable": true,
"symbolIndex": 7
},
{
"blockID": 7,
@@ -334,7 +354,7 @@
{
"blockID": 8,
"immutable": true,
"symbolIndex": 3
"symbolIndex": 1
},
{
"blockID": 8,
@@ -342,7 +362,8 @@
},
{
"blockID": 8,
"symbolIndex": -1
"immutable": true,
"symbolIndex": 8
}
],
"blocks": [

View File

@@ -1,10 +1,5 @@
{
"cells": [
{
"blockID": 0,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 0,
"symbolIndex": -1
@@ -12,44 +7,15 @@
{
"blockID": 0,
"immutable": true,
"symbolIndex": 6
"symbolIndex": 8
},
{
"blockID": 1,
"immutable": true,
"symbolIndex": 7
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"blockID": 0,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 0,
"symbolIndex": -1
},
{
"blockID": 0,
"symbolIndex": -1
},
{
"blockID": 0,
"blockID": 1,
"symbolIndex": -1
},
{
@@ -58,25 +24,25 @@
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 2
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 0,
"symbolIndex": -1
@@ -86,78 +52,78 @@
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 0,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"immutable": true,
"symbolIndex": 8
"symbolIndex": 5
},
{
"blockID": 2,
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"immutable": true,
"symbolIndex": 7
},
{
"blockID": 2,
"symbolIndex": -1
"immutable": true,
"symbolIndex": 2
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 3,
"blockID": 2,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 5,
"symbolIndex": -1
"symbolIndex": 4
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 1
"symbolIndex": 8
},
{
"blockID": 3,
@@ -166,11 +132,13 @@
},
{
"blockID": 3,
"symbolIndex": -1
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 4,
"symbolIndex": -1
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 4,
@@ -188,62 +156,112 @@
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"immutable": true,
"symbolIndex": 7
},
{
"blockID": 4,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"blockID": 5,
"immutable": true,
"symbolIndex": 0
},
{
"blockID": 4,
"symbolIndex": -1
"symbolIndex": 4
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 7,
"symbolIndex": -1
@@ -254,8 +272,9 @@
"symbolIndex": 1
},
{
"blockID": 7,
"symbolIndex": -1
"blockID": 8,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 8,
@@ -264,11 +283,12 @@
{
"blockID": 8,
"immutable": true,
"symbolIndex": 7
"symbolIndex": 6
},
{
"blockID": 8,
"symbolIndex": -1
"blockID": 6,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 6,
@@ -279,13 +299,10 @@
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 7,
"symbolIndex": -1
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 7,
@@ -314,7 +331,8 @@
},
{
"blockID": 6,
"symbolIndex": -1
"immutable": true,
"symbolIndex": 0
},
{
"blockID": 6,
@@ -323,17 +341,20 @@
{
"blockID": 7,
"immutable": true,
"symbolIndex": 4
"symbolIndex": 7
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 5
"symbolIndex": -1
},
{
"blockID": 7,
"symbolIndex": -1
},
{
"blockID": 8,
"immutable": true,
"symbolIndex": 0
"symbolIndex": 1
},
{
"blockID": 8,
@@ -341,11 +362,8 @@
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 8,
"symbolIndex": -1
"immutable": true,
"symbolIndex": 8
}
],
"blocks": [

View File

@@ -1,32 +0,0 @@
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

@@ -1,57 +0,0 @@
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

@@ -1,31 +0,0 @@
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

@@ -1,4 +1,4 @@
package common;
package org.polytech.ryuk.common;
import java.util.HashSet;
import java.util.Set;

View File

@@ -1,4 +1,4 @@
package common;
package org.polytech.ryuk.common;
import java.util.HashSet;
import java.util.Set;

View File

@@ -1,4 +1,4 @@
package game;
package org.polytech.ryuk.game;
import java.time.Instant;
import java.util.ArrayList;
@@ -7,7 +7,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
public class Game {

View File

@@ -1,4 +1,4 @@
package game;
package org.polytech.ryuk.game;
import java.io.Serializable;

View File

@@ -1,7 +1,5 @@
package gui.widget;
package org.polytech.ryuk.gui;
import gui.constants.Images;
import gui.constants.Options;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.flag.ImGuiWindowFlags;

View File

@@ -1,4 +1,4 @@
package gui;
package org.polytech.ryuk.gui;
import java.util.ArrayList;
import java.util.List;

View File

@@ -1,6 +1,5 @@
package gui.constants;
package org.polytech.ryuk.gui;
import gui.AssetManager;
import imgui.ImFont;
import imgui.ImFontConfig;
import imgui.ImFontGlyphRangesBuilder;
@@ -21,15 +20,15 @@ public class Fonts {
ImFontGlyphRangesBuilder builder = new ImFontGlyphRangesBuilder();
builder.addRanges(ImGui.getIO().getFonts().getGlyphRangesDefault());
builder.addRanges(ImGui.getIO().getFonts().getGlyphRangesCyrillic());
// builder.addRanges(ImGui.getIO().getFonts().getGlyphRangesChineseFull());
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);
COMIC = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "comic.ttf", 50.0f);
ARIAL_BOLD = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "arial_bold.ttf", 50.0f);
ARIAL = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "arial.ttf", 50.0f, cfg);
CHERI = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "cheri.ttf", 50.0f);
INFECTED = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "INFECTED.ttf", 50.0f);
}
}

View File

@@ -1,25 +1,20 @@
package gui.constants;
package org.polytech.ryuk.gui;
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) {
private static int loadTexture(String fileName) {
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);
ByteBuffer pixels = STBImage.stbi_load(fileName, width, height, channelCount, 4);
int textureID = GL11.glGenTextures();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
@@ -37,8 +32,8 @@ public class Images {
return textureID;
}
public static void reloadImages() {
BACKGROUND = loadTexture(AssetManager.getResource(Options.BackgroundPath));
public static void loadImages() {
BACKGROUND = loadTexture("background.png");
}
}

View File

@@ -1,9 +1,8 @@
package gui;
package org.polytech.ryuk.gui;
import org.polytech.ryuk.gui.menu.MainMenu;
import org.polytech.ryuk.gui.menu.StateMachine;
import gui.constants.Fonts;
import gui.constants.Images;
import gui.menu.MainMenu;
import gui.menu.StateMachine;
import imgui.app.Application;
import imgui.app.Configuration;
@@ -31,7 +30,7 @@ public class Main extends Application {
@Override
protected void preRun() {
super.preRun();
Images.reloadImages();
Images.loadImages();
}
@Override

View File

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

View File

@@ -1,15 +1,15 @@
package gui;
package org.polytech.ryuk.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;
import org.polytech.ryuk.sudoku.structure.Block;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.Coordinate;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
public class RenderableMultidoku {
@@ -47,6 +47,8 @@ public class RenderableMultidoku {
return cells.get(index);
}
private static record PositionConstraint(Sudoku sudoku1, Sudoku sudoku2, Coordinate offset) {
}

View File

@@ -1,10 +1,10 @@
package gui.constants;
package org.polytech.ryuk.gui;
import java.util.List;
import sudoku.constraint.IConstraint;
import sudoku.structure.MultiDoku;
import sudoku.structure.SudokuFactory;;
import org.polytech.ryuk.sudoku.constraint.Constraint;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.SudokuFactory;;
public enum SudokuType {
@@ -33,7 +33,7 @@ public enum SudokuType {
return this.displayName;
}
public MultiDoku createDoku(List<IConstraint> constraints, int... params) {
public MultiDoku createDoku(List<Constraint> constraints, int... params) {
return maker.makeSudoku(constraints, params);
}
@@ -43,7 +43,7 @@ public enum SudokuType {
@FunctionalInterface
private static interface SudokuMaker {
MultiDoku makeSudoku(List<IConstraint> constraints, int... params);
MultiDoku makeSudoku(List<Constraint> constraints, int... params);
}
private static final String[] dokuNames;

View File

@@ -1,4 +1,4 @@
package gui.constants;
package org.polytech.ryuk.gui;
import java.util.ArrayList;
import java.util.List;

View File

@@ -1,4 +1,4 @@
package gui.menu;
package org.polytech.ryuk.gui.menu;
import imgui.ImGui;

View File

@@ -1,11 +1,12 @@
package gui.menu;
package org.polytech.ryuk.gui.menu;
import java.io.IOException;
import java.net.UnknownHostException;
import org.polytech.ryuk.network.client.Client;
import org.polytech.ryuk.network.server.Server;
import imgui.ImGui;
import network.client.Client;
import network.server.Server;
public class ConnexionStatusView extends BaseView {
@@ -14,12 +15,12 @@ public class ConnexionStatusView extends BaseView {
private String displayText = "Connecting ...";
public ConnexionStatusView(StateMachine stateMachine, String pseudo, String address, short port)
public ConnexionStatusView(StateMachine stateMachine, String address, short port)
throws UnknownHostException, IOException {
super(stateMachine);
Thread t = new Thread(() -> {
try {
this.client = new Client(pseudo, address, port);
this.client = new Client(address, port);
bindListeners();
} catch (IOException e) {
e.printStackTrace();
@@ -29,13 +30,12 @@ public class ConnexionStatusView extends BaseView {
t.start();
}
public ConnexionStatusView(StateMachine stateMachine, String pseudo, short port)
throws UnknownHostException, IOException {
public ConnexionStatusView(StateMachine stateMachine, short port) throws UnknownHostException, IOException {
super(stateMachine);
Thread t = new Thread(() -> {
try {
this.server = new Server(port);
this.client = new Client(pseudo, "localhost", port);
this.client = new Client("localhost", port);
bindListeners();
} catch (IOException e) {
e.printStackTrace();

View File

@@ -1,11 +1,12 @@
package gui.menu;
package org.polytech.ryuk.gui.menu;
import org.polytech.ryuk.game.Player;
import org.polytech.ryuk.gui.ColorGenerator;
import org.polytech.ryuk.gui.widget.SudokuRenderer;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
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 {

View File

@@ -1,4 +1,4 @@
package gui.menu;
package org.polytech.ryuk.gui.menu;
import imgui.ImGui;
import imgui.ImVec2;

View File

@@ -1,7 +1,6 @@
package gui.menu;
package org.polytech.ryuk.gui.menu;
import java.io.IOException;
import java.util.Random;
import imgui.ImGui;
import imgui.ImVec2;
@@ -12,7 +11,6 @@ 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);
@@ -22,12 +20,10 @@ public class MultiMenu extends BaseView {
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);
ImGui.inputInt("Port", port);
if (ImGui.button("Créer")) {
try {
this.stateMachine.pushState(new ConnexionStatusView(stateMachine, pseudo.get(), (short) port.get()));
this.stateMachine.pushState(new ConnexionStatusView(stateMachine, (short) port.get()));
} catch (IOException e) {
e.printStackTrace();
}
@@ -39,13 +35,12 @@ public class MultiMenu extends BaseView {
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);
ImGui.inputInt("Port", port);
if (ImGui.button("Rejoindre")) {
try {
this.stateMachine.pushState(new ConnexionStatusView(stateMachine, address.get(), (short) port.get()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

View File

@@ -1,17 +1,18 @@
package gui.menu;
package org.polytech.ryuk.gui.menu;
import org.polytech.ryuk.game.Player;
import org.polytech.ryuk.gui.widget.LeaderboardRenderer;
import org.polytech.ryuk.gui.widget.MultiPlayerCompleteProgress;
import org.polytech.ryuk.gui.widget.SudokuRenderer;
import org.polytech.ryuk.gui.widget.TimerRenderer;
import org.polytech.ryuk.network.client.Client;
import org.polytech.ryuk.network.server.Server;
import org.polytech.ryuk.sudoku.solver.BacktrackingSolver;
import org.polytech.ryuk.sudoku.solver.Solver;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
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 {

View File

@@ -1,12 +1,13 @@
package gui.menu;
package org.polytech.ryuk.gui.menu;
import org.polytech.ryuk.game.Player;
import org.polytech.ryuk.gui.widget.SudokuSelector;
import org.polytech.ryuk.network.client.Client;
import org.polytech.ryuk.network.server.Server;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
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 {
@@ -68,8 +69,7 @@ public class MultiPlayerView extends BaseView {
}
private void renderTimer() {
if (ImGui.inputInt("Temps de la partie (minutes)", gameDurationMinutes))
gameDurationMinutes.set(Math.clamp(gameDurationMinutes.get(), 1, 90));
ImGui.inputInt("Temps de la partie (minutes)", gameDurationMinutes);
}
@Override
@@ -78,9 +78,4 @@ public class MultiPlayerView extends BaseView {
renderGameStatus();
}
@Override
public void cleanResources() {
this.selector.clean();
}
}

View File

@@ -0,0 +1,30 @@
package org.polytech.ryuk.gui.menu;
import org.polytech.ryuk.gui.Options;
import org.polytech.ryuk.gui.Symbols;
import imgui.ImGui;
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);
}
@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];
}
renderReturnButton();
}
}

View File

@@ -1,8 +1,9 @@
package gui.menu;
package org.polytech.ryuk.gui.menu;
import org.polytech.ryuk.gui.widget.SudokuSelector;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import gui.widget.SudokuSelector;
import imgui.ImGui;
import sudoku.structure.MultiDoku;
public class SoloMenu extends BaseView {
@@ -25,9 +26,4 @@ public class SoloMenu extends BaseView {
renderReturnButton();
}
@Override
public void cleanResources() {
this.sudokuSelector.clean();
}
}

View File

@@ -1,8 +1,9 @@
package gui.menu;
package org.polytech.ryuk.gui.menu;
import java.util.Stack;
import gui.widget.AnimatedBackground;
import org.polytech.ryuk.gui.AnimatedBackground;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.flag.ImGuiKey;

View File

@@ -1,21 +1,17 @@
package gui.menu;
package org.polytech.ryuk.gui.menu;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import gui.widget.SudokuRenderer;
import org.polytech.ryuk.gui.widget.SudokuRenderer;
import org.polytech.ryuk.sudoku.io.SudokuSerializer;
import org.polytech.ryuk.sudoku.solver.BacktrackingSolver;
import org.polytech.ryuk.sudoku.solver.HumanSolver;
import org.polytech.ryuk.sudoku.solver.MixedSolver;
import org.polytech.ryuk.sudoku.solver.Solver;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
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 {
@@ -25,8 +21,6 @@ public class SudokuView extends BaseView {
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);
@@ -75,28 +69,10 @@ public class SudokuView extends BaseView {
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);
solver.solve(this.doku);
} catch (CancellationException e) {
System.out.println("The user is bored !");
}
@@ -104,11 +80,6 @@ public class SudokuView extends BaseView {
});
}
private void renderResolvedText() {
if (this.resolved)
ImGui.text("Bravo !");
}
private void renderSolvePopup() {
if (ImGui.beginPopup("solve")) {
if (ImGui.button("Résoudre avec backtrace")) {
@@ -132,14 +103,16 @@ public class SudokuView extends BaseView {
ImGui.beginDisabled();
if (!this.resolved && centeredButton("Résoudre")) {
// beginSolve = true;
ImGui.openPopup("solve");
}
if (resolveThread != null)
ImGui.endDisabled();
renderResolvedText();
renderUnsolvableText();
if (this.resolved) {
ImGui.text("Bravo !");
}
renderSolvePopup();
}
@@ -156,19 +129,9 @@ public class SudokuView extends BaseView {
}
}
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();

View File

@@ -1,7 +1,8 @@
package gui.widget;
package org.polytech.ryuk.gui.widget;
import org.polytech.ryuk.game.Game;
import org.polytech.ryuk.game.Player;
import game.Game;
import game.Player;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.ImVec4;

View File

@@ -1,7 +1,8 @@
package gui.widget;
package org.polytech.ryuk.gui.widget;
import org.polytech.ryuk.game.Game;
import org.polytech.ryuk.game.Player;
import game.Game;
import game.Player;
import imgui.ImGui;
import imgui.ImVec2;

View File

@@ -1,4 +1,4 @@
package gui.widget;
package org.polytech.ryuk.gui.widget;
import imgui.ImGui;
import imgui.ImVec2;
@@ -9,22 +9,13 @@ public class SmoothProgressBar {
private final float speed = 2.0f;
private final float clipConstant = 0.001f;
private void updateProgress(float newProgress) {
float delta = newProgress - lastProgress;
public void render(String label, ImVec2 size, float progress) {
float delta = progress - lastProgress;
if (Math.abs(delta) < clipConstant)
lastProgress = newProgress;
lastProgress = progress;
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

@@ -1,4 +1,4 @@
package gui.widget;
package org.polytech.ryuk.gui.widget;
import java.util.HashMap;
import java.util.HashSet;
@@ -6,24 +6,25 @@ 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 org.polytech.ryuk.common.ConsumerSignal;
import org.polytech.ryuk.common.Signal;
import org.polytech.ryuk.gui.ColorGenerator;
import org.polytech.ryuk.gui.ColorGenerator.Color;
import org.polytech.ryuk.gui.Fonts;
import org.polytech.ryuk.gui.Options;
import org.polytech.ryuk.gui.RenderableMultidoku;
import org.polytech.ryuk.gui.Symbols;
import org.polytech.ryuk.sudoku.constraint.Constraint;
import org.polytech.ryuk.sudoku.structure.Block;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
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 {
@@ -84,8 +85,8 @@ public class SudokuRenderer {
}
} else {
if (ImGui.button(Options.Symboles.getSymbols().get(i), cellSize)) {
currentCell.setSymbolIndex(i);
this.onCellChange.emit(currentCell);
if (currentCell.trySetValue(i))
this.onCellChange.emit(currentCell);
if (this.doku.getDoku().isSolved())
this.onResolve.emit();
ImGui.closeCurrentPopup();
@@ -117,7 +118,6 @@ public class SudokuRenderer {
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);
@@ -142,7 +142,6 @@ public class SudokuRenderer {
currentCell = cell;
}
}
ImGui.endDisabled();
ImGui.popStyleColor(2);
}
}

View File

@@ -1,21 +1,20 @@
package gui.widget;
package org.polytech.ryuk.gui.widget;
import java.util.ArrayList;
import java.util.List;
import common.ConsumerSignal;
import gui.constants.SudokuType;
import org.polytech.ryuk.common.ConsumerSignal;
import org.polytech.ryuk.gui.SudokuType;
import org.polytech.ryuk.sudoku.constraint.Constraint;
import org.polytech.ryuk.sudoku.structure.Difficulty;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.SudokuFactory;
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;
import sudoku.structure.SudokuFiller;
public class SudokuSelector {
@@ -26,7 +25,7 @@ public class SudokuSelector {
private final ImInt sudokuType = new ImInt(0);
private final ImInt difficulty = new ImInt(Difficulty.Easy.ordinal());
private final ImInt difficulty = new ImInt(Difficulty.Medium.ordinal());
private final List<ImBoolean> contraints = new ArrayList<>();
private final ImInt sudokuSize = new ImInt(3);
@@ -36,66 +35,37 @@ public class SudokuSelector {
private final String confirmMessage;
private Thread genThread = null;
private final SmoothProgressBar genProgressBar;
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<>();
private List<Constraint> getConstraints() {
List<Constraint> constraints = new ArrayList<>();
for (int i = 0; i < this.contraints.size(); i++) {
if (this.contraints.get(i).get())
constraints.add(Constraint.values()[i].getConstraint());
constraints.add(Constraint.values()[i]);
}
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);
ImGui.endPopup();
} else {
stopGenThread();
contraints.add(new ImBoolean(SudokuFactory.DEFAULT_CONSTRAINTS.contains(cons)));
}
}
private void selectSudoku(MultiDoku doku, boolean empty) {
this.doku = doku;
ImGui.openPopup("genProgress");
this.genThread = new Thread(() -> {
if (!empty) {
try {
if (!empty) {
SudokuFiller.fillDoku(doku, Difficulty.values()[difficulty.get()]);
// SudokuFactory.fillDoku(doku, Difficulty.values()[difficulty.get()]);
}
this.onSelect.emit(this.doku);
SudokuFactory.fillDoku(doku, Difficulty.values()[difficulty.get()]);
} catch (Exception e) {
e.printStackTrace();
}
});
this.genThread.start();
}
this.onSelect.emit(this.doku);
}
public void renderFileDialog() {
@@ -129,8 +99,7 @@ public class SudokuSelector {
SudokuType currentType = SudokuType.values()[sudokuType.get()];
switch (currentType.getMakerParamCount()) {
case 1:
if (ImGui.inputInt("Taille", sudokuSize))
sudokuSize.set(Math.clamp(sudokuSize.get(), 1, 10));
ImGui.inputInt("Taille", sudokuSize);
if (ImGui.button(confirmMessage)) {
selectSudoku(currentType.createDoku(getConstraints(), sudokuSize.get()), false);
}
@@ -140,10 +109,8 @@ public class SudokuSelector {
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));
ImGui.inputInt("Largeur", sudokuHeight);
ImGui.inputInt("Longueur", sudokuWidth);
if (ImGui.button(confirmMessage)) {
selectSudoku(currentType.createDoku(getConstraints(), sudokuWidth.get(), sudokuHeight.get()),
false);
@@ -161,12 +128,7 @@ public class SudokuSelector {
if (ImGui.button("À partir d'un fichier")) {
ImGuiFileDialog.openDialog("browse-sudoku", "Choisissez un fichier", ".json", ".");
}
renderGenProgress();
renderFileDialog();
}
public void clean() {
stopGenThread();
}
}

View File

@@ -1,4 +1,4 @@
package gui.widget;
package org.polytech.ryuk.gui.widget;
import java.time.Instant;

View File

@@ -1,11 +1,11 @@
package network;
package org.polytech.ryuk.network;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.PacketVisitor;
public abstract class Connexion implements PacketVisitor {

View File

@@ -1,9 +1,9 @@
package network;
package org.polytech.ryuk.network;
import java.io.IOException;
import java.io.ObjectInputStream;
import network.protocol.Packet;
import org.polytech.ryuk.network.protocol.Packet;
public class ConnexionThread extends Thread {

View File

@@ -1,18 +1,18 @@
package network.client;
package org.polytech.ryuk.network.client;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Random;
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;
import org.polytech.ryuk.common.ConsumerSignal;
import org.polytech.ryuk.common.Signal;
import org.polytech.ryuk.game.Game;
import org.polytech.ryuk.game.Player;
import org.polytech.ryuk.network.protocol.packets.ChangeCellPacket;
import org.polytech.ryuk.network.protocol.packets.LoginPacket;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
public class Client {
private final ClientConnexion clientConnection;
@@ -28,10 +28,12 @@ public class Client {
String disconnectReason = null;
public Client(String pseudo, String address, short port) throws UnknownHostException, IOException {
public Client(String address, short port) throws UnknownHostException, IOException {
this.clientConnection = new ClientConnexion(address, port, this);
this.game = new Game();
login(pseudo);
// temp
Random r = new Random();
login("Player" + r.nextInt());
}
public void login(String pseudo) {

View File

@@ -1,22 +1,22 @@
package network.client;
package org.polytech.ryuk.network.client;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
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 org.polytech.ryuk.game.Player;
import org.polytech.ryuk.network.Connexion;
import org.polytech.ryuk.network.protocol.packets.ChangeCellPacket;
import org.polytech.ryuk.network.protocol.packets.ConnexionInfoPacket;
import org.polytech.ryuk.network.protocol.packets.DisconnectPacket;
import org.polytech.ryuk.network.protocol.packets.EndGamePacket;
import org.polytech.ryuk.network.protocol.packets.KeepAlivePacket;
import org.polytech.ryuk.network.protocol.packets.LoginPacket;
import org.polytech.ryuk.network.protocol.packets.PlayerJoinPacket;
import org.polytech.ryuk.network.protocol.packets.PlayerLeavePacket;
import org.polytech.ryuk.network.protocol.packets.StartGamePacket;
import org.polytech.ryuk.network.protocol.packets.UpdatePlayerScorePacket;
import org.polytech.ryuk.sudoku.io.SudokuSerializer;
public class ClientConnexion extends Connexion {

View File

@@ -1,4 +1,4 @@
package network.protocol;
package org.polytech.ryuk.network.protocol;
import java.io.Serializable;

View File

@@ -0,0 +1,31 @@
package org.polytech.ryuk.network.protocol;
import org.polytech.ryuk.network.protocol.packets.ChangeCellPacket;
import org.polytech.ryuk.network.protocol.packets.ConnexionInfoPacket;
import org.polytech.ryuk.network.protocol.packets.DisconnectPacket;
import org.polytech.ryuk.network.protocol.packets.EndGamePacket;
import org.polytech.ryuk.network.protocol.packets.KeepAlivePacket;
import org.polytech.ryuk.network.protocol.packets.LoginPacket;
import org.polytech.ryuk.network.protocol.packets.PlayerJoinPacket;
import org.polytech.ryuk.network.protocol.packets.PlayerLeavePacket;
import org.polytech.ryuk.network.protocol.packets.StartGamePacket;
import org.polytech.ryuk.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

@@ -1,4 +1,4 @@
package network.protocol;
package org.polytech.ryuk.network.protocol;
public enum Packets {

View File

@@ -1,8 +1,8 @@
package network.protocol.packets;
package org.polytech.ryuk.network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.PacketVisitor;
import org.polytech.ryuk.network.protocol.Packets;
public class ChangeCellPacket extends Packet {

View File

@@ -1,8 +1,8 @@
package network.protocol.packets;
package org.polytech.ryuk.network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.PacketVisitor;
import org.polytech.ryuk.network.protocol.Packets;
public class ConnexionInfoPacket extends Packet {

View File

@@ -1,8 +1,8 @@
package network.protocol.packets;
package org.polytech.ryuk.network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.PacketVisitor;
import org.polytech.ryuk.network.protocol.Packets;
public class DisconnectPacket extends Packet {

View File

@@ -1,8 +1,8 @@
package network.protocol.packets;
package org.polytech.ryuk.network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.PacketVisitor;
import org.polytech.ryuk.network.protocol.Packets;
public class EndGamePacket extends Packet {

View File

@@ -1,8 +1,8 @@
package network.protocol.packets;
package org.polytech.ryuk.network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.PacketVisitor;
import org.polytech.ryuk.network.protocol.Packets;
public class KeepAlivePacket extends Packet {

View File

@@ -1,8 +1,8 @@
package network.protocol.packets;
package org.polytech.ryuk.network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.PacketVisitor;
import org.polytech.ryuk.network.protocol.Packets;
public class LoginPacket extends Packet {

View File

@@ -1,9 +1,9 @@
package network.protocol.packets;
package org.polytech.ryuk.network.protocol.packets;
import game.Player;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
import org.polytech.ryuk.game.Player;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.PacketVisitor;
import org.polytech.ryuk.network.protocol.Packets;
public class PlayerJoinPacket extends Packet{

View File

@@ -1,8 +1,8 @@
package network.protocol.packets;
package org.polytech.ryuk.network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.PacketVisitor;
import org.polytech.ryuk.network.protocol.Packets;
public class PlayerLeavePacket extends Packet{

View File

@@ -1,10 +1,10 @@
package network.protocol.packets;
package org.polytech.ryuk.network.protocol.packets;
import java.time.Instant;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.PacketVisitor;
import org.polytech.ryuk.network.protocol.Packets;
public class StartGamePacket extends Packet {

View File

@@ -1,8 +1,8 @@
package network.protocol.packets;
package org.polytech.ryuk.network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.PacketVisitor;
import org.polytech.ryuk.network.protocol.Packets;
public class UpdatePlayerScorePacket extends Packet {

View File

@@ -1,8 +1,8 @@
package network.server;
package org.polytech.ryuk.network.server;
import java.util.Random;
import network.protocol.packets.KeepAlivePacket;
import org.polytech.ryuk.network.protocol.packets.KeepAlivePacket;
public class KeepAliveHandler {

View File

@@ -1,4 +1,4 @@
package network.server;
package org.polytech.ryuk.network.server;
import java.io.IOException;
import java.net.ServerSocket;
@@ -6,14 +6,14 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import game.Game;
import game.Player;
import game.Game.GameState;
import network.protocol.Packet;
import network.protocol.packets.EndGamePacket;
import network.protocol.packets.StartGamePacket;
import sudoku.io.SudokuSerializer;
import sudoku.structure.MultiDoku;
import org.polytech.ryuk.game.Game;
import org.polytech.ryuk.game.Game.GameState;
import org.polytech.ryuk.game.Player;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.packets.EndGamePacket;
import org.polytech.ryuk.network.protocol.packets.StartGamePacket;
import org.polytech.ryuk.sudoku.io.SudokuSerializer;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
public class Server {

View File

@@ -1,4 +1,4 @@
package network.server;
package org.polytech.ryuk.network.server;
import java.io.IOException;
import java.net.Socket;

View File

@@ -1,25 +1,25 @@
package network.server;
package org.polytech.ryuk.network.server;
import java.io.IOException;
import java.net.Socket;
import game.Game;
import game.Player;
import game.Game.GameState;
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;
import org.polytech.ryuk.game.Game;
import org.polytech.ryuk.game.Game.GameState;
import org.polytech.ryuk.game.Player;
import org.polytech.ryuk.network.Connexion;
import org.polytech.ryuk.network.protocol.packets.ChangeCellPacket;
import org.polytech.ryuk.network.protocol.packets.ConnexionInfoPacket;
import org.polytech.ryuk.network.protocol.packets.DisconnectPacket;
import org.polytech.ryuk.network.protocol.packets.EndGamePacket;
import org.polytech.ryuk.network.protocol.packets.KeepAlivePacket;
import org.polytech.ryuk.network.protocol.packets.LoginPacket;
import org.polytech.ryuk.network.protocol.packets.PlayerJoinPacket;
import org.polytech.ryuk.network.protocol.packets.PlayerLeavePacket;
import org.polytech.ryuk.network.protocol.packets.StartGamePacket;
import org.polytech.ryuk.network.protocol.packets.UpdatePlayerScorePacket;
import org.polytech.ryuk.sudoku.io.SudokuSerializer;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
public class ServerConnexion extends Connexion {

View File

@@ -1,4 +1,4 @@
package network.server;
package org.polytech.ryuk.network.server;
public class ServerLogicThread extends Thread {

View File

@@ -0,0 +1,17 @@
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package org.polytech.ryuk.sudoku;
import org.polytech.ryuk.sudoku.io.ConsoleInterface;
public class Main {
public String getGreeting() {
return "Hello World!";
}
public static void main(String[] args) {
ConsoleInterface console = new ConsoleInterface();
console.start();
}
}

View File

@@ -1,7 +1,7 @@
package sudoku.constraint;
package org.polytech.ryuk.sudoku.constraint;
import sudoku.structure.Block;
import sudoku.structure.Sudoku;
import org.polytech.ryuk.sudoku.structure.Block;
import org.polytech.ryuk.sudoku.structure.Sudoku;
public class BlockConstraint implements IConstraint{

View File

@@ -1,7 +1,7 @@
package sudoku.constraint;
package org.polytech.ryuk.sudoku.constraint;
import sudoku.structure.Cell;
import sudoku.structure.Sudoku;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.Sudoku;
public class ColumnConstraint implements IConstraint {

View File

@@ -1,8 +1,8 @@
package sudoku.constraint;
package org.polytech.ryuk.sudoku.constraint;
import java.util.List;
import sudoku.structure.Sudoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
public enum Constraint {

View File

@@ -1,6 +1,6 @@
package sudoku.constraint;
package org.polytech.ryuk.sudoku.constraint;
import sudoku.structure.Sudoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
public class DiagonalConstraint implements IConstraint {

View File

@@ -1,12 +1,12 @@
package sudoku.constraint;
package org.polytech.ryuk.sudoku.constraint;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import sudoku.structure.Sudoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
public interface IConstraint {
public interface IConstraint extends Serializable {
boolean canBePlaced(final Sudoku s, int x, int y, int newSymbolIndex);
default List<Integer> getPossibleSymbols(final Sudoku s, int x, int y) {

View File

@@ -1,6 +1,6 @@
package sudoku.constraint;
package org.polytech.ryuk.sudoku.constraint;
import sudoku.structure.Sudoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
public class LineConstraint implements IConstraint {

View File

@@ -0,0 +1,138 @@
package org.polytech.ryuk.sudoku.io;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.polytech.ryuk.sudoku.constraint.Constraint;
import org.polytech.ryuk.sudoku.solver.RandomSolver;
import org.polytech.ryuk.sudoku.structure.Difficulty;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
import org.polytech.ryuk.sudoku.structure.SudokuFactory;
public class ConsoleInterface {
public Scanner reader = new Scanner(System.in);
public void start(){
welcome();
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;
System.out.println("Would you like to pick the " + numberOfSymbols + " symbols from the sudoku? (y/n, default 'no' will use numbers)" );
List<String> listSymbols = new ArrayList<>();
if(reader.next().equalsIgnoreCase("y")){
pickSymbols(listSymbols, numberOfSymbols);
}
else {
// TODO
System.out.println("Simon doit finir sa partie.");
assert false;
}
List<Constraint> 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') ?");
List<Sudoku> subGrids = new ArrayList<>();
MultiDoku doku;
if (reader.next().equalsIgnoreCase("multi")) {
doku = SudokuFactory.createBasicEmptyRectangleDoku(width, height, listConstraints);
}
else {
doku = SudokuFactory.createBasicXShapedMultidoku(width, height, listConstraints);
}
System.out.println("Your sudoku will look like this:");
// TODO printMultiDoku method not yet implemented
SudokuPrinter.printMultiDoku(doku, width, height);
System.out.println("We now will 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);
}
else {
generatePartialDoku(doku, difficulty);
}
System.out.println("Here's your sudoku !");
SudokuPrinter.printMultiDoku(doku, width, height);
}
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 Priblyski.");
}
public 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;
}
public 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;
}
private Boolean checkValidSize(int size) {
return (size > 0);
}
private void pickSymbols(List<String> listSymbols, int numberOfSymbols) {
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());
}
private List<Constraint> getListConstraints() {
List<Constraint> 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);
}
return listConstraints;
}
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.");
}
}
private void generateFullDoku(MultiDoku doku) {
new RandomSolver().solve(doku);
}
}

View File

@@ -0,0 +1,7 @@
package org.polytech.ryuk.sudoku.io;
public class SudokuFile {
}

View File

@@ -0,0 +1,51 @@
package org.polytech.ryuk.sudoku.io;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
public class SudokuPrinter {
public static void printRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight) {
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(" ");
if (x % blockWidth == blockWidth - 1 && x != blockWidth * blockHeight - 1) {
line.append("| ");
}
}
line.append("]");
System.out.println(line);
}
}
public static String toStringRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight) {
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
line.append((s.getCell(x, y).getSymbolIndex() + 1)).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){
// TODO
}
}

View File

@@ -1,4 +1,4 @@
package sudoku.io;
package org.polytech.ryuk.sudoku.io;
public class SudokuSave {

View File

@@ -1,4 +1,4 @@
package sudoku.io;
package org.polytech.ryuk.sudoku.io;
import java.io.File;
import java.io.FileWriter;
@@ -10,13 +10,11 @@ import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import sudoku.structure.Block;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
import org.polytech.ryuk.sudoku.constraint.Constraint;
import org.polytech.ryuk.sudoku.structure.Block;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
public class SudokuSerializer {
@@ -45,7 +43,7 @@ public class SudokuSerializer {
}
int blockID = blockIds.indexOf(block);
assert (blockID >= 0);
assert(blockID >= 0);
int symbolIndex = cell.getSymbolIndex();
JSONObject cellJsonObject = new JSONObject();
@@ -100,17 +98,8 @@ public class SudokuSerializer {
// 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é !");
}
for (Constraint cons : sudoku.getConstraints()) {
constraintsJsonArray.put(cons.ordinal());
}
jsonSudoku.put("constraints", constraintsJsonArray);
@@ -134,14 +123,17 @@ public class SudokuSerializer {
* @return String, the path of the save.
*/
public static String saveMultiDoku(final MultiDoku doku) {
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) {
@@ -150,25 +142,6 @@ public class SudokuSerializer {
return f.getAbsolutePath();
}
public static String saveMultiDoku(final MultiDoku doku, final int saveToOverwrite) {
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.
*
@@ -243,7 +216,7 @@ public class SudokuSerializer {
List<Cell> sudokuCells = new ArrayList<>();
List<Block> sudokuBlocks = new ArrayList<>();
List<IConstraint> sudokuConstraints = new ArrayList<>();
List<Constraint> sudokuConstraints = new ArrayList<>();
for (int j = 0; j < sudokuCellsJsonArray.length(); j++) {
int cellID = sudokuCellsJsonArray.getInt(j);
@@ -257,7 +230,7 @@ public class SudokuSerializer {
for (int j = 0; j < sudokuConstraintsJsonArray.length(); j++) {
int constraintID = sudokuConstraintsJsonArray.getInt(j);
sudokuConstraints.add(Constraint.values()[constraintID].getConstraint());
sudokuConstraints.add(Constraint.values()[constraintID]);
}
Sudoku s = new Sudoku(sudokuCells, sudokuBlocks, sudokuConstraints);

View File

@@ -1,10 +1,10 @@
package sudoku.solver;
package org.polytech.ryuk.sudoku.solver;
import java.util.List;
import java.util.concurrent.CancellationException;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
public class BacktrackingSolver implements Solver {
@@ -15,7 +15,7 @@ public class BacktrackingSolver implements Solver {
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
*/
@Override
public boolean solve(MultiDoku doku, List<SolverStep> steps) {
public boolean solve(MultiDoku doku) {
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
@@ -34,14 +34,14 @@ public class BacktrackingSolver implements Solver {
}
for (int symbol : possibleSymbols) {
cellToFill.setSymbolIndex(symbol);
addStep(cellToFill, steps);
if (this.solve(doku, steps)) {
if (this.solve(doku)) {
return true;
} else {
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
addStep(cellToFill, steps);
}
}
return false;
}

View File

@@ -0,0 +1,55 @@
package org.polytech.ryuk.sudoku.solver;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import org.polytech.ryuk.sudoku.io.SudokuPrinter;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
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) {
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
Sudoku sudoku = doku.getSubGrid(0);
logger.log(Level.FINE,
'\n' + SudokuPrinter.toStringRectangleSudoku(sudoku,
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getBlockWidth(),
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getSize() / sudoku.getBlockWidth()));
if (doku.isSolved()) {
return true;
}
List<Cell> cellsToFill = doku.getEmptyCells();
if (cellsToFill.isEmpty()) {
return false;
}
for (Cell cellToFill : cellsToFill) {
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
if (possibleSymbols.size() != 1) {
continue;
}
cellToFill.setSymbolIndex(possibleSymbols.getFirst());
return this.solve(doku);
}
return doku.isSolved();
}
}

View File

@@ -0,0 +1,71 @@
package org.polytech.ryuk.sudoku.solver;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import org.polytech.ryuk.sudoku.io.SudokuPrinter;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
public class MixedSolver implements Solver{
/**
* 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) {
Random rand = new Random();
if (Thread.interrupted()) {
throw new CancellationException("User wants to stop the solver");
}
Sudoku sudoku = doku.getSubGrid(0);
logger.log(Level.FINE,
'\n' + SudokuPrinter.toStringRectangleSudoku(
sudoku,
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getBlockWidth(),
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getSize() / sudoku.getBlockWidth()));
if (doku.isSolved()) {
return true;
}
Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) {
return false;
}
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
if (possibleSymbols.size() == 1) {
cellToFill.setSymbolIndex(possibleSymbols.getFirst());
if (this.solve(doku)) {
return true;
}
}
while (!possibleSymbols.isEmpty()) {
int nextPossibleSymbolIndex = rand.nextInt(possibleSymbols.size());
int nextSymbol = possibleSymbols.get(nextPossibleSymbolIndex);
cellToFill.setSymbolIndex(nextSymbol);
if (this.solve(doku)) {
return true;
}
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
possibleSymbols.remove(nextPossibleSymbolIndex);
}
return false;
}
}

View File

@@ -1,29 +1,39 @@
package sudoku.solver;
package org.polytech.ryuk.sudoku.solver;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.io.SudokuPrinter;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
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
* @param rand Random, pour tester aléatoirement les symboles
* @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) {
@Override
public boolean solve(MultiDoku doku) {
Random rand = new Random();
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
Sudoku sudoku = doku.getSubGrid(0);
logger.log(Level.FINE,
'\n' + SudokuPrinter.toStringRectangleSudoku(sudoku,
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getBlockWidth(),
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getSize() / sudoku.getBlockWidth()));
if (doku.isSolved()) {
return true;
}
@@ -40,12 +50,10 @@ public class RandomSolver implements Solver {
int nextSymbol = possibleSymbols.get(nextPossibleSymbolIndex);
cellToFill.setSymbolIndex(nextSymbol);
addStep(cellToFill, steps);
if (this.solve(doku, steps)) {
if (this.solve(doku)) {
return true;
}
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
addStep(cellToFill, steps);
possibleSymbols.remove(nextPossibleSymbolIndex);
}

View File

@@ -1,25 +1,21 @@
package sudoku.solver;
package org.polytech.ryuk.sudoku.solver;
import java.util.List;
import java.util.logging.Logger;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
public interface Solver {
/**
/**
* 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);
boolean solve(MultiDoku doku);
default boolean solve(MultiDoku doku) {
return solve(doku, null);
}
/**
/**
* Compte le nombre de solutions possibles au MultiDoku passé en paramètres.
*
* @param doku MultiDoku, MultiDoku dont on veut le nombre de solutions.
@@ -42,20 +38,10 @@ public interface Solver {
cellToFill.setSymbolIndex(symbol);
if (solve(doku)) {
result++;
if (result > 1) {
doku.getStateManager().popState();
return result;
}
}
doku.getStateManager().popState();
}
return result;
}
default void addStep(Cell cell, List<SolverStep> steps) {
if (steps == null)
return;
steps.add(new SolverStep(cell));
}
}

View File

@@ -1,17 +1,16 @@
package sudoku.solver;
package org.polytech.ryuk.sudoku.solver;
import java.util.List;
import java.util.concurrent.CancellationException;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
/**
* Class de test non utilisé
*/
public class StupidSolver implements Solver{
public class StupidSolver {
private boolean solve(Sudoku sudoku, int index, List<SolverStep> steps) {
private static boolean solve(Sudoku sudoku, int index) {
// mécanisme d'abandon
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
@@ -22,30 +21,27 @@ public class StupidSolver implements Solver{
// si la case n'est pas modifiable, on passe à la suivante
if (!sudoku.getCell(index).isMutable())
return solve(sudoku, index + 1, steps);
return solve(sudoku, index + 1);
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)) {
if (solve(sudoku, index + 1)) {
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) {
public static boolean solve(MultiDoku doku) {
if (doku.isSolved())
return true;
for (Sudoku sudoku : doku.getSubGrids()) {
if (!solve(sudoku, 0, steps))
if (!solve(sudoku, 0))
return false;
}
return true;

View File

@@ -1,44 +1,31 @@
package sudoku.structure;
package org.polytech.ryuk.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é.
* 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.
* 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.
* List de sudoku qui contiennent le block
* Pour un acces 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<>());
}
@@ -46,16 +33,13 @@ public class Block {
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) {
void addCell(Cell newCell) {
this.cells.add(newCell);
}
@@ -73,5 +57,16 @@ public class Block {
return false;
}
// </editor-fold>
public boolean containsCell(Cell cell) {
for (Cell cellTmp : this.cells) {
if (cellTmp.equals(cell)) {
return true;
}
}
return false;
}
public List<Sudoku> getSudokus() {
return sudokus;
}
}

View File

@@ -1,4 +1,4 @@
package sudoku.structure;
package org.polytech.ryuk.sudoku.structure;
import java.util.ArrayList;
import java.util.List;
@@ -9,8 +9,6 @@ import java.util.List;
*/
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.
@@ -31,10 +29,6 @@ public class Cell {
*/
private boolean isMutable = true;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="METHODES">
public Cell() {
this(Cell.NOSYMBOL);
}
@@ -52,22 +46,6 @@ public class Cell {
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;
}
@@ -79,16 +57,22 @@ public class Cell {
this.isMutable = false;
}
public Block getBlock() {
return this.blockContainer;
}
public void setBlock(Block block) {
this.blockContainer = block;
}
/**
* Vide la Cell.
* Remove the current symbolIndex and returns it
* @return integer symbolIndex cleared
*/
public void clearCurrentSymbol() {
public int clearCurrentSymbol() {
int i = this.symbolIndex;
setSymbolIndex(NOSYMBOL);
return i;
}
/**
@@ -99,6 +83,14 @@ public class Cell {
return this.symbolIndex == Cell.NOSYMBOL;
}
/**
* Renvoie si la Cell est modifiable
* @return boolean, true si elle est modifiable ou false sinon.
*/
public boolean isMutable() {
return this.isMutable;
}
/**
* Vide la Cell, en renvoie l'ancien index du symbole qui était dedans.
* @return int, index du symbole anciennement contenue dans la Cell.
@@ -109,11 +101,6 @@ public class Cell {
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);
@@ -129,10 +116,6 @@ public class Cell {
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++) {
@@ -142,11 +125,6 @@ public class Cell {
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;
@@ -155,6 +133,4 @@ public class Cell {
setSymbolIndex(newValue);
return true;
}
// </editor-fold>
}

View File

@@ -1,12 +1,10 @@
package sudoku.structure;
package org.polytech.ryuk.sudoku.structure;
/**
* Représente les coordonnées d'une Cell.
* Représente les coordonnées d'une Cell
*/
public class Coordinate {
// <editor-fold defaultstate="collapsed" desc="ATTRIBUTS">
/**
* L'abscisse de la Cell.
*/
@@ -16,10 +14,6 @@ public class Coordinate {
*/
private int y;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="METHODES">
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
@@ -41,23 +35,16 @@ public class Coordinate {
this.y = y;
}
/**
* Ajoute la Coordiante donnée à celle-ci.
* @param other Coordiante, à ajouter.
* @return Coordinate, le résultat de l'addition.
*/
public int calculateIndex(int size) {
return this.y * size + this.x;
}
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

@@ -1,32 +1,26 @@
package sudoku.structure;
package org.polytech.ryuk.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.
*/
//TODO: melvyn va passer par
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);
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) {
private Difficulty(String displayName, double factor) {
this.factor = factor;
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
public double getFactor() {
return factor;
}
private static final String[] difficultyNames;
static {
@@ -37,14 +31,6 @@ public enum Difficulty {
}
}
public String getDisplayName() {
return displayName;
}
public double getFactor() {
return factor;
}
public static String[] getDifficultyNames() {
return difficultyNames;
}

View File

@@ -1,45 +1,89 @@
package sudoku.structure;
import sudoku.io.SudokuSerializer;
package org.polytech.ryuk.sudoku.structure;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.polytech.ryuk.sudoku.io.SudokuSerializer;
/**
* @class MultiDoku
* @brief Représente une grille de Multidoku.
* Une grille de sudoku est un multidoku avec un seul sous-sudoku.
* 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.
* Renvoie le nombre de sudoku contenu dans ce MultiDoku.
*
* @return boolean, true s'il est résolu et false sinon.
* @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);
}
@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();
}
/**
* Renvoie les sous-Sudoku
*
* @return List<Sudoku>
*/
public List<Sudoku> getSubGrids() {
return this.subGrids;
}
/**
* Check si le MultiDoku est valide, en fonction de ses sous-Sudokus.
*
* @return boolean, true s'il est valide et false sinon.
*/
public boolean isSolved() {
for (Sudoku sudoku : this.subGrids) {
@@ -49,6 +93,21 @@ public class MultiDoku {
return true;
}
/**
* 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 la liste des Cells préalablement remplies du MultiDoku.
*
@@ -80,51 +139,14 @@ public class MultiDoku {
}
/**
* Renvoie la 1re Cell vide des sous-Sudoku.
*
* @return Cell, une Cell vide, ou null s'il n'y en a pas.
* Vide une Cell donnée.
*
* @param cell Cell, à vider.
*/
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);
public void empty(Cell cell) {
List<Cell> cells = getCells();
Cell cellToEmpty = cells.get(cells.indexOf(cell));
cellToEmpty.setSymbolIndex(Cell.NOSYMBOL);
}
/**
@@ -145,9 +167,22 @@ public class MultiDoku {
}
}
public StateManager getStateManager() {
return stateManager;
}
/**
* Vide les Cells modifiable.
* Renvoie une Cell vide choisie aléatoirement.
*
* @param rand Random, pour le choix aléatoire.
* @return Cell, une Cell vide.
*/
public Cell getRandomEmptyCell(Random rand) {
List<Cell> emptyCells = getEmptyCells();
int randomIndex = rand.nextInt(emptyCells.size());
return emptyCells.get(randomIndex);
}
public void clearMutableCells() {
for (Sudoku s : getSubGrids()) {
for (Cell cell : s.getCells()) {
@@ -157,53 +192,8 @@ public class MultiDoku {
}
}
/**
* 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() {
// TODO: C'est pas dingue de le faire comme ça...
//TODO: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah
return SudokuSerializer.deserializeSudoku(SudokuSerializer.serializeSudoku(this));
}
// </editor-fold>
}

View File

@@ -0,0 +1,41 @@
package org.polytech.ryuk.sudoku.structure;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
//TODO: doc
public class StateManager {
private final Stack<Map<Cell, Integer>> states;
private final MultiDoku doku;
public StateManager(MultiDoku doku) {
this.states = new Stack<>();
this.doku = doku;
}
public void pushState() {
states.add(new HashMap<>());
saveState();
}
public void popState() {
assert (states.size() > 0);
restoreState();
states.pop();
}
private void restoreState() {
for (var entry : this.states.getLast().entrySet()) {
entry.getKey().setSymbolIndex(entry.getValue());
}
}
private void saveState() {
for (Cell cell : this.doku.getCells()) {
states.getLast().put(cell, cell.getSymbolIndex());
}
}
}

View File

@@ -1,10 +1,9 @@
package sudoku.structure;
package org.polytech.ryuk.sudoku.structure;
import java.util.ArrayList;
import java.util.List;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import org.polytech.ryuk.sudoku.constraint.Constraint;
/**
* @class Sudoku
@@ -12,34 +11,24 @@ import sudoku.constraint.IConstraint;
*/
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;
private List<Cell> cells = new ArrayList<>();
/**
* Liste des contraintes (TODO) du Sudoku.
*/
private final List<IConstraint> constraints;
private final List<Constraint> constraints;
/**
* Largeur des Blocks s'ils sont rectangulaires,
* valant 0 si ce n'est pas le cas.
* 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) {
public Sudoku(List<Cell> cells, List<Block> blocks, List<Constraint> constraints) {
this.cells = cells;
this.blocks = blocks;
this.constraints = constraints;
@@ -57,7 +46,6 @@ public class Sudoku {
/**
* Transforme des coordonées d'une Cell en index.
*
* @param x int, abscisse.
* @param y int, ordonnée.
* @return int, index correspondant.
@@ -68,9 +56,7 @@ public class Sudoku {
/**
* 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.
* @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);
@@ -79,25 +65,21 @@ public class Sudoku {
/**
* 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.
* @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.
*
* 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) {
for (Constraint constraint : this.constraints) {
if (!constraint.canBePlaced(this, x, y, value)) {
return false;
}
@@ -106,84 +88,34 @@ public class Sudoku {
}
/**
* 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.
* Vide la Cell dotn les coordonnées sont renseignées de son symbole.
* @param x int, abscisse de la Cell voulue.
* @param y int, coordonnée de la Cell voulue.
*/
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);
public void clearCell(int x, int y) {
assert (isValidCoords(x, y));
try {
return this.cells.get(index);
} catch (IndexOutOfBoundsException e) {
return null;
}
Cell cell = getCell(x, y);
cell.setSymbolIndex(Cell.NOSYMBOL);
}
/**
* Renvoie la 1re Cell vide du Sudoku.
*
* @return Cell, une Cell vide, ou null s'il n'y en a pas.
* Vide toutes les Cell du Sudoku.
*/
public Cell getFirstEmptyCell() {
for (Cell cell : this.cells) {
if (cell.isEmpty()) {
return cell;
}
public void clear() {
for (int i = 0; i < getSize() * getSize(); i++) {
Cell cell = getCell(i);
if (cell.isMutable())
cell.setSymbolIndex(Cell.NOSYMBOL);
}
return null;
}
public int getBlockWidth() {
return blockWidth;
}
/**
* 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.
@@ -191,7 +123,7 @@ public class Sudoku {
*/
public Cell setCellSymbol(int x, int y, int value) {
assert (isValidCoords(x, y));
for (IConstraint constraint : this.constraints) {
for (Constraint constraint : this.constraints) {
if (!constraint.canBePlaced(this, x, y, value)) {
return null;
}
@@ -203,7 +135,6 @@ public class Sudoku {
/**
* 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.
*/
@@ -221,9 +152,7 @@ public class Sudoku {
}
/**
* Place les symboles d'index contenus dans values dans les cases du Sudoku et
* rend ces cases immuables.
*
* 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.
*/
@@ -246,14 +175,24 @@ public class Sudoku {
return true;
}
public boolean hasConstraint(Constraint constraint) {
return this.constraints.contains(constraint.getConstraint());
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;
}
}
public Cell getCell(int i) {
return this.cells.get(i);
}
public List<Constraint> getConstraints() {
return constraints;
}
public int getSize() {
return this.blocks.size();
}
@@ -266,19 +205,15 @@ public class Sudoku {
return this.blocks;
}
public List<IConstraint> getConstraints() {
return constraints;
/**
* Vérifie si une Cell appartient au Sudoku.
* @param cell Cell, cellule dont on veut vérifier l'appartenance au Sudoku.
* @return boolean, vaut true si la Cell appartient au Sudoku.
*/
public boolean contains(Cell cell) {
return this.cells.contains(cell);
}
public int getBlockWidth() {
return blockWidth;
}
public void setBlockWidth(int blockWidth) {
this.blockWidth = blockWidth;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Sudoku {");
@@ -293,6 +228,65 @@ public class Sudoku {
return sb.toString();
}
// <editor-fold defaultstate="collapsed" desc="METHODES">
/**
* 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;
}
/**
* 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;
}
public void setBlockWidth(int blockWidth) {
this.blockWidth = blockWidth;
}
public boolean hasConstraint(Constraint constraint) {
return this.constraints.contains(constraint);
}
}

View File

@@ -1,4 +1,4 @@
package sudoku.structure;
package org.polytech.ryuk.sudoku.structure;
import java.io.IOException;
import java.nio.file.Files;
@@ -9,11 +9,10 @@ import java.util.List;
import java.util.Map;
import java.util.Random;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import sudoku.io.SudokuSerializer;
import sudoku.solver.RandomSolver;
import sudoku.solver.Solver;
import org.polytech.ryuk.sudoku.constraint.Constraint;
import org.polytech.ryuk.sudoku.io.SudokuSerializer;
import org.polytech.ryuk.sudoku.solver.RandomSolver;
import org.polytech.ryuk.sudoku.solver.Solver;
public class SudokuFactory {
@@ -26,16 +25,11 @@ public class SudokuFactory {
* 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)
);
public static List<Constraint> DEFAULT_CONSTRAINTS = 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.
*/
@@ -48,11 +42,9 @@ public class SudokuFactory {
}
/**
* 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.
* 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.
*/
@@ -68,6 +60,9 @@ public class SudokuFactory {
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);
}
}
@@ -77,37 +72,89 @@ public class SudokuFactory {
}
/**
* Créée un MultiDoku vide dont les Blocks sont de taille widthBlock par
* heightBlock.
*
* @param widthBlock int, largeur des Blocks.
* 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)));
List<Constraint> constraints) {
return new MultiDoku(Arrays.asList(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)));
public static MultiDoku createBasicEmptySquareDoku(int size, List<Constraint> constraints) {
return new MultiDoku(Arrays.asList(createSquareSudoku(size, constraints)));
}
/**
* Créée un Sudoku vide dont les Blocks sont de taille widthBlock par
* heightBlock.
*
* Place des Cells immutables de valeurs fournies, aux Coordinate fournies dans le MultiDoku doku fourni.
* @param doku MultiDoku, MultiDoku à remplir.
* @param immutableCells Map<Coordinate, Integer>, association de Coordinate coordonnées et Integer valeurs, correspondant aux cases à remplir.
*/
public static void setImmutableCells(MultiDoku doku, Map<Coordinate, Integer> immutableCells) {
immutableCells.forEach((coordinate, symbol) -> {
for (Sudoku sudoku : doku.getSubGrids()) {
Cell cell = sudoku.getCell(coordinate.getX(), coordinate.getY());
if (cell != null) {
cell.setSymbolIndex(symbol);
cell.setImmutable();
}
}
});
}
/**
* 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();
while (!cellsThatCanBeEmptied.isEmpty()) {
int index = random.nextInt(cellsThatCanBeEmptied.size());
Cell cellToEmpty = cellsThatCanBeEmptied.get(index);
int oldSymbol = cellToEmpty.empty();
int nbDokuSultions = solver.countSolution(doku);
if (nbDokuSultions == 1) {
if (newDokuFromFilledOne(doku, --nbCellsToEmpty, solver)) {
return true;
}
}
cellToEmpty.setSymbolIndex(oldSymbol);
cellsThatCanBeEmptied.remove(cellToEmpty);
}
return false;
}
/**
* 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) {
private static Sudoku createRectangleSudoku(int widthBlock, int heightBlock, List<Constraint> constraints) {
int symbolCount = widthBlock * heightBlock;
List<Cell> cases = initCells(symbolCount);
List<Block> blocs = initRectangleBlocs(cases, widthBlock, heightBlock);
@@ -121,17 +168,15 @@ public class SudokuFactory {
/**
* 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) {
private static Sudoku createSquareSudoku(int size, List<Constraint> 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.
@@ -168,38 +213,51 @@ public class SudokuFactory {
}
/**
* 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
*
* 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.
* @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) {
public static MultiDoku createBasicXShapedMultidoku(int size, List<Constraint> constraints) {
assert (size > 1);
return createBasicXShapedMultidoku(size, size, constraints);
/*
* 2 3
* 1
* 4 5
*/
Sudoku sudoku1 = createSquareSudoku(size, constraints);
Sudoku sudoku2 = createSquareSudoku(size, constraints);
Sudoku sudoku3 = createSquareSudoku(size, constraints);
Sudoku sudoku4 = createSquareSudoku(size, constraints);
Sudoku sudoku5 = createSquareSudoku(size, constraints);
linkRectangleSudokus(sudoku1, sudoku2, new Coordinate(1 - size, 1 - size));
linkRectangleSudokus(sudoku1, sudoku3, new Coordinate(size - 1, 1 - size));
linkRectangleSudokus(sudoku1, sudoku4, new Coordinate(1 - size, size - 1));
linkRectangleSudokus(sudoku1, sudoku5, new Coordinate(size - 1, size - 1));
return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5));
}
/**
* Créée un MultiDoku de Blocks rectangulaires de forme X, de taille width par height composé
* de cinq Sudokus,
* Créée un MultiDoku de Blocks rectangulaires de forme 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.
* @param width int, largeur des Blocks unitraires des Sudokus à crééer.
* @param height int, hauteur des Blocks unitraires des Sudokus à crééer.
* @return MultiDoku, MultiDoku de forme X.
*/
public static MultiDoku createBasicXShapedMultidoku(int width, int height, List<IConstraint> constraints) {
public static MultiDoku createBasicXShapedMultidoku(int width, int height, List<Constraint> constraints) {
assert (width > 1 && height > 1);
/*
* 2 3
* 1
* 4 5
*/
Sudoku sudoku1 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku2 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku3 = createRectangleSudoku(width, height, constraints);
@@ -214,68 +272,33 @@ public class SudokuFactory {
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);
public static void fillDoku(MultiDoku doku, Difficulty difficulty) throws Exception {
Solver solver = new RandomSolver();
solver.solve(doku);
int nbCellsToEmpty = (int) (difficulty.getFactor() * doku.getNbCells());
boolean successfull = newDokuFromFilledOne(doku, nbCellsToEmpty, solver);
doku.setFilledCellsImmutable();
}
/**
* 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));
public static MultiDoku fromfile(String filePath) {
try {
String content = Files.readString(Paths.get(filePath));
MultiDoku doku = SudokuSerializer.deserializeSudoku(content);
return doku;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 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) {
public static MultiDoku createBasicEmptyRandomBlockDoku(int blockSize, List<Constraint> constraints) {
int blockCellCount = blockSize * blockSize;
List<Cell> cells = initCells(blockCellCount);
List<Cell> homeLessCells = new ArrayList<>(cells);
List<Cell> homeLessCells = new ArrayList<>();
homeLessCells.addAll(cells);
List<Block> blocks = new ArrayList<>();
Random r = new Random();
for (int i = 0; i < blockCellCount; i++) {
for (int i = 0 ; i < blockCellCount; i++) {
Block b = new Block();
for (int j = 0; j < blockCellCount; j++) {
int cellIndex = r.nextInt(homeLessCells.size());
@@ -289,84 +312,6 @@ public class SudokuFactory {
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 Constraint en IConstraint 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;
return new MultiDoku(Arrays.asList(sudoku));
}
}

View File

@@ -1,50 +0,0 @@
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package sudoku;
import gui.RenderableMultidoku;
import gui.constants.Symbols;
import sudoku.io.ConsoleInterface;
import sudoku.io.SudokuPrinter;
import sudoku.io.SudokuSerializer;
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) {
ConsoleInterface console = new ConsoleInterface();
/*
voidTest();
filledTest();
overwriteTest(0);
overwriteTest(17)
*/
console.welcome();
}
}

View File

@@ -1,336 +0,0 @@
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 {
public Scanner reader = new Scanner(System.in);
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();
}
}
private void useSavedDoku() {
System.out.println("What save should we use? Please enter the save number.");
MultiDoku md = saveChoice();
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();
}
public 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 ('generate', default):");
if (reader.next().equalsIgnoreCase("fill")) {
findSolution(doku, listSymbols, width, height);
} else {
playableDoku(doku, listSymbols, width, height);
}
}
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 !");
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();
}
}
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();
}
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);
}
private MultiDoku saveChoice() {
int nbSave;
MultiDoku md = null;
do {
nbSave = reader.nextInt();
try {
md = SudokuSerializer.getSavedMultiDoku(nbSave);
} catch (Exception e) {
System.out.println("There seems to be a problem with this save, please try again.");
}
} while (md == null);
return md;
}
public 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;
}
public 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;
}
private Boolean checkValidSize(int size) {
return (size > 0);
}
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();
};
}
}
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;
}
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.");
}
}
private void generateFullDoku(MultiDoku doku) {
new RandomSolver().solve(doku);
}
private void showMultidoku(MultiDoku doku, List<String> listSymbols, int width, int height) {
showMultiDoku(RenderableMultidoku.fromMultidoku(doku), listSymbols, width, height);
}
private void showMultiDoku(RenderableMultidoku doku, List<String> listSymbols, int width, int height) {
SudokuPrinter.printMultiDokuWithIndex(doku, listSymbols, width, height);
}
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);
}
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), save the state of the doku ('save'), show a solution ('solution') 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;
}
}
private void applyStep(SolverStep step) {
step.getCell().setSymbolIndex(step.getNewValue());
}
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");
}
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();
switch (reader.next()) {
case "y":
int stepCount = 0;
while(stepCount < steps.size() && showStep(doku, listSymbols, width, height, steps.get(stepCount))){stepCount++;}
break;
default:
break;
}
}
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;
}
showSolveSteps(doku, listSymbols, width, height, steps);
}
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);
}
private boolean isValidCoordinates(RenderableMultidoku doku, int width, int height, int x, int y) {
if (doku.getCell(x, y) != null) {
return true;
}
return false;
}
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 -1;
}
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;
}
private void exit() {
System.out.println("Thank you for playing!");
System.exit(0);
}
}

View File

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

View File

@@ -1,202 +0,0 @@
package sudoku.io;
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, 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++) {
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 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,53 +0,0 @@
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;
//TODO
public class HintHelper {
public static record Hint(Cell cell, int newValue) {}
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

@@ -1,39 +0,0 @@
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

@@ -1,99 +0,0 @@
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> findCellToBacktrack(MultiDoku doku, int maxPossibilities) {
int symbolCount = doku.getSubGrid(0).getSize();
if (maxPossibilities > symbolCount)
return null;
List<Cell> backtrackCells = new ArrayList<>();
for (Cell cell : doku.getCells()) {
if (!cell.isMutable() || !cell.isEmpty())
continue;
List<Integer> possibleSymbols = cell.getPossibleSymbols();
if (possibleSymbols.size() == maxPossibilities) {
backtrackCells.add(cell);
}
// grille non résolvable
if (possibleSymbols.size() == 0)
return null;
}
return backtrackCells;
}
/**
* 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;
int symbolCount = doku.getSubGrid(0).getSize();
// on remplit les cases par déduction
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);
return false;
}
}
// on ne peut plus remplir de cases, on tente de backtrack
for (int maxPossibilities = 2; maxPossibilities <= symbolCount; maxPossibilities++) {
List<Cell> backtrackCells = new ArrayList<>();
while (backtrackCells.isEmpty()) {
backtrackCells = findCellToBacktrack(doku, maxPossibilities);
// grille non résolvable
if (backtrackCells == null) {
return false;
}
maxPossibilities++;
}
// on fait du backtracking
for (Cell backtrackCell : backtrackCells) {
List<Integer> possibilities = backtrackCell.getPossibleSymbols();
// System.out.println("Backtraing on " + backtrackCell);
// on tente de placer chacun des symboles
for (int symbol : possibilities) {
backtrackCell.setSymbolIndex(symbol);
if (solve(doku, steps)) {
return true;
}
}
backtrackCell.setSymbolIndex(Cell.NOSYMBOL);
}
}
return doku.isSolved();
}
}

View File

@@ -1,23 +0,0 @@
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

@@ -1,63 +0,0 @@
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 void forgetState() {
states.pop();
}
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;
}
public 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;
}
}

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