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