Java猜数字游戏(不带扫描仪)

时间:2018-12-09 11:28:24

标签: java server client

因此,这就像一个基本的服务器/客户端游戏,但是数字必须由客户端生成,并且客户端也必须做出逻辑猜测,例如,如果服务器说“输入较小的数字”到5并“输入较大的数字”数字”设为0,则客户的猜测必须在0到5之间。我该如何做这部分?

2 个答案:

答案 0 :(得分:0)

如果您的问题是服务器/客户端实现,则应该研究一些有关套接字的信息:

https://docs.oracle.com/javase/tutorial/networking/sockets/index.html

答案 1 :(得分:0)

如果这是您正在苦苦挣扎的客户端“猜测”部分,那么最简单的实现就是简单地将最小的数字(不要过高)和最大的数字(过低)保持在中间,类似:

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
}

}