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