chessai
college code for ai playing chess in java
git clone https://9o.is/git/chessai.git
ChessGame.java
(3577B)
1 package chess;
2
3 import chess.server.*;
4 import chess.utils.ChessDirection;
5
6 import java.util.ArrayList;
7 import java.util.List;
8
9 /**
10 *
11 */
12 public class ChessGame {
13
14 public static void main(String[] args) {
15 final int gameId = 67;
16 final int teamNo = 1;
17 final String secret = "32c68cae";
18
19 BenCarleChessServer server =
20 new BenCarleChessServer(gameId, teamNo, secret);
21
22 ChessPlayer player = new ChessPlayer(teamNo);
23 ChessPlayer opponent = new ChessPlayer(teamNo==1 ? 2 : 1);
24
25 ChessBoard board = new ChessBoard();
26
27 StatusResponse status = server.poll();
28
29 boolean playing = true;
30 while (playing) {
31
32 // our turn
33 while(status.isReady()) {
34 ChessClock clock =
35 new ChessClock(status.getSecondsLeft());
36
37 ChessRules.INSTANCE.setLog(false);
38 ChessRules.INSTANCE.setEvaluating(true);
39 ChessMove move = player.bestPossibleMove(board);
40 ChessRules.INSTANCE.setLog(true);
41 ChessRules.INSTANCE.setEvaluating(false);
42
43 MoveResponse response = server.push(board, move);
44 if(response.isResult() && board.move(move)) {
45 player.incrementMoves();
46 System.out.println("Player Moved: "+
47 move.toString()+" with "+
48 status.getSecondsLeft()+" seconds left.");
49 }
50
51 status = server.poll();
52 }
53
54 if(isGameover(status,board,player))
55 playing = false;
56
57 // OPPONENT's turn
58 while(!status.isReady()) {
59 // poll every 5 seconds
60 try {
61 Thread.sleep((long)(5 * 1000));
62 status = server.poll();
63 } catch (InterruptedException e) {}
64
65 if(status.isReady()) {
66 // move opponent's last move
67 if(board.move(status.srcLastMove(), status.destLastMove())) {
68 opponent.incrementMoves();
69 System.out.println("Opponent Moved: "+
70 status.getLastMove()+" with "+
71 status.getSecondsLeft()+" seconds left.");
72 }
73 }
74 }
75
76 printBoard(status, board);
77 status = server.poll();
78
79 if(isGameover(status,board,player))
80 playing = false;
81 }
82 }
83
84 public static void printBoard(StatusResponse status, ChessBoard board) {
85 // print board in console every 5 moves
86 if(status.getLastMoveNumber() % 10 == 0) {
87 System.out.println("Moves: "+
88 status.getLastMoveNumber()+"\n"+
89 board.printState());
90 }
91 }
92
93 public static boolean isGameover(
94 StatusResponse status,
95 ChessBoard board,
96 ChessPlayer player) {
97
98 if(status.isGameover()) {
99 ChessPlayer w = new ChessPlayer(status.getWinner());
100 boolean winner = player.getColor() == w.getColor();
101
102 System.out.println("Moves: "+
103 status.getLastMoveNumber()+"\n"+
104 board.printState());
105
106 if(winner)
107 System.out.println("Congratulations! You Won!");
108 else
109 System.out.println("GAMEOVER! You Lost!");
110
111 return true;
112 }
113 return false;
114 }
115 }