Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

161
LINES

< > BotCompany Repo | #1001500 // class Stockfish

JavaX fragment (include)

1  
2  
/**
3  
 * A simple and efficient client to run Stockfish from Java
4  
 * 
5  
 * @author Rahul A R
6  
 *
7  
 */
8  
static class Stockfish {
9  
10  
	private Process engineProcess;
11  
	private BufferedReader processReader;
12  
	private OutputStreamWriter processWriter;
13  
14  
	/**
15  
	 * Starts Stockfish engine as a process and initializes it
16  
	 * 
17  
	 * @param None
18  
	 * @return True on success. False otherwise
19  
	 */
20  
	public boolean startEngine() {
21  
		try {
22  
		  File PATH = loadLibrary("#1001503");
23  
		  makeExecutable(PATH);
24  
			engineProcess = Runtime.getRuntime().exec(PATH.getPath());
25  
			processReader = new BufferedReader(new InputStreamReader(
26  
					engineProcess.getInputStream()));
27  
			processWriter = new OutputStreamWriter(
28  
					engineProcess.getOutputStream());
29  
		} catch (Exception e) {
30  
		  e.printStackTrace();
31  
			return false;
32  
		}
33  
		return true;
34  
	}
35  
36  
	/**
37  
	 * Takes in any valid UCI command and executes it
38  
	 * 
39  
	 * @param command
40  
	 */
41  
	public void sendCommand(String command) {
42  
		try {
43  
			processWriter.write(command + "\n");
44  
			processWriter.flush();
45  
		} catch (IOException e) {
46  
			e.printStackTrace();
47  
		}
48  
	}
49  
50  
	/**
51  
	 * This is generally called right after 'sendCommand' for getting the raw
52  
	 * output from Stockfish
53  
	 * 
54  
	 * @param waitTime
55  
	 *            Time in milliseconds for which the function waits before
56  
	 *            reading the output. Useful when a long running command is
57  
	 *            executed
58  
	 * @return Raw output from Stockfish
59  
	 */
60  
	public String getOutput(int waitTime) {
61  
		StringBuffer buffer = new StringBuffer();
62  
		try {
63  
			Thread.sleep(waitTime);
64  
			sendCommand("isready");
65  
			while (true) {
66  
				String text = processReader.readLine();
67  
				if (text.equals("readyok"))
68  
					break;
69  
				else
70  
					buffer.append(text + "\n");
71  
			}
72  
		} catch (Exception e) {
73  
			e.printStackTrace();
74  
		}
75  
		return buffer.toString();
76  
	}
77  
78  
	/**
79  
	 * This function returns the best move for a given position after
80  
	 * calculating for 'waitTime' ms
81  
	 * 
82  
	 * @param fen
83  
	 *            Position string
84  
	 * @param waitTime
85  
	 *            in milliseconds
86  
	 * @return Best Move in PGN format
87  
	 */
88  
	public String getBestMove(String fen, int waitTime) {
89  
		sendCommand("position fen " + fen);
90  
		sendCommand("go movetime " + waitTime);
91  
		return getOutput(waitTime + 20).split("bestmove ")[1].split(" ")[0];
92  
	}
93  
94  
	/**
95  
	 * Stops Stockfish and cleans up before closing it
96  
	 */
97  
	public void stopEngine() {
98  
		try {
99  
			sendCommand("quit");
100  
			processReader.close();
101  
			processWriter.close();
102  
		} catch (IOException e) {
103  
		}
104  
	}
105  
106  
	/**
107  
	 * Get a list of all legal moves from the given position
108  
	 * 
109  
	 * @param fen
110  
	 *            Position string
111  
	 * @return String of moves
112  
	 */
113  
	public String getLegalMoves(String fen) {
114  
		sendCommand("position fen " + fen);
115  
		sendCommand("d");
116  
		return getOutput(0).split("Legal moves: ")[1];
117  
	}
118  
119  
	/**
120  
	 * Draws the current state of the chess board
121  
	 * 
122  
	 * @param fen
123  
	 *            Position string
124  
	 */
125  
	public void drawBoard(String fen) {
126  
		sendCommand("position fen " + fen);
127  
		sendCommand("d");
128  
129  
		String[] rows = getOutput(0).split("\n");
130  
131  
		for (int i = 1; i < 18; i++) {
132  
			System.out.println(rows[i]);
133  
		}
134  
	}
135  
136  
	/**
137  
	 * Get the evaluation score of a given board position
138  
	 * @param fen Position string
139  
	 * @param waitTime in milliseconds
140  
	 * @return evalScore
141  
	 */
142  
	public float getEvalScore(String fen, int waitTime) {
143  
		sendCommand("position fen " + fen);
144  
		sendCommand("go movetime " + waitTime);
145  
146  
		float evalScore = 0.0f;
147  
		String[] dump = getOutput(waitTime + 20).split("\n");
148  
		for (int i = dump.length - 1; i >= 0; i--) {
149  
			if (dump[i].startsWith("info depth ")) {
150  
				try {
151  
				evalScore = Float.parseFloat(dump[i].split("score cp ")[1]
152  
						.split(" nodes")[0]);
153  
				} catch(Exception e) {
154  
					evalScore = Float.parseFloat(dump[i].split("score cp ")[1]
155  
							.split(" upperbound nodes")[0]);
156  
				}
157  
			}
158  
		}
159  
		return evalScore/100;
160  
	}
161  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1001500
Snippet name: class Stockfish
Eternal ID of this version: #1001500/1
Text MD5: f82eb76c1426e50e52f02a2e02034a55
Author: stefan
Category:
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-10-21 01:15:29
Source code size: 3997 bytes / 161 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 5137 / 4742
Referenced in: [show references]