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