[LIB-9] Separate chesshog-uci module
[chesshog.git] / chesshog-uci / 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.InputStream;
20 import java.io.OutputStream;
21 import java.io.PrintWriter;
22
23 /**
24  * External UCI Engine.
25  *
26  * @author Dmitry Samoshin aka gotty
27  */
28 public class ExternalEngine implements Engine {
29
30     private static final String COMMAND_FORMAT = "%s %s";
31
32     private Transmitter<String> transmitter;
33     private PrintWriter engineWriter;
34
35     ExternalEngine(InputStream input, OutputStream output) {
36         transmitter = new ExternalEngineTransmitter(input);
37         engineWriter = new PrintWriter(output, true);
38     }
39
40     public Transmitter<String> transmitter() {
41         return transmitter;
42     }
43
44     private void write(String command) {
45         engineWriter.println(command);
46     }
47
48     private String format(String name, String params) {
49         return String.format(
50                 COMMAND_FORMAT, name, params
51         );
52     }
53
54     @Override
55     public void init() {
56         write(
57                 UCIConstants.UCI
58         );
59     }
60
61     @Override
62     public void debug(DebugMode mode) {
63         write(
64                 format(
65                         UCIConstants.DEBUG, mode.value()
66                 )
67         );
68     }
69
70     @Override
71     public void isReady() {
72         write(
73                 UCIConstants.IS_READY
74         );
75     }
76
77     @Override
78     public void go() {
79         write(
80                 UCIConstants.GO // todo: + params
81         );
82     }
83
84     @Override
85     public void stop() {
86         write(
87                 UCIConstants.STOP
88         );
89     }
90
91     @Override
92     public void ponderhit() {
93         write(
94                 UCIConstants.PONDER_HIT
95         );
96     }
97
98     @Override
99     public void quit() {
100         write(
101                 UCIConstants.QUIT
102         );
103     }
104
105 }