summaryrefslogtreecommitdiff
path: root/src/main.c
blob: 2eacd474eaf3f7f677358dd3280675be5524ed13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "TZR.h"
#include "cfg.h"
#include "log.h"
#include "netcode.h"

static void deinit(void);
static int main_loop(void *udata);

int
main(int argc, char **argv)
{
	(void)argc, (void)argv;

	char p1_white;
	if (argc > 1) {
		log_info("client, connecting to %s", argv[1]);
		if (netcode_init_client(argv[1], 8177)) {
			log_error("netcode_init_client failed");
			return -1;
		}
		if (netcode_recv(&p1_white, 1)) {
			log_error("netcode_send failed");
			netcode_deinit();
			return -1;
		}
	} else {
		log_info("host");
		if (netcode_init_host(8177)) {
			log_error("netcode_init_host failed");
			return -1;
		}
		srand(time(NULL));
		p1_white = rand() % 2;
		if (netcode_send(&p1_white, 1)) {
			log_error("netcode_send failed");
			netcode_deinit();
			return -1;
		}
	}

	log_info("i'm %s", (p1_white ^ netcode_host()) ? "black" : "white");

	if (TZR_Init(.width=DWIDTH, .height=DHEIGHT, .target_fps=FPS))
		return 1;
	if (atexit(deinit)) {
		deinit();
		return 1;
	}

	return TZR_MainLoop(main_loop, NULL);
}

static void
deinit(void)
{
	TZR_Quit();
	log_info("closing connection");
	netcode_deinit();
}

static int
main_loop(void *udata)
{
	(void)udata;

	TZR_DrawBegin();
	TZR_DrawEnd();

	if (netcode_ping()) {
		log_error("netcode_ping failed");
		return -1;
	}

	return 0;
}