Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- _ _ _
- __| (_) ___| | _____
- / _` | |/ __| |/ / __|
- | (_| | | (__| <\__ \
- \__,_|_|\___|_|\_\___/
- */
- #include <stdio.h>
- #include <ncurses.h>
- #include <string.h>
- #define ROWS 42
- #define COLS 36
- #define PLAYER_STRING "**"
- #define DEFAULT_STRING " "
- void mapopen(char* map[ROWS][COLS]);
- void printmap(char* map[ROWS][COLS]);
- void play(char* map[ROWS][COLS]);
- void walk(char* map[ROWS][COLS], char* row, char* col, char dir);
- char checkcollisions(char* map[ROWS][COLS], char* row, char* col, char dir);
- int main() {
- char row, col;
- char* map[ROWS][COLS];
- /* ncurses initialization, receives single keypresses */
- initscr();
- raw();
- keypad(stdscr, TRUE);
- noecho();
- /* Start with the actual game content */
- mapopen(map);
- play(map);
- /* ncurses footer */
- refresh();
- getch();
- endwin();
- return 0;
- }
- /* Read map from file */
- void mapopen(char* map[ROWS][COLS]) {
- FILE *mapfile = fopen("map", "r");
- char charbuffer[3], row, col;
- /* - Read 2 characters from file, assign to each map grid - */
- row = 0, col = 0;
- while (fgets(charbuffer, 3, mapfile) && row < ROWS) {
- if (*charbuffer != '\n') {map[row][col] = strdup(charbuffer); col++;}
- else {row++; col = 0;}
- }
- fclose(mapfile):
- }
- /* Printf map */
- void printmap(char* map[ROWS][COLS]) {
- char row, col;
- for (row = 0; row < ROWS; row++) {
- for (col = 0; col < COLS; col++) {
- printw("%s", map[row][col]);
- }
- printw("\n");
- }
- }
- /* Start game */
- void play(char* map[ROWS][COLS]) {
- char row = 0, col = 0, input = ' ';
- map[row][col] = PLAYER_STRING;
- while (true) {
- printmap(map);
- input = getch();
- walk(map, &row, &col, input);
- clear();
- }
- }
- /* Move player */
- void walk(char* map[ROWS][COLS], char *row, char *col, char dir) {
- if (!checkcollisions(map, row, col, dir)) {
- switch (dir) {
- case 'w':
- map[*row][*col] = DEFAULT_STRING;
- map[--(*row)][*col] = PLAYER_STRING;
- break;
- case 'a':
- map[*row][*col] = DEFAULT_STRING;
- map[*row][--(*col)] = PLAYER_STRING;
- break;
- case 's':
- map[*row][*col] = DEFAULT_STRING;
- map[++(*row)][*col] = PLAYER_STRING;
- break;
- case 'd':
- map[*row][*col] = DEFAULT_STRING;
- map[*row][++(*col)] = PLAYER_STRING;
- break;
- }
- }
- }
- /* Check map boundaries and validate movements */
- char checkcollisions(char* map[ROWS][COLS], char *row, char *col, char dir) {
- char nextrow = 0, nextcol = 0;
- switch (dir) {
- case 'w':
- nextrow = *row - 1;
- nextcol = *col;
- break;
- case 'a':
- nextrow = *row;
- nextcol = *col - 1;
- break;
- case 's':
- nextrow = *row + 1;
- nextcol = *col;
- break;
- case 'd':
- nextrow = *row;
- nextcol = *col + 1;
- break;
- }
- if (strcmp(map[nextrow][nextcol], DEFAULT_STRING) != 0 || nextrow > (ROWS - 1) || nextcol > (COLS - 1) || nextrow < 0 || nextcol < 0) {return 1;}
- return 0;
- }
Add Comment
Please, Sign In to add comment