~ecs/tbrace

tbrace/state.c -rw-r--r-- 2.2 KiB
f007a19d — Eyal Sawady Makefile: rewrite 10 months ago
                                                                                
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

#include "helpers.h"
#include "state.h"

struct state *
load_state(FILE *file)
{
	int num_cars = fgetint("", file);
	int track_x = fgetint("", file);
	int track_y = fgetint("", file);
	struct state *state = malloc(sizeof(struct state));
	int i;

	state->num_cars = num_cars;
	state->cars = calloc(sizeof(struct car), num_cars);
	state->track_x = track_x;
	state->track_y = track_y;
	state->track = malloc(sizeof(enum tile*) * track_y);

	for (i = 0; i < track_y; i++) {
		int j;
		state->track[i] = malloc(sizeof(enum tile) * track_x);
		/* Ignore newline */
		fgetc(file);
		for (j = 0; j < track_x; j++) {
			enum tile current = EMPTY;
			char current_char = fgetc(file);
			switch (current_char) {
			case ' ':
				break;
			case '#':
				current = WALL;
				break;
			case '^':
				current = LAPLINE_UP;
				break;
			case 'V':
				current = LAPLINE_DOWN;
				break;
			case '<':
				current = LAPLINE_LEFT;
				break;
			case '>':
				current = LAPLINE_RIGHT;
				break;
			case '@':
				state->cars[0].x = j;
				state->cars[0].y = i;
				break;
			default:
				state->cars[current_char - '0'].x = j;
				state->cars[current_char - '0'].y = i;
				break;
			}
			state->track[i][j] = current;
		}
	}
	state->ticks = 0;
	return state;
}

void
destroy_state(struct state* state)
{
	int i;
	free(state->cars);
	for (i = 0; i < state->track_y; i++) {
		free(state->track[i]);
	}
	free(state->track);
	free(state);
}

void
print_track(struct state state)
{
	int i;
	for (i = 0; i < state.track_y; i++) {
		int j;
		for (j = 0; j < state.track_x; j++) {
			int car = -1;
			unsigned k;
			for (k = 0; k < state.num_cars; k++) {
				if (state.cars[k].y == i
						&& state.cars[k].x == j) {
					car = k;
				}
			}
			if (car != -1) {
				if (!car) {
					printf("@");
				} else {
					printf("%d", car);
				}
				continue;
			}
			switch (state.track[i][j]) {
			case WALL:
				printf("#");
				break;
			case CAR:
				printf("*");
				break;
			case LAPLINE_UP:
				printf("^");
				break;
			case LAPLINE_DOWN:
				printf("V");
				break;
			case LAPLINE_LEFT:
				printf("<");
				break;
			case LAPLINE_RIGHT:
				printf(">");
				break;
			case EMPTY:
				printf(" ");
				break;
			}
		}
		printf("\n");
	}
}