AI basique fonctionnel :)

This commit is contained in:
FyloZ 2023-03-21 18:06:17 -04:00
parent ec7f3568e5
commit 1b73bfdd17
Signed by: william
GPG Key ID: 835378AE9AF4AE97
13 changed files with 418 additions and 322 deletions

View File

@ -4,13 +4,24 @@
<option name="autoReloadType" value="SELECTIVE" /> <option name="autoReloadType" value="SELECTIVE" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="41395b4b-3252-492c-a869-5f4dab107186" name="Changes" comment="MiniMax"> <list default="true" id="41395b4b-3252-492c-a869-5f4dab107186" name="Changes" comment="Movement logic">
<change afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/Pushed.java" afterDir="false" /> <change afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/Main.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/Pusher.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pom.xml" beforeDir="false" afterPath="$PROJECT_DIR$/pom.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/laboratoire4/Client.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/Client.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/laboratoire4/GameTree.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/GameTree.java" afterDir="false" /> <change beforePath="$PROJECT_DIR$/src/main/java/laboratoire4/GameTree.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/GameTree.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/laboratoire4/MiniMax.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/MiniMax.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/laboratoire4/Pawn.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/Pawn.java" afterDir="false" /> <change beforePath="$PROJECT_DIR$/src/main/java/laboratoire4/Pawn.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/Pawn.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/laboratoire4/Player.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/Player.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/laboratoire4/Pushed.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/Pushed.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/laboratoire4/Pusher.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/Pusher.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/laboratoire4/PusherBoard.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/PusherBoard.java" afterDir="false" /> <change beforePath="$PROJECT_DIR$/src/main/java/laboratoire4/PusherBoard.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/PusherBoard.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/laboratoire4/Test.java" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/laboratoire4/TestPusherBoard.java" beforeDir="false" />
</list>
<list id="98b8a79f-2f53-42bf-96da-7af322697a0d" name="Changes by acastonguay" comment="">
<change beforePath="$PROJECT_DIR$/src/main/java/laboratoire4/GameTree.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/GameTree.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/main/java/laboratoire4/MiniMax.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/MiniMax.java" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -31,6 +42,34 @@
</map> </map>
</option> </option>
</component> </component>
<component name="LineStatusTrackerManager">
<file path="$PROJECT_DIR$/src/main/java/laboratoire4/MiniMax.java">
<ranges>
<range start1="2" end1="2" start2="2" end2="6" changelist="41395b4b-3252-492c-a869-5f4dab107186" />
<range start1="4" end1="4" start2="8" end2="9" changelist="41395b4b-3252-492c-a869-5f4dab107186" />
<range start1="5" end1="7" start2="10" end2="12" changelist="41395b4b-3252-492c-a869-5f4dab107186" />
<range start1="9" end1="13" start2="14" end2="19" changelist="41395b4b-3252-492c-a869-5f4dab107186" />
<range start1="14" end1="18" start2="20" end2="21" changelist="41395b4b-3252-492c-a869-5f4dab107186" />
<range start1="19" end1="21" start2="22" end2="25" changelist="41395b4b-3252-492c-a869-5f4dab107186" />
<range start1="22" end1="28" start2="26" end2="39" changelist="41395b4b-3252-492c-a869-5f4dab107186" />
<range start1="29" end1="31" start2="40" end2="50" changelist="41395b4b-3252-492c-a869-5f4dab107186" />
<range start1="32" end1="34" start2="51" end2="53" changelist="41395b4b-3252-492c-a869-5f4dab107186" />
<range start1="35" end1="39" start2="54" end2="56" changelist="41395b4b-3252-492c-a869-5f4dab107186" />
<range start1="42" end1="43" start2="59" end2="62" changelist="41395b4b-3252-492c-a869-5f4dab107186" />
<range start1="45" end1="46" start2="64" end2="67" changelist="41395b4b-3252-492c-a869-5f4dab107186" />
<range start1="47" end1="48" start2="68" end2="69" changelist="41395b4b-3252-492c-a869-5f4dab107186" />
<range start1="49" end1="49" start2="70" end2="125" changelist="98b8a79f-2f53-42bf-96da-7af322697a0d" />
</ranges>
</file>
<file path="$PROJECT_DIR$/src/main/java/laboratoire4/GameTree.java">
<ranges>
<range start1="17" end1="17" start2="17" end2="19" changelist="98b8a79f-2f53-42bf-96da-7af322697a0d" />
<range start1="18" end1="19" start2="20" end2="21" changelist="98b8a79f-2f53-42bf-96da-7af322697a0d" />
<range start1="20" end1="20" start2="22" end2="24" changelist="98b8a79f-2f53-42bf-96da-7af322697a0d" />
<range start1="25" end1="25" start2="29" end2="37" changelist="41395b4b-3252-492c-a869-5f4dab107186" />
</ranges>
</file>
</component>
<component name="MacroExpansionManager"> <component name="MacroExpansionManager">
<option name="directoryName" value="x0367gi2" /> <option name="directoryName" value="x0367gi2" />
</component> </component>
@ -52,20 +91,21 @@
<option name="hideEmptyMiddlePackages" value="true" /> <option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" /> <option name="showLibraryContents" value="true" />
</component> </component>
<component name="PropertiesComponent">{ <component name="PropertiesComponent"><![CDATA[{
&quot;keyToString&quot;: { "keyToString": {
&quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;, "RunOnceActivity.OpenProjectViewOnStart": "true",
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;, "RunOnceActivity.ShowReadmeOnStart": "true",
&quot;SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;, "SHARE_PROJECT_CONFIGURATION_FILES": "true",
&quot;last_opened_file_path&quot;: &quot;/home/william/Dev/Projects&quot;, "codeWithMe.voiceChat.enabledByDefault": "false",
&quot;node.js.detected.package.eslint&quot;: &quot;true&quot;, "last_opened_file_path": "/home/william/Dev/Projects",
&quot;node.js.detected.package.tslint&quot;: &quot;true&quot;, "node.js.detected.package.eslint": "true",
&quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;, "node.js.detected.package.tslint": "true",
&quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;, "node.js.selected.package.eslint": "(autodetect)",
&quot;vue.rearranger.settings.migration&quot;: &quot;true&quot; "node.js.selected.package.tslint": "(autodetect)",
"vue.rearranger.settings.migration": "true"
} }
}</component> }]]></component>
<component name="RunManager"> <component name="RunManager" selected="Application.Main">
<configuration name="Client" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true"> <configuration name="Client" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="laboratoire4.Client" /> <option name="MAIN_CLASS_NAME" value="laboratoire4.Client" />
<module name="Lab4" /> <module name="Lab4" />
@ -79,8 +119,36 @@
<option name="Make" enabled="true" /> <option name="Make" enabled="true" />
</method> </method>
</configuration> </configuration>
<configuration name="Main" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="laboratoire4.Main" />
<module name="Lab4" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="laboratoire4.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="Test" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="laboratoire4.Test" />
<module name="Lab4" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="laboratoire4.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<recent_temporary> <recent_temporary>
<list> <list>
<item itemvalue="Application.Main" />
<item itemvalue="Application.Test" />
<item itemvalue="Application.Client" /> <item itemvalue="Application.Client" />
</list> </list>
</recent_temporary> </recent_temporary>
@ -96,7 +164,9 @@
<workItem from="1679255649975" duration="1223000" /> <workItem from="1679255649975" duration="1223000" />
<workItem from="1679261446095" duration="1927000" /> <workItem from="1679261446095" duration="1927000" />
<workItem from="1679281763874" duration="46000" /> <workItem from="1679281763874" duration="46000" />
<workItem from="1679344371350" duration="3857000" /> <workItem from="1679344371350" duration="4138000" />
<workItem from="1679365557789" duration="21000" />
<workItem from="1679424430928" duration="11764000" />
</task> </task>
<task id="LOCAL-00001" summary="MiniMax"> <task id="LOCAL-00001" summary="MiniMax">
<created>1679263366439</created> <created>1679263366439</created>
@ -105,7 +175,14 @@
<option name="project" value="LOCAL" /> <option name="project" value="LOCAL" />
<updated>1679263366439</updated> <updated>1679263366439</updated>
</task> </task>
<option name="localTasksCounter" value="2" /> <task id="LOCAL-00002" summary="Movement logic">
<created>1679348475071</created>
<option name="number" value="00002" />
<option name="presentableId" value="LOCAL-00002" />
<option name="project" value="LOCAL" />
<updated>1679348475071</updated>
</task>
<option name="localTasksCounter" value="3" />
<servers /> <servers />
</component> </component>
<component name="TypeScriptGeneratedFilesManager"> <component name="TypeScriptGeneratedFilesManager">
@ -113,6 +190,7 @@
</component> </component>
<component name="VcsManagerConfiguration"> <component name="VcsManagerConfiguration">
<MESSAGE value="MiniMax" /> <MESSAGE value="MiniMax" />
<option name="LAST_COMMIT_MESSAGE" value="MiniMax" /> <MESSAGE value="Movement logic" />
<option name="LAST_COMMIT_MESSAGE" value="Movement logic" />
</component> </component>
</project> </project>

View File

@ -9,8 +9,8 @@
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<properties> <properties>
<maven.compiler.source>18</maven.compiler.source> <maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>18</maven.compiler.target> <maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>

View File

@ -1,124 +1,97 @@
package laboratoire4; package laboratoire4;
import java.io.*; import java.io.BufferedInputStream;
import java.net.*; import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
class Client { public class Client {
public static void main(String[] args) { private final Socket socket;
private final BufferedInputStream input;
private final BufferedOutputStream output;
private PusherBoard board;
Socket MyClient; public Client(String host, int port) throws IOException {
BufferedInputStream input; socket = new Socket(host, port);
BufferedOutputStream output; input = new BufferedInputStream(socket.getInputStream());
int[][] board = new int[8][8]; output = new BufferedOutputStream(socket.getOutputStream());
}
public void listen() {
try { try {
MyClient = new Socket("localhost", 8888); while (true) {
char cmd;
cmd = (char) input.read();
input = new BufferedInputStream(MyClient.getInputStream()); if (board == null) {
output = new BufferedOutputStream(MyClient.getOutputStream()); boolean play = initializeBoard(cmd);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); if (play) {
while(1 == 1){ play();
char cmd = 0; }
}
if (cmd == '3') {
play();
}
if (cmd == '4') {
handleInvalidMove();
}
if (cmd == '5') {
stopGame();
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private boolean initializeBoard(char cmd) throws IOException {
Player player = cmd == '1' ? Player.RED : Player.BLACK;
cmd = (char)input.read();
System.out.println(cmd);
// Debut de la partie en joueur blanc
if(cmd == '1'){
byte[] aBuffer = new byte[1024]; byte[] aBuffer = new byte[1024];
int size = input.available(); int size = input.available();
//System.out.println("size " + size);
input.read(aBuffer,0,size); input.read(aBuffer, 0, size);
String s = new String(aBuffer).trim(); String s = new String(aBuffer).trim();
System.out.println(s); String[] boardValues = s.split(" ");
String[] boardValues;
boardValues = s.split(" "); board = new PusherBoard(player, boardValues);
int x=0,y=0;
for(int i=0; i<boardValues.length;i++){ return player == Player.RED;
board[x][y] = Integer.parseInt(boardValues[i]);
x++;
if(x == 8){
x = 0;
y++;
}
} }
System.out.println("Nouvelle partie! Vous jouer blanc, entrez votre premier coup : "); private void play() throws IOException {
String move = null;
move = console.readLine();
output.write(move.getBytes(),0,move.length());
output.flush();
}
// Debut de la partie en joueur Noir
if(cmd == '2'){
System.out.println("Nouvelle partie! Vous jouer noir, attendez le coup des blancs");
byte[] aBuffer = new byte[1024];
int size = input.available();
//System.out.println("size " + size);
input.read(aBuffer,0,size);
String s = new String(aBuffer).trim();
System.out.println(s);
String[] boardValues;
boardValues = s.split(" ");
int x=0,y=0;
for(int i=0; i<boardValues.length;i++){
board[x][y] = Integer.parseInt(boardValues[i]);
x++;
if(x == 8){
x = 0;
y++;
}
}
}
// Le serveur demande le prochain coup
// Le message contient aussi le dernier coup joue.
if(cmd == '3'){
byte[] aBuffer = new byte[16];
int size = input.available();
System.out.println("size :" + size);
input.read(aBuffer,0,size);
String s = new String(aBuffer);
System.out.println("Dernier coup :"+ s);
System.out.println("Entrez votre coup : ");
String move = null;
move = console.readLine();
output.write(move.getBytes(),0,move.length());
output.flush();
}
// Le dernier coup est invalide
if(cmd == '4'){
System.out.println("Coup invalide, entrez un nouveau coup : ");
String move = null;
move = console.readLine();
output.write(move.getBytes(),0,move.length());
output.flush();
}
// La partie est terminée
if(cmd == '5'){
byte[] aBuffer = new byte[16]; byte[] aBuffer = new byte[16];
int size = input.available(); int size = input.available();
input.read(aBuffer,0,size); if (size > 0) {
String s = new String(aBuffer); input.read(aBuffer, 0, size);
System.out.println("Partie Terminé. Le dernier coup joué est: "+s); String previousMove = new String(aBuffer);
String move = null; System.out.println("Mouvement reçu: " + previousMove);
move = console.readLine();
output.write(move.getBytes(),0,move.length()); board.move(previousMove);
}
String nextMove = board.runNextMove();
System.out.println("Prochain mouvement: " + nextMove);
output.write(nextMove.getBytes(), 0, nextMove.length());
output.flush(); output.flush();
}
}
}
catch (IOException e) {
System.out.println(e);
} }
private void handleInvalidMove() throws InterruptedException {
System.err.println("Mouvement invalide!");
Thread.sleep(500);
board.printBoard();
}
private void stopGame() throws IOException {
System.out.println("GG well played!");
socket.close();
} }
} }

View File

@ -23,6 +23,14 @@ public class GameTree {
public Collection<Node> getChilds() { public Collection<Node> getChilds() {
return childs; return childs;
} }
public Pawn getPawn() {
return pawn;
}
public Pawn.PawnMovement getMovement() {
return movement;
}
} }
} }

View File

@ -0,0 +1,9 @@
package laboratoire4;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
new Client("localhost", 8888).listen();
}
}

View File

@ -1,50 +1,71 @@
package laboratoire4; package laboratoire4;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MiniMax { public class MiniMax {
private static final int MAX_DEPTH = 4; private static final int MAX_DEPTH = 4;
private static Random random = new Random();
public static int miniMax(GameTree tree) { public static MiniMaxResult miniMax(PusherBoard board) {
return miniMax(tree.getRoot(), Player.MAX, 0); return miniMax(board, true, 0, Integer.MIN_VALUE);
} }
private static int miniMax(GameTree.Node node, Player player, int depth) { private static MiniMaxResult miniMax(PusherBoard board, boolean max, int depth, int alphaBeta) {
if (depth == MAX_DEPTH) { int limScore = max ? Integer.MIN_VALUE : Integer.MAX_VALUE;
return evaluate(node); List<Pawn> pawns = max ?
board.getMaxPawns() :
board.getMinPawns();
List<MiniMaxResult> results = new ArrayList<>();
for (Pawn pawn : pawns) {
int originalRow = pawn.getRow();
int originalCol = pawn.getCol();
for (Pawn.PawnMovement movement : Pawn.PawnMovement.values()) {
if (pawn.isMoveValid(board, movement)) {
pawn.move(movement);
int score = depth < MAX_DEPTH ?
miniMax(board, !max, depth + 1, limScore).getScore() :
evaluate(pawn, board);
score *= pawn.getDirection();
if ((max && score > limScore) ||
(!max && score < limScore)) {
limScore = score;
} }
return player == Player.MAX ? MiniMaxResult result = new MiniMaxResult(limScore, pawn, movement);
max(node, depth) :
min(node, depth); //elagage alphaBeta
if ((max && limScore >= alphaBeta) ||
(!max && limScore <= alphaBeta)) {
pawn.setRow(originalRow);
pawn.setCol(originalCol);
return result;
} }
private static int max(GameTree.Node node, int depth) { results.add(result);
int maxScore = Integer.MIN_VALUE; }
for (GameTree.Node child : node.getChilds()) { pawn.setRow(originalRow);
int score = miniMax(child, Player.MIN, depth + 1); pawn.setCol(originalCol);
if (score > maxScore) {
maxScore = score;
} }
} }
return maxScore; // Choisir aléatoirement
int index = random.nextInt(results.size());
return results.get(index);
} }
private static int min(GameTree.Node node, int depth) { private static int evaluate(Pawn pawn, PusherBoard board) {
int minScore = Integer.MAX_VALUE; int score = didWin(pawn);
score = Math.max(score, didCapture(pawn, board));
for (GameTree.Node child : node.getChilds()) { return score;
int score = miniMax(child, Player.MIN, depth + 1);
if (score < minScore) {
minScore = score;
}
}
return minScore;
}
private static int evaluate(GameTree.Node node) {
return 0;
} }
} }

View File

@ -1,18 +1,30 @@
package laboratoire4; package laboratoire4;
public abstract class Pawn { public abstract class Pawn {
protected final PawnColor color; protected final Player player;
protected int col;
protected int row; protected int row;
protected int col;
protected int direction;
public Pawn(PawnColor color, int col, int row) { public Pawn(Player player, int row, int col) {
this.color = color; this.player = player;
this.col = col;
this.row = row; this.row = row;
this.col = col;
this.direction = player == Player.RED ? 1 : -1;
} }
public PawnColor getColor() { public void move(PawnMovement movement) {
return color; setRow(row + direction);
setCol(col + movement.move);
}
public String getPosition() {
char colStr = (char)(col + 65);
return String.format("%s%d", colStr, row + 1);
}
public Player getPlayer() {
return player;
} }
public int getCol() { public int getCol() {
@ -31,13 +43,28 @@ public abstract class Pawn {
this.row = row; this.row = row;
} }
public abstract boolean isMoveValid(PusherBoard board, PawnMovement movement); public int getDirection() {
return direction;
enum PawnColor {
RED,
BLACK
} }
public boolean isMoveValid(PusherBoard game, PawnMovement movement) {
Pawn[][] board = game.getBoard();
int nextRow = row + getDirection();
if (nextRow < 0 || nextRow >= board.length) {
return false;
}
int nextCol = col + movement.move;
if (nextCol < 0 || nextCol >= board.length) {
return false;
}
return isMoveValid(board, movement);
}
protected abstract boolean isMoveValid(Pawn[][] board, PawnMovement movement);
enum PawnMovement { enum PawnMovement {
STRAIGHT(0), STRAIGHT(0),
LEFT_DIAGONAL(-1), LEFT_DIAGONAL(-1),
@ -52,5 +79,15 @@ public abstract class Pawn {
public int getMove() { public int getMove() {
return move; return move;
} }
public static PawnMovement from(int move) {
if (move == 0) {
return STRAIGHT;
}
if (move == 1) {
return RIGHT_DIAGONAL;
}
return LEFT_DIAGONAL;
}
} }
} }

View File

@ -1,6 +1,6 @@
package laboratoire4; package laboratoire4;
public enum Player { public enum Player {
MIN, BLACK,
MAX RED
} }

View File

@ -1,26 +1,34 @@
package laboratoire4; package laboratoire4;
public class Pushed extends Pawn { public class Pushed extends Pawn {
public Pushed(PawnColor color, int col, int row) { public Pushed(Player player, int row, int col) {
super(color, col, row); super(player, row, col);
} }
@Override @Override
public boolean isMoveValid(PusherBoard game, PawnMovement movement) { public boolean isMoveValid(Pawn[][] board, PawnMovement movement) {
Pawn[][] board = game.getBoard();
Pawn pusher = null; Pawn pusher = null;
Pawn to = board[row + 1][col + movement.getMove()]; Pawn to = board[row + direction][col + movement.getMove()];
if (col > 0 && movement == PawnMovement.RIGHT_DIAGONAL) { if (col > 0 && movement == PawnMovement.RIGHT_DIAGONAL) {
pusher = board[row - 1][col - 1]; pusher = board[row - direction][col - 1];
} else if (col < board.length - 1 && movement == PawnMovement.LEFT_DIAGONAL) { } else if (col < board.length - 1 && movement == PawnMovement.LEFT_DIAGONAL) {
pusher = board[row - 1][col + 1]; pusher = board[row - direction][col + 1];
} else if (movement == PawnMovement.STRAIGHT) { } else if (movement == PawnMovement.STRAIGHT) {
pusher = board[row - 1][col]; pusher = board[row - direction][col];
} }
boolean pusherValid = pusher != null; boolean pusherValid = pusher instanceof Pusher;
boolean destinationValid = to == null || to.color != this.color; boolean destinationValid = to == null || to.player != this.player;
return pusherValid && destinationValid; return pusherValid && destinationValid;
} }
@Override
public String toString() {
return "Pushed{" +
player +
", " + col +
", " + row +
"} ";
}
} }

View File

@ -1,14 +1,27 @@
package laboratoire4; package laboratoire4;
public class Pusher extends Pawn { public class Pusher extends Pawn {
public Pusher(PawnColor color, int col, int row) { public Pusher(Player player, int row, int col) {
super(color, col, row); super(player, row, col);
} }
@Override @Override
public boolean isMoveValid(PusherBoard game, PawnMovement movement) { public boolean isMoveValid(Pawn[][] board, PawnMovement movement) {
Pawn to = game.getBoard()[row + 1][col + movement.getMove()]; Pawn to = board[row + direction][col + movement.getMove()];
return to == null || to.color != this.color; if (to == null) {
return true;
}
return to.player != this.player && movement != PawnMovement.STRAIGHT;
}
@Override
public String toString() {
return "Pusher{" +
player +
", " + col +
", " + row +
"} ";
} }
} }

View File

@ -1,123 +1,130 @@
package laboratoire4; package laboratoire4;
import java.util.ArrayList;
import java.util.List;
public class PusherBoard { public class PusherBoard {
private final Player player;
private Pawn[][] board; private Pawn[][] board;
public PusherBoard() { private final List<Pawn> maxPawns = new ArrayList<>();
this.newGame(); private final List<Pawn> minPawns = new ArrayList<>();
public PusherBoard(Player player, String[] boardValues) {
this.player = player;
newGame(boardValues);
} }
public void newGame() { public void newGame(String[] boardValues) {
this.board = new Pawn[8][8]; this.board = new Pawn[8][8];
// TODO: Construire depuis le serveur int col = 0, row = 0;
for (int i = 0; i < board.length; i++) { for (String boardValue : boardValues) {
for (int j = 0; j < board.length; j++) { int v = Integer.parseInt(boardValue);
Pawn pawn = null; if (v != 0) {
Pawn.PawnColor color = i < board.length / 2 ? Player pawnPlayer = (v == 1 || v == 2) ? Player.RED : Player.BLACK;
Pawn.PawnColor.RED : Pawn pawn;
Pawn.PawnColor.BLACK; if (v % 2 == 0) { // 2 et 4 sont les pushers
pawn = new Pusher(pawnPlayer, row, col);
if (i == 0 || i == board.length - 1) { } else {
pawn = new Pusher(color, i, j); pawn = new Pushed(pawnPlayer, row, col);
} else if (i == 1 || i == board.length - 2) {
pawn = new Pushed(color, i, j);
} }
board[i][j] = pawn; if (pawnPlayer == player) {
maxPawns.add(pawn);
} else {
minPawns.add(pawn);
}
board[row][col] = pawn;
}
col++;
if (col == board.length) {
col = 0;
row++;
} }
} }
} }
public int move(String move) { public String runNextMove() {
MiniMax.MiniMaxResult result = MiniMax.miniMax(this);
Pawn pawn = result.getPawn();
String initialPosition = pawn.getPosition();
move(pawn, result.getMovement());
return initialPosition + "-" + pawn.getPosition();
}
public void move(String move) {
//FORMAT ex : D2-D3 //FORMAT ex : D2-D3
String[] split = move.split("-"); String[] split = move.trim().split(" - ");
move(split[0], split[1]);
return move(split[0], split[1]);
} }
public int move(String from, String to) { private void move(Pawn pawn, Pawn.PawnMovement movement) {
move(pawn.getCol(), pawn.getRow(), pawn.getCol() + movement.getMove(), pawn.getRow() + pawn.getDirection());
}
public void move(String from, String to) {
//FORMAT ex : from {D2}, to {D3} //FORMAT ex : from {D2}, to {D3}
int from_col = (int) from.charAt(0) - 65; int from_col = (int) from.charAt(0) - 65;
int from_row = Integer.parseInt(String.valueOf(from.charAt(1))) - 1; int from_row = Integer.parseInt(String.valueOf(from.charAt(1))) - 1;
int to_col = (int) to.charAt(0) - 65; int to_col = (int) to.charAt(0) - 65;
int to_row = Integer.parseInt(String.valueOf(to.charAt(1))) - 1; int to_row = Integer.parseInt(String.valueOf(to.charAt(1))) - 1;
return move(from_col, from_row, to_col, to_row); move(from_col, from_row, to_col, to_row);
} }
public int move(int from_col, int from_row, int to_col, int to_row) { public void move(int from_col, int from_row, int to_col, int to_row) {
//FORMAT ex : from_col {3}, from_row {2}, to_col {3}, to_row {3} if (!isValid(from_col, from_row, to_col)) {
return;
//System.out.println("Move :" + from_col+""+from_row + "-"+ to_col+""+to_row);
//System.out.println("Move is valid : " + isValid(from_col,from_row,to_col,to_row));
if (isValid(from_col, from_row, to_col, to_row)) {
Pawn pawn = this.getBoard()[from_row][from_col];
//System.out.println("Pawn to move : " + pawn);
this.getBoard()[from_row][from_col] = null;
this.getBoard()[to_row][to_col] = pawn;
} }
return -1; Pawn pawn = board[from_row][from_col];
Pawn destPawn = board[to_row][to_col];
if (destPawn != null) {
if (destPawn.getPlayer() == Player.RED) {
maxPawns.remove(destPawn);
} else {
minPawns.remove(destPawn);
}
}
board[from_row][from_col] = null;
board[to_row][to_col] = pawn;
pawn.setRow(to_row);
pawn.setCol(to_col);
} }
private boolean isValid(int from_col, int from_row, int to_col, int to_row) { private boolean isValid(int from_col, int from_row, int to_col) {
Pawn[][] board = this.getBoard(); Pawn pawn = getBoard()[from_row][from_col];
Pawn.PawnMovement move = Pawn.PawnMovement.from(to_col - from_col);
//out of bound? if (pawn == null) {
if ((from_col > 7 || from_col < 0) || ((from_row > 7 || from_row < 0)) || ((to_col > 7 || to_col < 0)) || ((to_row > 7 || to_row < 0)))
return false; return false;
//no pawn to move?
Pawn pawnToMove = board[from_row][from_col];
if (pawnToMove == null) return false;
//Pawn at destination is our own pawn?
Pawn destination = board[to_row][to_col];
char source_color = pawnToMove.name().charAt(0);
if (destination != null) {
char destination_color = destination.name().charAt(0);
if (source_color == destination_color) return false;
} }
//Pawn goes back? or move is in valid range? return pawn.isMoveValid(this, move);
if (source_color == 'R') {
if (from_row > to_row) return false;
if (from_row + 1 != to_row) return false;
} else if (source_color == 'B') {
if (from_row < to_row) return false;
if (from_row - 1 != to_row) return false;
}
//PUSHED is in front a PUSHER?
if (pawnToMove.equals(Pawn.B_PUSHED)) {
if (from_col + 1 == to_col) {
return board[from_row + 1][from_col + 1] == Pawn.B_PUSHER;
} else if (from_col - 1 == to_col) {
return board[from_row - 1][from_col + 1] == Pawn.B_PUSHER;
} else if (from_col == to_col) {
return board[from_row + 1][from_col] == Pawn.B_PUSHER;
}
} else if (pawnToMove.equals(Pawn.R_PUSHED)) {
if (from_col + 1 == to_col) {
return board[from_row + 1][from_col - 1] == Pawn.R_PUSHER;
} else if (from_col - 1 == to_col) {
return board[from_row - 1][from_col - 1] == Pawn.R_PUSHER;
} else if (from_col == to_col) {
return board[from_row - 1][from_col] == Pawn.R_PUSHER;
}
}
return true;
} }
public Pawn[][] getBoard() { public Pawn[][] getBoard() {
return board; return board;
} }
public List<Pawn> getMaxPawns() {
return maxPawns;
}
public List<Pawn> getMinPawns() {
return minPawns;
}
public void printBoard() { public void printBoard() {
for (int i = 7; i >= 0; i--) { for (int i = 7; i >= 0; i--) {
for (int j = 0; j < this.board.length; j++) { for (int j = 0; j < this.board.length; j++) {

View File

@ -1,29 +0,0 @@
package laboratoire4;
public class Test {
public static void main(String[] args) {
PusherBoard pusherBoard = new PusherBoard();
testMoves(pusherBoard);
pusherBoard.printBoard();
}
private static void testMoves(PusherBoard pusherBoard){
//Move examples
pusherBoard.move("D2","D3");
pusherBoard.move("C2","C3");
pusherBoard.move("D1","D2");
pusherBoard.move("D2","E3");
pusherBoard.move("C1","C2");
pusherBoard.move("E3","D4");
pusherBoard.move("A5","A6");
pusherBoard.move("D2","D1");
pusherBoard.move("H8","H9");
pusherBoard.move("A1","A3");
pusherBoard.move("A1","A2");
pusherBoard.move("A8","A6");
pusherBoard.move("A8","A7");
pusherBoard.move("D3","D4");
pusherBoard.move("C3","D4");
}
}

View File

@ -1,29 +0,0 @@
package laboratoire4;
import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.*;
class TestPusherBoard {
private Method getIsValidMethod() throws NoSuchMethodException {
Method method = PusherBoard.class.getDeclaredMethod("isValid", int.class, int.class, int.class, int.class);
method.setAccessible(true);
return method;
}
@Test
public void moveValidation() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
PusherBoard pusherBoard = new PusherBoard();
//Move examples
assertEquals(true, getIsValidMethod().invoke(null, null, new Integer[] { 3,2,3,3 }));
// assertEquals(true,pusherBoard.move("C2","C3"));
// assertEquals(true,pusherBoard.move("D1","D3"));
// assertEquals(true,pusherBoard.move("D2","E3"));
}
}