所以这就像一个基本的服务器/客户端游戏,但数字必须由客户端生成。客户端必须进行逻辑猜测,例如,如果服务器将"输入较小的数字"设置为5,将"输入较大的数字"设为0,则客户端的猜测必须在0到5之间。我该怎么做这部分?
如果您的问题是服务器/客户端实现,那么您应该研究一下套接字:
https://docs.oracle.com/javase/tutorial/networking/sockets/index.html
如果是客户端"猜测"的部分,最简单的实现就是在你不认为"太高"的最小数字和你知道"太低"的最大数字之间保持一半,比如:
public class NumberGuessingClientExample {
public static void main(String[] args) {
new NumberGuessingClient(new ServerStub()).findNumber();
}
public static class NumberGuessingClient {
private int min = Integer.MIN_VALUE;
private int max = Integer.MAX_VALUE;
private final NumberGuessingServer server;
public NumberGuessingClient(NumberGuessingServer server) {
this.server = server;
}
public int findNumber() {
Result result = null;
int value = nextGuess();
while ((result = server.makeGuess(value)) != Result.CORRECT) {
System.out.println(value + " = " + result);
if (result == Result.TOO_HIGH) {
max = value - 1;
} else if (result == Result.TOO_LOW) {
min = value + 1;
}
value = nextGuess();
}
System.out.println(value);
return value;
}
private int nextGuess() {
return (int) ((((long) max - (long) min) / 2) + min);
}
}
public interface NumberGuessingServer {
Result makeGuess(int value);
}
public static class ServerStub implements NumberGuessingServer {
private static final int RESULT = 3;
public Result makeGuess(int value) {
if (value > RESULT) {
return Result.TOO_HIGH;
}
if (value < RESULT) {
return Result.TOO_LOW;
}
return Result.CORRECT;
}
}
public enum Result {
CORRECT, TOO_HIGH, TOO_LOW
}
}