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