summaryrefslogtreecommitdiff
path: root/turtle.c
diff options
context:
space:
mode:
Diffstat (limited to 'turtle.c')
-rw-r--r--turtle.c112
1 files changed, 112 insertions, 0 deletions
diff --git a/turtle.c b/turtle.c
new file mode 100644
index 0000000..8dfeafc
--- /dev/null
+++ b/turtle.c
@@ -0,0 +1,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");
+ }
+}