Created
January 21, 2018 14:38
-
-
Save Hajto/ae0a3d509b50f4f6718f65099d440e1d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Created by Haito on 19.01.2018. | |
// | |
#include <ncurses.h> | |
#include <unistd.h> | |
#include "minesweaper.h" | |
void initCurses() { | |
initscr(); | |
cbreak(); | |
noecho(); | |
keypad(stdscr, TRUE); | |
} | |
char stateToChar(int state) { | |
if (state == GAME_MINE) return '*'; | |
if (state == GAME_UNALLOCATED) return '#'; | |
else if (state == GAME_FLAGGED_MINE || state == GAME_FALSE_FLAG) return 'F'; | |
else if (state == 0) return ' '; | |
else if (state > 0 && state <= 9) { | |
return (char) (state + 48); //48 is Asci of 0 | |
} else return ' '; | |
} | |
void render_game(Game *game) { | |
mvaddch(0, 0, '+'); | |
mvaddch(game->size_x + 1, 0, '+'); | |
mvaddch(game->size_x + 1, game->size_y + 1, '+'); | |
mvaddch(0, game->size_y + 1, '+'); | |
for (int i = 1; i <= game->size_x; i++) { | |
mvaddch(0, i, '-'); | |
mvaddch(game->size_y + 1, i, '-'); | |
mvaddch(i, 0, '|'); | |
mvaddch(i, game->size_x + 1, '|'); | |
} | |
for (int i = 0; i < game->size_x; i++) { | |
for (int j = 0; j < game->size_y; j++) { | |
char display = stateToChar(game->game_board[i][j]); | |
mvaddch(j + 1, i + 1, display); | |
} | |
} | |
char status[128]; | |
sprintf(status, "Bombs to go: %d", game->bombs_count - game->flags); | |
mvaddstr(game->size_y + 2, 1, status); | |
} | |
void move_in_bound(Game *game, int *x, int *y, int direction) { | |
if (direction == KEY_LEFT && *x > 1) { | |
*x = *x - 1; | |
} else if (direction == KEY_RIGHT && *x < game->size_x) { | |
*x = *x + 1; | |
} else if (direction == KEY_UP && *y > 1) { | |
*y = *y - 1; | |
} else if (direction == KEY_DOWN && *y < game->size_y) { | |
*y = *y + 1; | |
} | |
move(*y, *x); | |
} | |
int start_rendering_loop(Game *game) { | |
initCurses(); | |
render_game(game); | |
int ch; | |
int x = 1, y = 1; | |
while ((ch = getch()) != KEY_F(1)) { | |
move_in_bound(game, &x, &y, ch); | |
if (ch == 10) { /* Enter */ | |
int result = make_move(game, x - 1, y - 1); | |
if (result == GAME_STATUS_OK) { | |
render_game(game); | |
} else if (result == GAME_STATUS_BOOM) { | |
endwin(); | |
return GAME_STATUS_BOOM; | |
} | |
} else if(ch == 102){ //TAB | |
mark_bomb(game, x-1, y-1); | |
if(game->bombs_count == 0) | |
return GAME_STATUS_OK; | |
render_game(game); | |
} | |
move(y,x); | |
refresh(); | |
} | |
endwin(); | |
return GAME_STATUS_OK; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment