home · contact · privacy
The monster moves. Contact between monster and player entails hitting each other.
[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 next_turn (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 next_turn (struct World * world) {
250 // Increment turn and move enemy.
251   world->turn++;
252   char d = rand() % 5;
253   char ty = world->monster->y;
254   char tx = world->monster->x;
255   if (1 == d)
256     ty++;
257   else if (2 == d)
258     ty--;
259   else if (3 == d)
260     tx++;
261   else if (4 == d)
262     tx--;
263   if (tx == world->player->x && ty == world->player->y)
264     update_log(world, "\nThe monster hits you.");
265   else if (is_passable(world, tx, ty)) {
266     world->monster->y = ty;
267     world->monster->x = tx; } }
268
269 void update_log (struct World * world, char * text) {
270 // Update log with new text to be appended.
271   char * new_text;
272   int len_old = strlen(world->log);
273   int len_new = strlen(text);
274   int len_whole = len_old + len_new + 1;
275   new_text = calloc(len_whole, sizeof(char));
276   memcpy(new_text, world->log, len_old);
277   memcpy(new_text + len_old, text, len_new);
278   free(world->log);
279   world->log = new_text; }
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 get_action_key (struct KeyBinding * keybindings, char * name) {
300 // Return key matching name in keybindings.
301   int i = 0;
302   while (strcmp(keybindings[i].name, name) )
303     i++;
304   return keybindings[i].key; }
305
306 char * get_keyname(int keycode) {
307 // Translate some keycodes to readable names of max 9 chars.
308   char * keyname;
309   keyname = malloc(15);
310   if (32 < keycode && keycode < 127)
311     sprintf(keyname, "%c", keycode);
312   else if (keycode == 9)
313     sprintf(keyname, "TAB");
314   else if (keycode == 10)
315     sprintf(keyname, "RETURN");
316   else if (keycode == 27)
317     sprintf(keyname, "ESCAPE");
318   else if (keycode == 32)
319     sprintf(keyname, "SPACE");
320   else if (keycode == KEY_UP)
321     sprintf(keyname, "UP");
322   else if (keycode == KEY_DOWN)
323     sprintf(keyname, "DOWN");
324   else if (keycode == KEY_LEFT)
325     sprintf(keyname, "LEFT");
326   else if (keycode == KEY_RIGHT)
327     sprintf(keyname, "RIGHT");
328   else if (keycode == KEY_HOME)
329     sprintf(keyname, "HOME");
330   else if (keycode == KEY_BACKSPACE)
331     sprintf(keyname, "BACKSPACE");
332   else if (keycode >= KEY_F0 && keycode <= KEY_F(63)) {
333     int f = keycode - KEY_F0;
334     sprintf(keyname, "F%d", f); }
335   else if (keycode == KEY_DC)
336     sprintf(keyname, "DELETE");
337   else if (keycode == KEY_IC)
338     sprintf(keyname, "INSERT");
339   else if (keycode == KEY_NPAGE)
340     sprintf(keyname, "NEXT PAGE");
341   else if (keycode == KEY_PPAGE)
342     sprintf(keyname, "PREV PAGE");
343   else if (keycode == KEY_END)
344     sprintf(keyname, "END");
345   else
346     sprintf(keyname, "(unknown)");
347   return keyname;  }
348
349 char is_passable (struct World * world, int x, int y) {
350 // Check if coordinate on (or beyond) map is accessible to movement.
351   char passable = 0;
352   if (0 <= x && x < world->map->width && 0 <= y && y < world->map->height)
353     if ('.' == world->map->cells[y * world->map->width + x])
354       passable = 1;
355   return passable; }
356
357 void move_player (struct World * world, char d) {
358 // Move player in direction d, increment turn counter and update log.
359   static char prev = 0;
360   char success = 0;
361   char * dir;
362   char ty = world->player->y;
363   char tx = world->player->x;
364   if ('s' == d) {
365     dir = "south";
366     ty++; }
367   if ('n' == d) {
368     dir = "north";
369     ty--; }
370   if ('w' == d) {
371     dir = "west";
372     tx--; }
373   if ('e' == d) {
374     dir = "east";
375     tx++; }
376   if (ty == world->monster->y && tx == world->monster->x)
377     success = 2;
378   else if (is_passable(world, tx, ty)) {
379     success = 1;
380     world->player->y = ty;
381     world->player->x = tx; }
382   if (success * d == prev)
383     update_log (world, ".");
384   else {
385     if (2 == success)
386       update_log (world, "\nYou hit the monster.");
387     else {
388       char * msg = calloc(25, sizeof(char));
389       char * msg_content = "You fail to move";
390       if (1 == success)
391         msg_content = "You move";
392       sprintf(msg, "\n%s %s.", msg_content, dir);
393       update_log (world, msg);
394       free(msg); } }
395   prev = success * d;
396   next_turn (world); }
397
398 int main () {
399   struct World world;
400   init_keybindings(&world);
401   world.turn = 0;
402   world.log = calloc(1, sizeof(char));
403   update_log (&world, "Start!");
404   struct Map map = init_map();
405   world.map = &map;
406   struct Player player;
407   player.y = 16;
408   player.x = 16;
409   world.player = &player;
410   struct Monster monster;
411   monster.y = 16;
412   monster.x = 80;
413   world.monster = &monster;
414
415   WINDOW * screen = initscr();
416   noecho();
417   curs_set(0);
418   keypad(screen, TRUE);
419   raw();
420   struct WinMeta win_meta = init_win_meta(screen);
421
422   struct Win win_keys = init_window(&win_meta, "Keys");
423   win_keys.draw = draw_keys_window;
424   win_keys.data = &world;
425   struct Win win_map = init_window(&win_meta, "Map");
426   win_map.draw = draw_map;
427   win_map.data = &world;
428   struct Win win_info = init_window(&win_meta, "Info");
429   win_info.draw = draw_info;
430   win_info.data = &world;
431   struct Win win_log = init_window(&win_meta, "Log");
432   win_log.draw = draw_log;
433   win_log.data = &world;
434
435   int key;
436   while (1) {
437     draw_all_windows (&win_meta);
438     key = getch();
439     if      (key == get_action_key(world.keybindings, "quit"))
440       break;
441     else if (key == get_action_key(world.keybindings, "scroll pad right"))
442       win_meta.pad_offset++;
443     else if (key == get_action_key(world.keybindings, "scroll pad left") && win_meta.pad_offset > 0)
444       win_meta.pad_offset--;
445     else if (key == get_action_key(world.keybindings, "toggle keys window"))
446       toggle_window(&win_meta, &win_keys);
447     else if (key == get_action_key(world.keybindings, "toggle map window"))
448       toggle_window(&win_meta, &win_map);
449     else if (key == get_action_key(world.keybindings, "toggle info window"))
450       toggle_window(&win_meta, &win_info);
451     else if (key == get_action_key(world.keybindings, "toggle log window"))
452       toggle_window(&win_meta, &win_log);
453     else if (key == get_action_key(world.keybindings, "cycle forwards") && win_meta.active != 0)
454       cycle_active_window(&win_meta, 'n');
455     else if (key == get_action_key(world.keybindings, "cycle backwards") && win_meta.active != 0)
456       cycle_active_window(&win_meta, 'p');
457     else if (key == get_action_key(world.keybindings, "shift forwards")  && win_meta.active != 0)
458       shift_window(&win_meta, 'f');
459     else if (key == get_action_key(world.keybindings, "shift backwards") && win_meta.active != 0)
460       shift_window(&win_meta, 'b');
461     else if (key == get_action_key(world.keybindings, "grow horizontally") && win_meta.active != 0)
462       resize_window(&win_meta, '*');
463     else if (key == get_action_key(world.keybindings, "shrink horizontally") && win_meta.active != 0)
464       resize_window(&win_meta, '_');
465     else if (key == get_action_key(world.keybindings, "grow vertically") && win_meta.active != 0)
466       resize_window(&win_meta, '+');
467     else if (key == get_action_key(world.keybindings, "shrink vertically") && win_meta.active != 0)
468       resize_window(&win_meta, '-');
469     else if (key == get_action_key(world.keybindings, "save keys"))
470       save_keybindings(&world);
471     else if (key == get_action_key(world.keybindings, "keys nav up") && world.keyswindata->select > 0)
472       world.keyswindata->select--;
473     else if (key == get_action_key(world.keybindings, "keys nav down") && world.keyswindata->select < world.keyswindata->max)
474       world.keyswindata->select++;
475     else if (key == get_action_key(world.keybindings, "keys mod")) {
476       world.keyswindata->edit = 1;
477       draw_all_windows (&win_meta);
478       key = getch();
479       if (key < 1000) // ensure maximum of three digits in key code field
480         world.keybindings[world.keyswindata->select].key = key;
481       world.keyswindata->edit = 0; }
482     else if (key == get_action_key(world.keybindings, "map up") && map.offset_y > 0)
483       map.offset_y--;
484     else if (key == get_action_key(world.keybindings, "map down"))
485       map.offset_y++;
486     else if (key == get_action_key(world.keybindings, "map right"))
487       map.offset_x++;
488     else if (key == get_action_key(world.keybindings, "map left") && map.offset_x > 0)
489       map.offset_x--;
490     else if (key == get_action_key(world.keybindings, "player down"))
491       move_player(&world, 's');
492     else if (key == get_action_key(world.keybindings, "player up"))
493       move_player(&world, 'n');
494     else if (key == get_action_key(world.keybindings, "player right"))
495       move_player(&world, 'e');
496     else if (key == get_action_key(world.keybindings, "player left"))
497       move_player(&world, 'w');
498     else if (key == get_action_key(world.keybindings, "wait") ) {
499       next_turn (&world);
500       update_log (&world, "\nYou wait."); } }
501
502   free(map.cells);
503   for (key = 0; key <= world.keyswindata->max; key++)
504     free(world.keybindings[key].name);
505   free(world.keybindings);
506   free(world.keyswindata);
507   free(world.log);
508
509   endwin();
510   return 0; }