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