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