home · contact · privacy
Corrected mixed up coordinates.
[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 = 128;
223   map.height = 128;
224   map.offset_x = 0;
225   map.offset_y = 0;
226   map.cells = malloc(map.width * map.height);
227   int x, y;
228   for (y = 0; y < map.height; y++)
229     for (x = 0; x < map.width; x++)
230       map.cells[(y * map.width) + x] = '.';
231   map.cells[(5 * map.width) + 5] = 'X';
232   map.cells[(3 * map.width) + 8] = 'X';
233   map.cells[(8 * map.width) + 3] = 'X';
234   return map; }
235
236 void update_info (struct World * world) {
237 // Update info data by incrementing turn value.
238   world->turn++; }
239
240 void update_log (struct World * world, char * text) {
241 // Update log with new text to be appended.
242   char * new_text;
243   int len_old = strlen(world->log);
244   int len_new = strlen(text);
245   int len_whole = len_old + len_new + 1;
246   new_text = calloc(len_whole, sizeof(char));
247   memcpy(new_text, world->log, len_old);
248   memcpy(new_text + len_old, text, len_new);
249   free(world->log);
250   world->log = new_text; }
251
252 void save_keybindings(struct World * world) {
253 // Write keybindings to keybindings file.
254   struct KeysWinData * keyswindata = (struct KeysWinData *) world->keyswindata;
255   struct KeyBinding * keybindings = world->keybindings;
256   FILE * file = fopen("keybindings", "w");
257   int linemax = 0;
258   int i;
259   for (i = 0; i <= keyswindata->max; i++)
260     if (strlen(keybindings[i].name) > linemax)
261       linemax = strlen(keybindings[i].name);
262   linemax = linemax + 6;                                // + 6 = + 3 digits + whitespace + newline + null byte
263   char * line = malloc(linemax);
264   for (i = 0; i <= keyswindata->max; i++) {
265     snprintf(line, linemax, "%d %s\n", keybindings[i].key, keybindings[i].name);
266     fwrite(line, sizeof(char), strlen(line), file); }
267   free(line);
268   fclose(file); }
269
270 int get_action_key (struct KeyBinding * keybindings, char * name) {
271 // Return key matching name in keybindings.
272   int i = 0;
273   while (strcmp(keybindings[i].name, name) )
274     i++;
275   return keybindings[i].key; }
276
277 char * get_keyname(int keycode) {
278 // Translate some keycodes to readable names of max 9 chars.
279   char * keyname;
280   keyname = malloc(15);
281   if (32 < keycode && keycode < 127)
282     sprintf(keyname, "%c", keycode);
283   else if (keycode == 9)
284     sprintf(keyname, "TAB");
285   else if (keycode == 10)
286     sprintf(keyname, "RETURN");
287   else if (keycode == 27)
288     sprintf(keyname, "ESCAPE");
289   else if (keycode == 32)
290     sprintf(keyname, "SPACE");
291   else if (keycode == KEY_UP)
292     sprintf(keyname, "UP");
293   else if (keycode == KEY_DOWN)
294     sprintf(keyname, "DOWN");
295   else if (keycode == KEY_LEFT)
296     sprintf(keyname, "LEFT");
297   else if (keycode == KEY_RIGHT)
298     sprintf(keyname, "RIGHT");
299   else if (keycode == KEY_HOME)
300     sprintf(keyname, "HOME");
301   else if (keycode == KEY_BACKSPACE)
302     sprintf(keyname, "BACKSPACE");
303   else if (keycode >= KEY_F0 && keycode <= KEY_F(63)) {
304     int f = keycode - KEY_F0;
305     sprintf(keyname, "F%d", f); }
306   else if (keycode == KEY_DC)
307     sprintf(keyname, "DELETE");
308   else if (keycode == KEY_IC)
309     sprintf(keyname, "INSERT");
310   else if (keycode == KEY_NPAGE)
311     sprintf(keyname, "NEXT PAGE");
312   else if (keycode == KEY_PPAGE)
313     sprintf(keyname, "PREV PAGE");
314   else if (keycode == KEY_END)
315     sprintf(keyname, "END");
316   else
317     sprintf(keyname, "(unknown)");
318   return keyname;  }
319
320 char is_passable (struct World * world, int x, int y) {
321 // Check if coordinate on (or beyond) map is accessible to movement.
322   char passable = 0;
323   if (0 <= x && x < world->map->width && 0 <= y && y < world->map->height)
324     if ('.' == world->map->cells[y * world->map->width + x])
325       passable = 1;
326   return passable; }
327
328 void move_player (struct World * world, char d) {
329 // Move player in direction d, increment turn counter and update log.
330   static char prev = 0;
331   char success = 0;
332   char * dir;
333   if ('s' == d) {
334     dir = "south";
335     if (is_passable(world, world->player->x, world->player->y + 1)) {
336       world->player->y++;
337       success = 1; } }
338   else if ('n' == d) {
339     dir = "north";
340     if (is_passable(world, world->player->x, world->player->y - 1)) {
341       world->player->y--;
342       success = 1; } }
343   else if ('w' == d) {
344     dir = "west";
345     if (is_passable(world, world->player->x - 1, world->player->y)) {
346       world->player->x--;
347       success = 1; } }
348   else if ('e' == d) {
349     dir = "east";
350     if (is_passable(world, world->player->x + 1, world->player->y)) {
351       world->player->x++;
352       success = 1; } }
353   if (success * d == prev)
354     update_log (world, ".");
355   else {
356   char * msg = calloc(25, sizeof(char));
357     char * msg_content = "You fail to move";
358     if (success)
359       msg_content = "You move";
360     sprintf(msg, "\n%s %s.", msg_content, dir);
361     update_log (world, msg);
362     free(msg); }
363   prev = success * d;
364   update_info (world); }
365
366 int main () {
367   struct World world;
368   init_keybindings(&world);
369   world.turn = 0;
370   world.log = calloc(1, sizeof(char));
371   update_log (&world, "Start!");
372   struct Map map = init_map();
373   world.map = &map;
374   struct Player player;
375   player.y = 2;
376   player.x = 2;
377   world.player = &player;
378
379   WINDOW * screen = initscr();
380   noecho();
381   curs_set(0);
382   keypad(screen, TRUE);
383   raw();
384   struct WinMeta win_meta = init_win_meta(screen);
385
386   struct Win win_keys = init_window(&win_meta, "Keys");
387   win_keys.draw = draw_keys_window;
388   win_keys.data = &world;
389   struct Win win_map = init_window(&win_meta, "Map");
390   win_map.draw = draw_map;
391   win_map.data = &world;
392   struct Win win_info = init_window(&win_meta, "Info");
393   win_info.draw = draw_info;
394   win_info.data = &world;
395   struct Win win_log = init_window(&win_meta, "Log");
396   win_log.draw = draw_log;
397   win_log.data = &world;
398
399   int key;
400   while (1) {
401     draw_all_windows (&win_meta);
402     key = getch();
403     if      (key == get_action_key(world.keybindings, "quit"))
404       break;
405     else if (key == get_action_key(world.keybindings, "scroll pad right"))
406       win_meta.pad_offset++;
407     else if (key == get_action_key(world.keybindings, "scroll pad left") && win_meta.pad_offset > 0)
408       win_meta.pad_offset--;
409     else if (key == get_action_key(world.keybindings, "toggle keys window"))
410       toggle_window(&win_meta, &win_keys);
411     else if (key == get_action_key(world.keybindings, "toggle map window"))
412       toggle_window(&win_meta, &win_map);
413     else if (key == get_action_key(world.keybindings, "toggle info window"))
414       toggle_window(&win_meta, &win_info);
415     else if (key == get_action_key(world.keybindings, "toggle log window"))
416       toggle_window(&win_meta, &win_log);
417     else if (key == get_action_key(world.keybindings, "cycle forwards") && win_meta.active != 0)
418       cycle_active_window(&win_meta, 'n');
419     else if (key == get_action_key(world.keybindings, "cycle backwards") && win_meta.active != 0)
420       cycle_active_window(&win_meta, 'p');
421     else if (key == get_action_key(world.keybindings, "shift forwards")  && win_meta.active != 0)
422       shift_window(&win_meta, 'f');
423     else if (key == get_action_key(world.keybindings, "shift backwards") && win_meta.active != 0)
424       shift_window(&win_meta, 'b');
425     else if (key == get_action_key(world.keybindings, "grow horizontally") && win_meta.active != 0)
426       resize_window(&win_meta, '*');
427     else if (key == get_action_key(world.keybindings, "shrink horizontally") && win_meta.active != 0)
428       resize_window(&win_meta, '_');
429     else if (key == get_action_key(world.keybindings, "grow vertically") && win_meta.active != 0)
430       resize_window(&win_meta, '+');
431     else if (key == get_action_key(world.keybindings, "shrink vertically") && win_meta.active != 0)
432       resize_window(&win_meta, '-');
433     else if (key == get_action_key(world.keybindings, "save keys"))
434       save_keybindings(&world);
435     else if (key == get_action_key(world.keybindings, "keys nav up") && world.keyswindata->select > 0)
436       world.keyswindata->select--;
437     else if (key == get_action_key(world.keybindings, "keys nav down") && world.keyswindata->select < world.keyswindata->max)
438       world.keyswindata->select++;
439     else if (key == get_action_key(world.keybindings, "keys mod")) {
440       world.keyswindata->edit = 1;
441       draw_all_windows (&win_meta);
442       key = getch();
443       if (key < 1000) // ensure maximum of three digits in key code field
444         world.keybindings[world.keyswindata->select].key = key;
445       world.keyswindata->edit = 0; }
446     else if (key == get_action_key(world.keybindings, "map up") && map.offset_y > 0)
447       map.offset_y--;
448     else if (key == get_action_key(world.keybindings, "map down"))
449       map.offset_y++;
450     else if (key == get_action_key(world.keybindings, "map right"))
451       map.offset_x++;
452     else if (key == get_action_key(world.keybindings, "map left") && map.offset_x > 0)
453       map.offset_x--;
454     else if (key == get_action_key(world.keybindings, "player down"))
455       move_player(&world, 's');
456     else if (key == get_action_key(world.keybindings, "player up"))
457       move_player(&world, 'n');
458     else if (key == get_action_key(world.keybindings, "player right"))
459       move_player(&world, 'e');
460     else if (key == get_action_key(world.keybindings, "player left"))
461       move_player(&world, 'w');
462     else if (key == get_action_key(world.keybindings, "wait") ) {
463       update_info (&world);
464       update_log (&world, "\nYou wait."); } }
465
466   free(map.cells);
467   for (key = 0; key <= world.keyswindata->max; key++)
468     free(world.keybindings[key].name);
469   free(world.keybindings);
470   free(world.keyswindata);
471   free(world.log);
472
473   endwin();
474   return 0; }