home · contact · privacy
Moved check for existence of active window into shift_window().
[plomrogue] / roguelike.c
1 #include <ncurses.h>
2 #include <string.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include "windows.h"
6
7 struct World {
8   struct KeyBinding * keybindings;
9   struct KeysWinData * keyswindata;
10   int turn;
11   char * log;
12   struct Map * map;
13   struct Monster * monster;
14   struct Player * player; };
15
16 struct KeyBinding {
17   char * name;
18   int key; };
19
20 struct KeysWinData {
21   int max;
22   char edit;
23   int select; };
24
25 struct Map {
26   int width;
27   int height;
28   int offset_x;
29   int offset_y;
30   char * cells; };
31
32 struct Player {
33   int y;
34   int x; };
35
36 struct Monster {
37   int y;
38   int x; };
39
40 void draw_with_linebreaks (struct Win *, char *, int);
41 void draw_text_from_bottom (struct Win *, char *);
42 void draw_log (struct Win *);
43 void draw_map (struct Win *);
44 void draw_info (struct Win *);
45 void draw_keys_window (struct Win *);
46 void toggle_window (struct WinMeta *, struct Win *);
47 void init_keybindings(struct World *);
48 struct Map init_map ();
49 void next_turn (struct World *);
50 void update_log (struct World *, char *);
51 void save_keybindings(struct World *);
52 int get_action_key (struct KeyBinding *, char *);
53 char * get_keyname(int);
54 void keyswin_mod_key (struct World *, struct WinMeta *);
55 void keyswin_move_selection (struct World *, char);
56 char is_passable (struct World *, int, int);
57 void move_player (struct World *, char);
58 void player_wait(struct World *);
59
60 void draw_with_linebreaks (struct Win * win, char * text, int start_y) {
61 // Write text into window content space. Start on row start_y. Fill unused rows with whitespace.
62   int x, y;
63   char toggle;
64   char fin = 0;
65   int z = -1;
66   for (y = start_y; y < win->height; y++) {
67     if (0 == fin)
68       toggle = 0;
69     for (x = 0; x < win->width; x++) {
70        if (0 == toggle) {
71          z++;
72          if ('\n' == text[z]) {
73            toggle = 1;
74            continue; }
75          else
76            mvwaddch(win->curses, y, x, text[z]);
77          if ('\n' == text[z+1]) {
78            z++;
79            toggle = 1; }
80          else if (0 == text[z+1]) {
81             toggle = 1;
82             fin = 1; } } } } }
83
84 void draw_text_from_bottom (struct Win * win, char * text) {
85 // Draw text from end/bottom to the top.
86   char toggle = 0;
87   int x, y, offset;
88   int z = -1;
89   for (y = 0; 0 == toggle; y++)                           // Determine number of lines text would have in
90     for (x = 0; x < win->width; x++) {                    // a window of available width, but infinite height.
91       z++;
92       if ('\n' == text[z])            // Treat \n and \0 as control characters for incrementing y and stopping
93         break;                        // the loop. Make sure they don't count as cell space themselves.
94       if ('\n' == text[z+1]) {
95         z++;
96         break; }
97       else if (0 == text[z+1]) {
98         toggle = 1;
99         break; } }
100   z = -1;
101   int start_y = 0;
102   if (y < win->height)             // Depending on what is bigger, determine start point in window or in text.
103     start_y = win->height - y;
104   else if (y > win->height) {
105     offset = y - win->height;
106     for (y = 0; y < offset; y++)
107       for (x = 0; x < win->width; x++) {
108         z++;
109         if ('\n' == text[z])
110           break;
111         if ('\n' == text[z+1]) {
112           z++;
113           break; } }
114     text = text + (sizeof(char) * (z + 1)); }
115   draw_with_linebreaks(win, text, start_y); }
116
117 void draw_log (struct Win * win) {
118 // Draw log text from world struct in win->data from bottom to top.
119   struct World * world = (struct World *) win->data;
120   draw_text_from_bottom(win, world->log); }
121
122 void draw_map (struct Win * win) {
123 // Draw map determined by win->data Map struct into window. Respect offset.
124   struct World * world = (struct World *) win->data;
125   struct Map * map = world->map;
126   struct Player * player = world->player;
127   struct Monster * monster = world->monster;
128   char * cells = map->cells;
129   int width_map_av = map->width - map->offset_x;
130   int height_map_av = map->height - map->offset_y;
131   int x, y, z;
132   for (y = 0; y < win->height; y++) {
133     z = map->offset_x + (map->offset_y + y) * (map->width);
134     for (x = 0; x < win->width; x++) {
135       if (y < height_map_av && x < width_map_av) {
136         if (z == (map->width * player->y) + player->x)
137           mvwaddch(win->curses, y, x, '@');
138         else if (z == (map->width * monster->y) + monster->x)
139           mvwaddch(win->curses, y, x, 'M');
140         else
141           mvwaddch(win->curses, y, x, cells[z]);
142         z++; } } } }
143
144 void draw_info (struct Win * win) {
145 // Draw info window by appending win->data integer value to "Turn: " display.
146   struct World * world = (struct World *) win->data;
147   int count = world->turn;
148   char text[100];
149   snprintf(text, 100, "Turn: %d", count);
150   draw_with_linebreaks(win, text, 0); }
151
152 void draw_keys_window (struct Win * win) {
153 // Draw keybinding window.
154   struct World * world = (struct World *) win->data;
155   struct KeysWinData * keyswindata = (struct KeysWinData *) world->keyswindata;
156   struct KeyBinding * keybindings = world->keybindings;
157   int offset = 0;
158   if (keyswindata->max >= win->height) {
159     if (keyswindata->select > win->height / 2) {
160       if (keyswindata->select < (keyswindata->max - (win->height / 2)))
161         offset = keyswindata->select - (win->height / 2);
162       else
163         offset = keyswindata->max - win->height + 1; } }
164   int keydescwidth = 9 + 1; // max length assured by get_keyname() + \0
165   char * keydesc = malloc(keydescwidth);
166   attr_t attri;
167   int y, x;
168   char * keyname;
169   for (y = 0; y <= keyswindata->max && y < win->height; y++) {
170     attri = 0;
171     if (y == keyswindata->select - offset) {
172       attri = A_REVERSE;
173       if (1 == keyswindata->edit)
174         attri = attri | A_BLINK; }
175     keyname = get_keyname(keybindings[y + offset].key);
176     snprintf(keydesc, keydescwidth, "%-9s", keyname);
177     free(keyname);
178     for (x = 0; x < win->width; x++)
179       if (x < strlen(keydesc))
180         mvwaddch(win->curses, y, x, keydesc[x] | attri);
181       else if (strlen(keydesc) < x && x < strlen(keybindings[y + offset].name) + strlen(keydesc) + 1)
182         mvwaddch(win->curses, y, x, keybindings[y + offset].name[x - strlen(keydesc) - 1] | attri);
183       else
184         mvwaddch(win->curses, y, x, ' ' | attri); }
185   free(keydesc); }
186
187 void toggle_window (struct WinMeta * win_meta, struct Win * win) {
188 // Toggle display of window win.
189   if (0 != win->curses)
190     suspend_window(win_meta, win);
191   else
192     append_window(win_meta, win); }
193
194 void init_keybindings(struct World * world) {
195 // Initialize keybindings from file "keybindings".
196   FILE * file = fopen("keybindings", "r");
197   int lines = 0;
198   int c = 0;
199   int linemax = 0;
200   int c_count = 0;
201   while (EOF != c) {
202     c_count++;
203     c = getc(file);
204     if ('\n' == c) {
205       if (c_count > linemax)
206         linemax = c_count + 1;
207       c_count = 0;
208       lines++; } }
209   struct KeyBinding * keybindings = malloc(lines * sizeof(struct KeyBinding));
210   fseek(file, 0, SEEK_SET);
211   char * command = malloc(linemax);
212   int commcount = 0;
213   char * cmdptr;
214   while (fgets(command, linemax, file)) {
215     keybindings[commcount].key = atoi(command);
216     cmdptr = strchr(command, ' ') + 1;
217     keybindings[commcount].name = malloc(strlen(cmdptr));
218     memcpy(keybindings[commcount].name, cmdptr, strlen(cmdptr) - 1);
219     keybindings[commcount].name[strlen(cmdptr) - 1] = '\0';
220     commcount++; }
221   free(command);
222   fclose(file);
223   struct KeysWinData * keyswindata = malloc(sizeof(struct KeysWinData));
224   keyswindata->max = lines - 1;
225   keyswindata->select = 0;
226   keyswindata->edit = 0;
227   world->keybindings = keybindings;
228   world->keyswindata = keyswindata; }
229
230 struct Map init_map () {
231 // Initialize map with some experimental start values.
232   struct Map map;
233   map.width = 96;
234   map.height = 32;
235   map.offset_x = 0;
236   map.offset_y = 0;
237   map.cells = malloc(map.width * map.height);
238   int x, y, ran;
239   char terrain;
240   for (y = 0; y < map.height; y++)
241     for (x = 0; x < map.width; x++) {
242       terrain = '.';
243       ran = rand();
244       if (   0 == ran % ((x*x) / 3 + 1)
245           || 0 == ran % ((y*y) / 3 + 1)
246           || 0 == ran % ((map.width - x - 1) * (map.width - x - 1) / 3 + 1)
247           || 0 == ran %((map.height - y - 1) * (map.height - y - 1) / 3 + 1))
248         terrain = ' ';
249       map.cells[(y * map.width) + x] = terrain; }
250   return map; }
251
252 void next_turn (struct World * world) {
253 // Increment turn and move enemy.
254   world->turn++;
255   char d = rand() % 5;
256   char ty = world->monster->y;
257   char tx = world->monster->x;
258   if (1 == d)
259     ty++;
260   else if (2 == d)
261     ty--;
262   else if (3 == d)
263     tx++;
264   else if (4 == d)
265     tx--;
266   if (tx == world->player->x && ty == world->player->y)
267     update_log(world, "\nThe monster hits you.");
268   else if (is_passable(world, tx, ty)) {
269     world->monster->y = ty;
270     world->monster->x = tx; } }
271
272 void update_log (struct World * world, char * text) {
273 // Update log with new text to be appended.
274   char * new_text;
275   int len_old = strlen(world->log);
276   int len_new = strlen(text);
277   int len_whole = len_old + len_new + 1;
278   new_text = calloc(len_whole, sizeof(char));
279   memcpy(new_text, world->log, len_old);
280   memcpy(new_text + len_old, text, len_new);
281   free(world->log);
282   world->log = new_text; }
283
284 void save_keybindings(struct World * world) {
285 // Write keybindings to keybindings file.
286   struct KeysWinData * keyswindata = (struct KeysWinData *) world->keyswindata;
287   struct KeyBinding * keybindings = world->keybindings;
288   FILE * file = fopen("keybindings", "w");
289   int linemax = 0;
290   int i;
291   for (i = 0; i <= keyswindata->max; i++)
292     if (strlen(keybindings[i].name) > linemax)
293       linemax = strlen(keybindings[i].name);
294   linemax = linemax + 6;                                // + 6 = + 3 digits + whitespace + newline + null byte
295   char * line = malloc(linemax);
296   for (i = 0; i <= keyswindata->max; i++) {
297     snprintf(line, linemax, "%d %s\n", keybindings[i].key, keybindings[i].name);
298     fwrite(line, sizeof(char), strlen(line), file); }
299   free(line);
300   fclose(file); }
301
302 int get_action_key (struct KeyBinding * keybindings, char * name) {
303 // Return key matching name in keybindings.
304   int i = 0;
305   while (strcmp(keybindings[i].name, name) )
306     i++;
307   return keybindings[i].key; }
308
309 char * get_keyname(int keycode) {
310 // Translate some keycodes to readable names of max 9 chars.
311   char * keyname;
312   keyname = malloc(15);
313   if (32 < keycode && keycode < 127)
314     sprintf(keyname, "%c", keycode);
315   else if (keycode == 9)
316     sprintf(keyname, "TAB");
317   else if (keycode == 10)
318     sprintf(keyname, "RETURN");
319   else if (keycode == 27)
320     sprintf(keyname, "ESCAPE");
321   else if (keycode == 32)
322     sprintf(keyname, "SPACE");
323   else if (keycode == KEY_UP)
324     sprintf(keyname, "UP");
325   else if (keycode == KEY_DOWN)
326     sprintf(keyname, "DOWN");
327   else if (keycode == KEY_LEFT)
328     sprintf(keyname, "LEFT");
329   else if (keycode == KEY_RIGHT)
330     sprintf(keyname, "RIGHT");
331   else if (keycode == KEY_HOME)
332     sprintf(keyname, "HOME");
333   else if (keycode == KEY_BACKSPACE)
334     sprintf(keyname, "BACKSPACE");
335   else if (keycode >= KEY_F0 && keycode <= KEY_F(63)) {
336     int f = keycode - KEY_F0;
337     sprintf(keyname, "F%d", f); }
338   else if (keycode == KEY_DC)
339     sprintf(keyname, "DELETE");
340   else if (keycode == KEY_IC)
341     sprintf(keyname, "INSERT");
342   else if (keycode == KEY_NPAGE)
343     sprintf(keyname, "NEXT PAGE");
344   else if (keycode == KEY_PPAGE)
345     sprintf(keyname, "PREV PAGE");
346   else if (keycode == KEY_END)
347     sprintf(keyname, "END");
348   else
349     sprintf(keyname, "(unknown)");
350   return keyname;  }
351
352 void keyswin_mod_key (struct World * world, struct WinMeta * win_meta) {
353 // In keybindings window, mark selection modifiable, modify key. Ensure max of three digits in key code field.
354   world->keyswindata->edit = 1;
355   draw_all_windows (win_meta);
356   int key = getch();
357   if (key < 1000)
358     world->keybindings[world->keyswindata->select].key = key;
359   world->keyswindata->edit = 0; }
360
361 void keyswin_move_selection (struct World * world, char dir) {
362 // In keybindings window, move selection upwards or downwards (if within limits of list length).
363   if ('u' == dir && world->keyswindata->select > 0)
364     world->keyswindata->select--;
365   else if ('d' == dir && world->keyswindata->select < world->keyswindata->max)
366     world->keyswindata->select++; }
367
368 char is_passable (struct World * world, int x, int y) {
369 // Check if coordinate on (or beyond) map is accessible to movement.
370   char passable = 0;
371   if (0 <= x && x < world->map->width && 0 <= y && y < world->map->height)
372     if ('.' == world->map->cells[y * world->map->width + x])
373       passable = 1;
374   return passable; }
375
376 void move_player (struct World * world, char d) {
377 // Move player in direction d, increment turn counter and update log.
378   static char prev = 0;
379   char success = 0;
380   char * dir;
381   char ty = world->player->y;
382   char tx = world->player->x;
383   if ('s' == d) {
384     dir = "south";
385     ty++; }
386   if ('n' == d) {
387     dir = "north";
388     ty--; }
389   if ('w' == d) {
390     dir = "west";
391     tx--; }
392   if ('e' == d) {
393     dir = "east";
394     tx++; }
395   if (ty == world->monster->y && tx == world->monster->x)
396     success = 2;
397   else if (is_passable(world, tx, ty)) {
398     success = 1;
399     world->player->y = ty;
400     world->player->x = tx; }
401   if (success * d == prev)
402     update_log (world, ".");
403   else {
404     if (2 == success)
405       update_log (world, "\nYou hit the monster.");
406     else {
407       char * msg = calloc(25, sizeof(char));
408       char * msg_content = "You fail to move";
409       if (1 == success)
410         msg_content = "You move";
411       sprintf(msg, "\n%s %s.", msg_content, dir);
412       update_log (world, msg);
413       free(msg); } }
414   prev = success * d;
415   next_turn (world); }
416
417 void player_wait(struct World * world) {
418 // Make player wait one turn.
419   next_turn (world);
420   update_log (world, "\nYou wait."); }
421
422 int main () {
423   struct World world;
424   init_keybindings(&world);
425   world.turn = 0;
426   world.log = calloc(1, sizeof(char));
427   update_log (&world, "Start!");
428   struct Map map = init_map();
429   world.map = &map;
430   struct Player player;
431   player.y = 16;
432   player.x = 16;
433   world.player = &player;
434   struct Monster monster;
435   monster.y = 16;
436   monster.x = 80;
437   world.monster = &monster;
438
439   WINDOW * screen = initscr();
440   noecho();
441   curs_set(0);
442   keypad(screen, TRUE);
443   raw();
444   struct WinMeta win_meta = init_win_meta(screen);
445
446   struct Win win_keys = init_window(&win_meta, "Keys");
447   win_keys.draw = draw_keys_window;
448   win_keys.data = &world;
449   struct Win win_map = init_window(&win_meta, "Map");
450   win_map.draw = draw_map;
451   win_map.data = &world;
452   struct Win win_info = init_window(&win_meta, "Info");
453   win_info.draw = draw_info;
454   win_info.data = &world;
455   struct Win win_log = init_window(&win_meta, "Log");
456   win_log.draw = draw_log;
457   win_log.data = &world;
458
459   int key;
460   while (1) {
461     draw_all_windows (&win_meta);
462     key = getch();
463     if      (key == get_action_key(world.keybindings, "quit"))
464       break;
465     else if (key == get_action_key(world.keybindings, "scroll pad right"))
466       win_meta.pad_offset++;
467     else if (key == get_action_key(world.keybindings, "scroll pad left") && win_meta.pad_offset > 0)
468       win_meta.pad_offset--;
469     else if (key == get_action_key(world.keybindings, "toggle keys window"))
470       toggle_window(&win_meta, &win_keys);
471     else if (key == get_action_key(world.keybindings, "toggle map window"))
472       toggle_window(&win_meta, &win_map);
473     else if (key == get_action_key(world.keybindings, "toggle info window"))
474       toggle_window(&win_meta, &win_info);
475     else if (key == get_action_key(world.keybindings, "toggle log window"))
476       toggle_window(&win_meta, &win_log);
477     else if (key == get_action_key(world.keybindings, "cycle forwards"))
478       cycle_active_window(&win_meta, 'n');
479     else if (key == get_action_key(world.keybindings, "cycle backwards"))
480       cycle_active_window(&win_meta, 'p');
481     else if (key == get_action_key(world.keybindings, "shift forwards"))
482       shift_window(&win_meta, 'f');
483     else if (key == get_action_key(world.keybindings, "shift backwards"))
484       shift_window(&win_meta, 'b');
485     else if (key == get_action_key(world.keybindings, "grow horizontally") && win_meta.active != 0)
486       resize_window(&win_meta, '*');
487     else if (key == get_action_key(world.keybindings, "shrink horizontally") && win_meta.active != 0)
488       resize_window(&win_meta, '_');
489     else if (key == get_action_key(world.keybindings, "grow vertically") && win_meta.active != 0)
490       resize_window(&win_meta, '+');
491     else if (key == get_action_key(world.keybindings, "shrink vertically") && win_meta.active != 0)
492       resize_window(&win_meta, '-');
493     else if (key == get_action_key(world.keybindings, "save keys"))
494       save_keybindings(&world);
495     else if (key == get_action_key(world.keybindings, "keys nav up"))
496       keyswin_move_selection (&world, 'u');
497     else if (key == get_action_key(world.keybindings, "keys nav down"))
498       keyswin_move_selection (&world, 'd');
499     else if (key == get_action_key(world.keybindings, "keys mod"))
500       keyswin_mod_key (&world, &win_meta);
501     else if (key == get_action_key(world.keybindings, "map up") && map.offset_y > 0)
502       map.offset_y--;
503     else if (key == get_action_key(world.keybindings, "map down"))
504       map.offset_y++;
505     else if (key == get_action_key(world.keybindings, "map right"))
506       map.offset_x++;
507     else if (key == get_action_key(world.keybindings, "map left") && map.offset_x > 0)
508       map.offset_x--;
509     else if (key == get_action_key(world.keybindings, "player down"))
510       move_player(&world, 's');
511     else if (key == get_action_key(world.keybindings, "player up"))
512       move_player(&world, 'n');
513     else if (key == get_action_key(world.keybindings, "player right"))
514       move_player(&world, 'e');
515     else if (key == get_action_key(world.keybindings, "player left"))
516       move_player(&world, 'w');
517     else if (key == get_action_key(world.keybindings, "wait") )
518       player_wait (&world); }
519
520   free(map.cells);
521   for (key = 0; key <= world.keyswindata->max; key++)
522     free(world.keybindings[key].name);
523   free(world.keybindings);
524   free(world.keyswindata);
525   free(world.log);
526
527   endwin();
528   return 0; }