summaryrefslogtreecommitdiffstats
path: root/src/game.c
blob: 9f7cebd7c64b973f169766ae3dddc60604ca4173 (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <stdlib.h>
#include <unistd.h>
#include <curses.h>

#include "game.h"
#include "player.h"
#include "paddle.h"

static void wait(struct game *g);
static void input(struct game *g);
static void update(struct game *g);
static void draw(struct game *g);

struct game *
new_game(void)
{
	struct game *g;

	g = malloc(sizeof(*g));
	if (g == NULL) {
		return NULL;
	}

	g->players[0] = new_player(0);
	g->players[1] = new_player(1);

	return g;
}

void
free_game(struct game *g)
{
	free_player(g->players[0]);
	free_player(g->players[1]);

	free(g);
}

void
run_game(struct game *g)
{
	g->running = 1;

	while (g->running) {
		input(g);
		update(g);
		draw(g);
		wait(g);
	}
}

static void
wait(struct game *g)
{
	++g;
	usleep(10000);
}

static void
input(struct game *g)
{
	int c;

	timeout(0);
	for (;;) {
		c = getch();
		if (c == 'q') {
			g->running = 0;
		} else if (c == ERR) {
			break;
		} else if (c == 'a') {
			g->players[0]->paddle_h.dir = -1;
		} else if (c == 'd') {
			g->players[0]->paddle_h.dir = 1;
		} else if (c == 'w') {
			g->players[0]->paddle_v.dir = -1;
		} else if (c == 's') {
			g->players[0]->paddle_v.dir = 1;
		} else if (c == KEY_LEFT) {
			g->players[1]->paddle_h.dir = -1;
		} else if (c == KEY_RIGHT) {
			g->players[1]->paddle_h.dir = 1;
		} else if (c == KEY_UP) {
			g->players[1]->paddle_v.dir = -1;
		} else if (c == KEY_DOWN) {
			g->players[1]->paddle_v.dir = 1;
		}
	}
}

static void
update(struct game *g)
{
	update_paddle(&g->players[0]->paddle_h);
	update_paddle(&g->players[0]->paddle_v);
	update_paddle(&g->players[1]->paddle_h);
	update_paddle(&g->players[1]->paddle_v);
}

static void
draw(struct game *g)
{
	draw_paddle(&g->players[0]->paddle_h);
	draw_paddle(&g->players[0]->paddle_v);
	draw_paddle(&g->players[1]->paddle_h);
	draw_paddle(&g->players[1]->paddle_v);
}