[LIB-9] Add original chesshog source files
[chesshog.git] / src / main / java / org / hedgecode / chess / uci / ExternalEngine.java
1 /*
2  * Copyright (c) 2018. Developed by Hedgecode.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.hedgecode.chess.uci;
18
19 import java.io.BufferedWriter;
20 import java.io.IOException;
21
22 /**
23  * External UCI Engine.
24  *
25  * @author Dmitry Samoshin aka gotty
26  */
27 public class ExternalEngine implements Engine {
28
29     private static final String COMMAND_FORMAT = "%s %s";
30     private static final String CRLF = System.getProperty("line.separator");
31
32     private BufferedWriter engineWriter;
33
34     ExternalEngine(BufferedWriter writer) {
35         engineWriter = writer;
36     }
37
38     private void write(String command) {
39         try {
40             engineWriter.write(command);
41             engineWriter.write(CRLF);
42             engineWriter.flush();
43         } catch (IOException ignored) {
44         }
45     }
46
47     private String format(String name, String params) {
48         return String.format(
49                 COMMAND_FORMAT, name, params
50         );
51     }
52
53     @Override
54     public void init() {
55         write(
56                 UCIConstants.UCI
57         );
58     }
59
60     @Override
61     public void debug(DebugMode mode) {
62         write(
63                 format(
64                         UCIConstants.DEBUG, mode.value()
65                 )
66         );
67     }
68
69     @Override
70     public void isReady() {
71         write(
72                 UCIConstants.IS_READY
73         );
74     }
75
76     @Override
77     public void go() {
78         write(
79                 UCIConstants.GO // todo: + params
80         );
81     }
82
83     @Override
84     public void stop() {
85         write(
86                 UCIConstants.STOP
87         );
88     }
89
90     @Override
91     public void ponderhit() {
92         write(
93                 UCIConstants.PONDER_HIT
94         );
95     }
96
97     @Override
98     public void quit() {
99         write(
100                 UCIConstants.QUIT
101         );
102     }
103
104 }