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" />
</component>
<component name="ChangeListManager">
<list default="true" id="41395b4b-3252-492c-a869-5f4dab107186" name="Changes" comment="MiniMax">
<change afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/Pushed.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/Pusher.java" afterDir="false" />
<list default="true" id="41395b4b-3252-492c-a869-5f4dab107186" name="Changes" comment="Movement logic">
<change afterPath="$PROJECT_DIR$/src/main/java/laboratoire4/Main.java" 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/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/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/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>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -31,6 +42,34 @@
</map>
</option>
</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">
<option name="directoryName" value="x0367gi2" />
</component>
@ -52,20 +91,21 @@
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;,
&quot;last_opened_file_path&quot;: &quot;/home/william/Dev/Projects&quot;,
&quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
&quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
&quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
&quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
&quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"SHARE_PROJECT_CONFIGURATION_FILES": "true",
"codeWithMe.voiceChat.enabledByDefault": "false",
"last_opened_file_path": "/home/william/Dev/Projects",
"node.js.detected.package.eslint": "true",
"node.js.detected.package.tslint": "true",
"node.js.selected.package.eslint": "(autodetect)",
"node.js.selected.package.tslint": "(autodetect)",
"vue.rearranger.settings.migration": "true"
}
}</component>
<component name="RunManager">
}]]></component>
<component name="RunManager" selected="Application.Main">
<configuration name="Client" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="laboratoire4.Client" />
<module name="Lab4" />
@ -79,8 +119,36 @@
<option name="Make" enabled="true" />
</method>
</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>
<list>
<item itemvalue="Application.Main" />
<item itemvalue="Application.Test" />
<item itemvalue="Application.Client" />
</list>
</recent_temporary>
@ -96,7 +164,9 @@
<workItem from="1679255649975" duration="1223000" />
<workItem from="1679261446095" duration="1927000" />
<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 id="LOCAL-00001" summary="MiniMax">
<created>1679263366439</created>
@ -105,7 +175,14 @@
<option name="project" value="LOCAL" />
<updated>1679263366439</updated>
</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 />
</component>
<component name="TypeScriptGeneratedFilesManager">
@ -113,6 +190,7 @@
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value="MiniMax" />
<option name="LAST_COMMIT_MESSAGE" value="MiniMax" />
<MESSAGE value="Movement logic" />
<option name="LAST_COMMIT_MESSAGE" value="Movement logic" />
</component>
</project>

View File

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

View File

@ -1,124 +1,97 @@
package laboratoire4;
import java.io.*;
import java.net.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
class Client {
public static void main(String[] args) {
public class Client {
private final Socket socket;
private final BufferedInputStream input;
private final BufferedOutputStream output;
private PusherBoard board;
Socket MyClient;
BufferedInputStream input;
BufferedOutputStream output;
int[][] board = new int[8][8];
public Client(String host, int port) throws IOException {
socket = new Socket(host, port);
input = new BufferedInputStream(socket.getInputStream());
output = new BufferedOutputStream(socket.getOutputStream());
}
public void listen() {
try {
MyClient = new Socket("localhost", 8888);
input = new BufferedInputStream(MyClient.getInputStream());
output = new BufferedOutputStream(MyClient.getOutputStream());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
while(1 == 1){
char cmd = 0;
while (true) {
char cmd;
cmd = (char) input.read();
System.out.println(cmd);
// Debut de la partie en joueur blanc
if(cmd == '1'){
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++;
if (board == null) {
boolean play = initializeBoard(cmd);
if (play) {
play();
}
}
System.out.println("Nouvelle partie! Vous jouer blanc, entrez votre premier coup : ");
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();
play();
}
// 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();
handleInvalidMove();
}
// La partie est terminée
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;
byte[] aBuffer = new byte[1024];
int size = input.available();
input.read(aBuffer, 0, size);
String s = new String(aBuffer).trim();
String[] boardValues = s.split(" ");
board = new PusherBoard(player, boardValues);
return player == Player.RED;
}
private void play() throws IOException {
byte[] aBuffer = new byte[16];
int size = input.available();
if (size > 0) {
input.read(aBuffer, 0, size);
String s = new String(aBuffer);
System.out.println("Partie Terminé. Le dernier coup joué est: "+s);
String move = null;
move = console.readLine();
output.write(move.getBytes(),0,move.length());
String previousMove = new String(aBuffer);
System.out.println("Mouvement reçu: " + previousMove);
board.move(previousMove);
}
String nextMove = board.runNextMove();
System.out.println("Prochain mouvement: " + nextMove);
output.write(nextMove.getBytes(), 0, nextMove.length());
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() {
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;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MiniMax {
private static final int MAX_DEPTH = 4;
private static Random random = new Random();
public static int miniMax(GameTree tree) {
return miniMax(tree.getRoot(), Player.MAX, 0);
public static MiniMaxResult miniMax(PusherBoard board) {
return miniMax(board, true, 0, Integer.MIN_VALUE);
}
private static int miniMax(GameTree.Node node, Player player, int depth) {
if (depth == MAX_DEPTH) {
return evaluate(node);
private static MiniMaxResult miniMax(PusherBoard board, boolean max, int depth, int alphaBeta) {
int limScore = max ? Integer.MIN_VALUE : Integer.MAX_VALUE;
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 ?
max(node, depth) :
min(node, depth);
MiniMaxResult result = new MiniMaxResult(limScore, pawn, movement);
//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) {
int maxScore = Integer.MIN_VALUE;
results.add(result);
}
for (GameTree.Node child : node.getChilds()) {
int score = miniMax(child, Player.MIN, depth + 1);
if (score > maxScore) {
maxScore = score;
pawn.setRow(originalRow);
pawn.setCol(originalCol);
}
}
return maxScore;
// Choisir aléatoirement
int index = random.nextInt(results.size());
return results.get(index);
}
private static int min(GameTree.Node node, int depth) {
int minScore = Integer.MAX_VALUE;
private static int evaluate(Pawn pawn, PusherBoard board) {
int score = didWin(pawn);
score = Math.max(score, didCapture(pawn, board));
for (GameTree.Node child : node.getChilds()) {
int score = miniMax(child, Player.MIN, depth + 1);
if (score < minScore) {
minScore = score;
}
}
return minScore;
}
private static int evaluate(GameTree.Node node) {
return 0;
return score;
}
}

View File

@ -1,18 +1,30 @@
package laboratoire4;
public abstract class Pawn {
protected final PawnColor color;
protected int col;
protected final Player player;
protected int row;
protected int col;
protected int direction;
public Pawn(PawnColor color, int col, int row) {
this.color = color;
this.col = col;
public Pawn(Player player, int row, int col) {
this.player = player;
this.row = row;
this.col = col;
this.direction = player == Player.RED ? 1 : -1;
}
public PawnColor getColor() {
return color;
public void move(PawnMovement movement) {
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() {
@ -31,13 +43,28 @@ public abstract class Pawn {
this.row = row;
}
public abstract boolean isMoveValid(PusherBoard board, PawnMovement movement);
enum PawnColor {
RED,
BLACK
public int getDirection() {
return direction;
}
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 {
STRAIGHT(0),
LEFT_DIAGONAL(-1),
@ -52,5 +79,15 @@ public abstract class Pawn {
public int getMove() {
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;
public enum Player {
MIN,
MAX
BLACK,
RED
}

View File

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

View File

@ -1,14 +1,27 @@
package laboratoire4;
public class Pusher extends Pawn {
public Pusher(PawnColor color, int col, int row) {
super(color, col, row);
public Pusher(Player player, int row, int col) {
super(player, row, col);
}
@Override
public boolean isMoveValid(PusherBoard game, PawnMovement movement) {
Pawn to = game.getBoard()[row + 1][col + movement.getMove()];
public boolean isMoveValid(Pawn[][] board, PawnMovement movement) {
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;
import java.util.ArrayList;
import java.util.List;
public class PusherBoard {
private final Player player;
private Pawn[][] board;
public PusherBoard() {
this.newGame();
private final List<Pawn> maxPawns = new ArrayList<>();
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];
// TODO: Construire depuis le serveur
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
Pawn pawn = null;
Pawn.PawnColor color = i < board.length / 2 ?
Pawn.PawnColor.RED :
Pawn.PawnColor.BLACK;
if (i == 0 || i == board.length - 1) {
pawn = new Pusher(color, i, j);
} else if (i == 1 || i == board.length - 2) {
pawn = new Pushed(color, i, j);
int col = 0, row = 0;
for (String boardValue : boardValues) {
int v = Integer.parseInt(boardValue);
if (v != 0) {
Player pawnPlayer = (v == 1 || v == 2) ? Player.RED : Player.BLACK;
Pawn pawn;
if (v % 2 == 0) { // 2 et 4 sont les pushers
pawn = new Pusher(pawnPlayer, row, col);
} else {
pawn = new Pushed(pawnPlayer, row, col);
}
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
String[] split = move.split("-");
return move(split[0], split[1]);
String[] split = move.trim().split(" - ");
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}
int from_col = (int) from.charAt(0) - 65;
int from_row = Integer.parseInt(String.valueOf(from.charAt(1))) - 1;
int to_col = (int) to.charAt(0) - 65;
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) {
//FORMAT ex : from_col {3}, from_row {2}, to_col {3}, to_row {3}
//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;
public void move(int from_col, int from_row, int to_col, int to_row) {
if (!isValid(from_col, from_row, to_col)) {
return;
}
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) {
Pawn[][] board = this.getBoard();
private boolean isValid(int from_col, int from_row, int to_col) {
Pawn pawn = getBoard()[from_row][from_col];
Pawn.PawnMovement move = Pawn.PawnMovement.from(to_col - from_col);
//out of bound?
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)))
if (pawn == null) {
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?
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;
return pawn.isMoveValid(this, move);
}
public Pawn[][] getBoard() {
return board;
}
public List<Pawn> getMaxPawns() {
return maxPawns;
}
public List<Pawn> getMinPawns() {
return minPawns;
}
public void printBoard() {
for (int i = 7; i >= 0; i--) {
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"));
}
}