teaching

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

main.c (1525B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 #include <unistd.h>
      5 #include <fcntl.h>
      6 
      7 #define MAPW 30
      8 #define MAPH 30
      9 
     10 struct vec2 {
     11 	int x, y;
     12 };
     13 
     14 char map[MAPH][MAPW] = {0};
     15 char scr[MAPH][MAPW] = {0};
     16 
     17 void
     18 drawbox(struct vec2 pos, struct vec2 size) {
     19 	for (int y = pos.y; y < size.y + pos.y; y++) {
     20 		for (int x = pos.x; x < size.x + pos.x; x++) {
     21 
     22 			if (y == pos.y && x == pos.x)
     23 				map[y][x] = '/';
     24 
     25 			else if (y == pos.y && x == pos.x + size.x - 1)
     26 				map[y][x] = '\\';
     27 
     28 			else if (y == pos.y + size.y - 1 && x == pos.x) 
     29 				map[y][x] = '\\';
     30 
     31 			else if (y == pos.y + size.y - 1 && x == pos.x + size.x -1)
     32 				map[y][x] = '/';
     33 
     34 			else if (y == pos.y + size.y - 1 || y == pos.y) 
     35 				map[y][x] = '-';
     36 
     37 			else if (x == pos.x + size.x - 1 || x == pos.x)
     38 				map[y][x] = '|';
     39 		}
     40 	}
     41 }
     42 
     43 void
     44 printscr() {
     45 	for (int y = 0; y < MAPH; y++) {
     46 		for (int x = 0; x < MAPW; x++) {
     47 			printf("%c", scr[y][x]);
     48 		}
     49 		printf("\n\r");
     50 	}
     51 }
     52 
     53 int
     54 main() {
     55 	struct vec2 player = {10, 10};
     56 
     57 	fcntl(0, F_SETFL, O_NONBLOCK);
     58 
     59 	memset(map, ' ', MAPH * MAPW);
     60 	struct vec2 pos = {5,5};
     61 	struct vec2 size = {5,5};
     62 	drawbox(pos, size);
     63 
     64 	char in;
     65 
     66 	for (;;) {
     67 		memcpy(scr, map, MAPH * MAPW); 
     68 		scr[player.y][player.x] = '@';
     69 
     70 		read(0, &in, 1);
     71 		switch (in) {
     72 		case 'w':
     73 			player.y--;
     74 			break;
     75 		case 's':
     76 			player.y++;
     77 			break;
     78 		case 'a':
     79 			player.x--;
     80 			break;
     81 		case 'd':
     82 			player.x++;
     83 			break;
     84 		case 'q':
     85 			goto end;
     86 		}
     87 		in = 0;
     88 
     89 		printf("\033c");
     90 		printscr();
     91 		usleep(32000);
     92 	}
     93 end:
     94 	return 0;
     95 }