hanze/game-client

src/main/java/nl/isygameclient/network/GameClient.java in main
Repositories | Summary | Log | Files

GameClient.java (2105B) download


 1package nl.isygameclient.network;
 2
 3import java.io.IOException;
 4import java.util.List;
 5import java.util.Map;
 6import java.util.Random;
 7
 8public class GameClient extends GameClientBase {
 9	private String name;
10
11	public GameClient(String host, int port) throws IOException {
12		super(host, port);
13	}
14
15	public String getName() {
16		return name;
17	}
18
19	@SuppressWarnings("unchecked")
20	public List<String> games() throws IOException {
21		send("get gamelist");
22
23		return (List<String>) event(EventType.GAMELIST).data;
24	}
25
26	@SuppressWarnings("unchecked")
27	public List<String> players() throws IOException {
28		send("get playerlist");
29
30		return (List<String>) event(EventType.GAMELIST).data;
31	}
32
33	public void login(String name) throws IOException {
34		this.name = name;
35
36		send("login", name);
37	}
38
39	public Match match(GameType game, String other) throws IOException {
40		send("challenge", other, game.name);
41
42		return new Match(this);
43	}
44
45	public Match match(GameType game) throws IOException {
46		send("subscribe", game.name);
47
48		return new Match(this);
49	}
50
51	public Match match() throws IOException {
52		@SuppressWarnings("unchecked")
53		var challengeEvent = (Map<String, String>) event(-1, EventType.CHALLENGE).data;
54		var challengeID	   = challengeEvent.get("challengenumber");
55		send("challenge", "accept", challengeID);
56
57		return new Match(this);
58	}
59
60	public static void main(String[] args) throws IOException {
61		var name   = "testclient" + new Random().nextInt(100);
62		var client = new GameClient("localhost", 7789);	   // public: 145.33.225.170
63
64		client.login(name);
65		System.out.println("connected as " + name);
66
67		var current = client.match(GameType.TICTACTOE4);
68		for (;;) {
69			while (current.update()) {
70				int move;
71				do {
72					move = new Random().nextInt(current.getGame().maxMoves);
73				} while (current.getMove(move) != 0);
74				current.move(move);
75			}
76			System.out.printf("[%4s] %02d:%02d\n", current.getOutcome().type, current.getPointsSelf(), current.getPointsOther());
77			if (current.getPointsSelf() >= 10 || current.getPointsOther() >= 10)
78				break;
79
80			current.rematch();
81		}
82
83		client.close();
84	}
85}