135 lines
2.7 KiB
C
Raw Permalink Normal View History

2016-07-21 10:22:47 -07:00
#include <stdlib.h>
#include <ncurses.h>
#include <unistd.h>
void quit();
void draw_borders(WINDOW *screen);
int move_player(int keypress, int* player_y, int* player_x);
void refresh_window(WINDOW *screen);
int main(int argc, char *argv[]){
int max_y, max_x, new_y, new_x, field_max_x, field_max_y, player_x, player_y;
int next_x = 0;
int keypress;
int control_size = 5;
initscr(); // Initialize window
noecho(); // Don't echo keypresses
curs_set(FALSE); // No cursor
nodelay(stdscr,1); // Stop getch from waiting.
getmaxyx(stdscr, max_y, max_x); //Get the max x/y of the screen
WINDOW *field = newwin(max_y - control_size, max_x, 0, 0);
WINDOW *controls = newwin(control_size, max_x, max_y - control_size, 0);
draw_borders(field);
draw_borders(controls);
//center player on field
getmaxyx(field, field_max_y, field_max_x);
player_x = field_max_x/2;
player_y = field_max_y/2;
while(1){
getmaxyx(stdscr, new_y, new_x);
keypress = getch(); // Listen for commands; must be before window refresh
if (new_y != max_y || new_x != max_x) {
max_x = new_x;
max_y = new_y;
wresize(field, new_y - control_size, new_x);
wresize(controls, control_size, new_x);
mvwin(controls, new_y - control_size, 0);
wclear(stdscr);
wclear(field);
wclear(controls);
draw_borders(field);
draw_borders(controls);
wrefresh(stdscr);
}
mvwprintw(field, 1, 1, "Field");
mvwprintw(field, player_y, player_x, "o");
mvwprintw(controls, 1, 1, "Commands");
mvwprintw(controls, 3, 1, "^Q to quit");
wrefresh(field);
wrefresh(controls);
if (keypress != -1) {
move_player(keypress, &player_y, &player_x);
refresh_window(field);
}
}
endwin();
return 0;
}
int move_player(int keypress, int* player_y, int* player_x){
if (keypress == 'w'){
*player_y = *player_y - 1;
}
else if (keypress == 'a'){
*player_x = *player_x - 1;
}
else if (keypress == 's'){
*player_y = *player_y + 1;
}
else if (keypress == 'd'){
*player_x = *player_x + 1;
}
else if (keypress == 17) {
quit();
}
}
void refresh_window(WINDOW *screen) {
wclear(screen);
draw_borders(screen);
wrefresh(screen);
}
void draw_borders(WINDOW *screen) {
int x, y, i;
getmaxyx(screen, y, x);
// 4 corners
mvwprintw(screen, 0, 0, "+");
mvwprintw(screen, y - 1, 0, "+");
mvwprintw(screen, 0, x - 1, "+");
mvwprintw(screen, y - 1, x - 1, "+");
// sides
for (i = 1; i < (y - 1); i++) {
mvwprintw(screen, i, 0, "|");
mvwprintw(screen, i, x - 1, "|");
}
// top and bottom
for (i = 1; i < (x - 1); i++) {
mvwprintw(screen, 0, i, "-");
mvwprintw(screen, y - 1, i, "-");
}
}
void quit(){
endwin();
exit(0);
}