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