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