summaryrefslogtreecommitdiff
path: root/turtle.c
blob: 8dfeafcff926e63390dd08d30ca839ede49e7f9a (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
108
109
110
111
112
#include "turtle.h"
/*assigns initial values to turtle position*/
int tx = 0;
int ty = 0;
int td = UP;
/*loads a map from a 20x20 ascii plaintext file excluding newlines*/
/* returns any io errors*/
/*returns 0 on sucess */
int loadmap(char * filename) {
	/*file of the map to load*/
	FILE * mapfile = fopen(filename,"r");
	if (mapfile == NULL) {
		printf("error loading map file\n");
		return -1;
	}
	for (int yi = 0; yi < 20; yi++) {
		for (int xi = 0; xi < 20; xi++) {
			map[xi][yi] = fgetc(mapfile);
			if (map[xi][yi] == EOF) {
				return EOF;
			}
		}
		/*to account for newlines*/
		fgetc(mapfile);
	}
	printmap();
	return 0;
}
/*moves the turtle, will keep moving until either blocks runs out or it can't
 * moveforwards anymore, only non '#' chars can be moveable*/
void go(int blocks){
	/*position of blocks to move to*/
	unsigned int mx, my;
	for (int i = 0; i < blocks; i++) {
		switch (td) {
			/*using modulus to wrap them around*/
			case UP:
				mx = (tx)%20;
				my = (ty - 1)%20;
			break;
			case DOWN:
				mx = (tx)%20;
				my = (ty + 1)%20;
			break;
			case LEFT:
				mx = (tx + 1)%20;
				my = (ty)%20;
			break;
			case RIGHT:
				mx = (tx - 1)%20;
				my = (ty)%20;
			break;
		}
		/*keeps turtle in the boundaries of the map*/
		if(mx < 0) {
			mx = 0;
		}
		if(mx >= 20) {
			mx = 19;
		}
		if(my < 0) {
			my = 0;
		}
		if(my >= 20) {
			my = 19;
		}
		if (map[mx][my] != '#') {
			tx = mx;
			ty = my;
		}
		printmap();
		/*victory screen*/
		if (map[tx][ty] == '$') {
			printf("YOU WON! CONGRATS!\n");
		}
		sleep(1);
	}
}
/*sets the irction, no sanity checking*/
void turn(int direction){
	td = direction;
	printmap();
	sleep(1);
	return;
}
void printmap() {
	/*terminal escape code to move cursor to 0,0*/
	printf("\033[1;1H");
	for (int yi = 0; yi < 20; yi++) {
		for (int xi = 0; xi < 20; xi++) {
			if ((yi == ty) && (xi == tx)){
				switch (td) {
					case UP:
						printf("\033[32m^\033[37m");
					break;
					case DOWN:
						printf("\033[32mV\033[37m");
					break;
					case LEFT:
						printf("\033[32m>\033[37m");
					break;
					case RIGHT:
						printf("\033[32m<\033[37m");
					break;
				}
			} else {
				printf("%c",map[xi][yi]);
			}
		}
		printf("\n");
	}
}