c091dd46ab5b05b25a02edbf050c72a0d59aa7c1
[rfk] / rfk.c
1 /*  robotfindskitten for maemo
2  *  original by Leonard Richardson, 1997
3  *  ported to maemo by Thomas Thurman, 2009
4  *  suggestions welcome
5  *  Compile with:
6  *  gcc -Wall -g rfk.c -o rfk `pkg-config --cflags --libs gtk+-2.0 hildon-1 dbus-glib-1 dbus-1`
7  */
8
9 #include <dbus/dbus-glib.h>
10 #include <gtk/gtk.h>
11 #include <stdlib.h>
12 #include <glib.h>
13 #include <hildon/hildon.h>
14 #include <math.h>
15 #include <stdio.h>
16 #include <string.h>
17
18 #define ARENA_WIDTH 25
19 #define ARENA_HEIGHT 12
20
21 const int amount_of_random_stuff = 15;
22
23 typedef enum {
24   STATE_PROLOGUE,
25   STATE_PLAYING,
26   STATE_EPILOGUE,
27   STATE_LAST
28 } StateOfPlay;
29
30 StateOfPlay current_state = STATE_LAST;
31 GtkWidget* state_widget[STATE_LAST];
32
33 GSList *nki = NULL;
34 guint nki_count = 0;
35
36 GtkWidget *arena[ARENA_WIDTH][ARENA_HEIGHT];
37 GtkWidget *window, *robot, *kitten;
38 int robot_x, robot_y;
39 gboolean *used = NULL;
40
41 GdkPixbuf *robot_pic, *love_pic, *kitten_pic;
42
43 const GdkColor black = { 0, };
44
45 /****************************************************************/
46 /* Random object descriptions.                                  */
47 /****************************************************************/
48
49 char *
50 description (void)
51 {
52   int r;
53    
54   do
55     {
56       r = random() % nki_count;
57     }
58   while (used[r]);
59
60   used[r] = TRUE;
61   return g_slist_nth_data (nki, r);
62 }
63
64 /****************************************************************/
65 /* Placing objects.                                             */
66 /****************************************************************/
67
68 void
69 place_in_arena_at_xy (GtkWidget *item, int x, int y)
70 {
71   arena[x][y] = item;
72
73   gtk_table_attach_defaults (GTK_TABLE (state_widget[STATE_PLAYING]),
74                              item,
75                              x, x+1,
76                              y, y+1);
77
78   if (item==robot)
79     {
80       robot_x = x;
81       robot_y = y;
82     }
83 }
84
85 void
86 place_in_arena_randomly (GtkWidget *item)
87 {
88   int x, y;
89    
90   do
91     {
92       x = random() % ARENA_WIDTH;
93       y = random() % ARENA_HEIGHT;
94     }
95   while (arena[x][y]);
96
97   place_in_arena_at_xy (item, x, y);
98 }
99
100 /****************************************************************/
101 /* Labels representing things the robot might find.             */
102 /****************************************************************/
103
104 GtkWidget *
105 random_character (gchar *description)
106 {
107   gchar character[2] = { random() % ('~'-'!') + '!', 0 };
108   gchar *escaped_character = g_markup_escape_text (character, -1);
109   gchar *markup = g_strdup_printf ("<span color=\"#%02x%02x%02x\">%s</span>",
110                                    (int) (random() % 0x7F)+0x80,
111                                    (int) (random() % 0x7F)+0x80,
112                                    (int) (random() % 0x7F)+0x80,
113                                    escaped_character);
114   GtkWidget *result = gtk_label_new (NULL);
115   gtk_label_set_markup (GTK_LABEL (result), markup);
116   g_free (markup);
117   g_free (escaped_character);
118
119   g_object_set_data (G_OBJECT (result), "examine", description);
120
121   return result;
122 }
123
124 /****************************************************************/
125 /* Talking back to the user.                                    */
126 /****************************************************************/
127
128 void
129 show_message (const char *message)
130 {
131   HildonNote* note = HILDON_NOTE
132     (hildon_note_new_information (GTK_WINDOW (window),
133                                   message?message:
134                                   "Some message was supposed to be here."));
135   gtk_dialog_run (GTK_DIALOG (note));
136   gtk_widget_destroy (GTK_WIDGET (note));
137 }
138
139 /****************************************************************/
140 /* Loading the non-kitten objects.                              */
141 /****************************************************************/
142 void
143 ensure_messages_loaded (void)
144 {
145   FILE *nki_file = NULL;
146   gchar *line = NULL;
147   gboolean headers = TRUE;
148
149   if (nki_count)
150     return;
151
152   nki_file = fopen ("/usr/share/rfk/non-kitten-items.rfk", "r");
153
154   if (!nki_file)
155     {
156       show_message ("Could not open list of non-kitten items!  Must quit.");
157       exit (EXIT_FAILURE);
158     }
159
160   while (!feof (nki_file))
161     {
162       char newline;
163       if (fscanf (nki_file, "%a[^\n]%c", &line, &newline) == EOF)
164         {
165           break;
166         }
167
168       if (strcmp(line, "")==0)
169         {
170           headers = FALSE;
171           fscanf (nki_file, "%c", &newline); 
172           free (line);
173         }
174       else if (headers)
175         {
176           /* we ignore all the headers for now */
177           free (line);
178         }
179       else
180         {
181           nki = g_slist_prepend (nki, line);
182           nki_count++;
183         }
184     }
185
186   fclose (nki_file);
187
188   used = g_malloc0 (nki_count);
189 }
190
191 void
192 load_images (void)
193 {
194   robot_pic = gdk_pixbuf_new_from_file ("/usr/share/rfk/rfk-robot.png", NULL);
195   love_pic = gdk_pixbuf_new_from_file ("/usr/share/rfk/rfk-love.png", NULL);
196   kitten_pic = gdk_pixbuf_new_from_file ("/usr/share/rfk/rfk-kitten.png", NULL);
197 }
198
199 /****************************************************************/
200 /* Stop doing that, and do something else.                      */
201 /****************************************************************/
202 static void
203 switch_state (StateOfPlay new_state)
204 {
205   if (current_state != STATE_LAST)
206     {
207       gtk_container_remove (GTK_CONTAINER (window), state_widget[current_state]);
208     }
209   gtk_container_add (GTK_CONTAINER (window), state_widget[new_state]);
210
211   gtk_widget_show_all (window);
212   gdk_window_set_events (GTK_WIDGET (window)->window,
213                          gdk_window_get_events(GTK_WIDGET (window)->window) | GDK_BUTTON_PRESS_MASK);
214
215   current_state = new_state;
216 }
217
218 /****************************************************************/
219 /* The ending animation.                                        */
220 /****************************************************************/
221
222 gboolean animation_running = FALSE;
223
224 /*
225 static gboolean
226 love_animation_draw
227 */
228 static gboolean
229 ending_animation_quit (gpointer data)
230 {
231   switch_state (STATE_PROLOGUE);
232   return FALSE;
233 }
234
235 static gboolean
236 ending_animation_draw (GtkWidget *widget, GdkEventExpose *event, gpointer data)
237 {
238   static int cycle_count = 0;
239
240   static int robot_x = 0;
241   static int robot_stop = 0;
242   static int kitten_x = 0;
243   static int all_y = 0;
244   static GdkGC *gc = NULL;
245
246   const int stepsize = 3;
247   static int love_size = 40;
248
249   if (!kitten_x)
250     {
251       gc = gdk_gc_new (GDK_DRAWABLE (widget->window));
252
253       all_y = (event->area.height - gdk_pixbuf_get_height (love_pic)) / 2;
254
255       robot_stop = gdk_pixbuf_get_width (robot_pic) + gdk_pixbuf_get_width (love_pic);
256       kitten_x = event->area.width - (cycle_count*stepsize + gdk_pixbuf_get_width (kitten_pic));
257     }
258
259   gdk_gc_set_foreground (gc, &black);
260
261   gdk_draw_rectangle (GDK_DRAWABLE (widget->window),
262                       gc,
263                       TRUE,
264                       0, 0, event->area.width, event->area.height);
265
266   gdk_draw_pixbuf (GDK_DRAWABLE (widget->window),
267                    gc,
268                    robot_pic, 0, 0,
269                    robot_x, all_y,
270                    -1, -1,
271                    GDK_RGB_DITHER_NONE, 0, 0);
272
273   gdk_draw_pixbuf (GDK_DRAWABLE (widget->window),
274                    gc,
275                    kitten_pic, 0, 0,
276                    kitten_x, all_y,
277                    -1, -1,
278                    GDK_RGB_DITHER_NONE, 0, 0);
279
280   if (robot_x+robot_stop < kitten_x)
281     {
282       cycle_count++;
283       robot_x += stepsize;
284       kitten_x -= stepsize;
285     }
286   else
287     {
288       GdkPixbuf *scaled_love_pic =
289         gdk_pixbuf_scale_simple (love_pic,
290                                  love_size,
291                                  love_size,
292                                  GDK_INTERP_BILINEAR);
293
294       gdk_draw_pixbuf (GDK_DRAWABLE(widget->window),
295                        gc,
296                        scaled_love_pic, 0, 0,
297                        robot_x + gdk_pixbuf_get_width (robot_pic), all_y,
298                        -1, -1,
299                        GDK_RGB_DITHER_NONE, 0, 0);
300
301       love_size ++;
302
303       if (love_size >= gdk_pixbuf_get_width (love_pic))
304         {
305           animation_running = FALSE;
306
307           g_timeout_add (2000, ending_animation_quit, NULL);
308
309           gdk_gc_unref (gc);
310           love_size = 40;
311           cycle_count = 0;
312           robot_x = 0;
313           robot_stop = 0;
314           kitten_x = 0;
315           all_y = 0;
316           gc = NULL;
317         }
318     }
319
320   return TRUE;
321 }
322
323 static gboolean
324 ending_animation_step (gpointer data)
325 {
326   if (animation_running)
327     {
328       gdk_window_invalidate_rect (state_widget[STATE_EPILOGUE]->window,
329                                   NULL, TRUE);
330
331       return TRUE;
332     }
333   else
334     return FALSE;
335 }
336
337 static void
338 ending_animation ()
339 {
340   if (current_state!=STATE_EPILOGUE)
341     {
342       animation_running = TRUE;
343       g_timeout_add (10, ending_animation_step, NULL);
344     }
345 }
346
347 /****************************************************************/
348 /* Moving the robot.  Way to go, robot!                         */
349 /****************************************************************/
350
351 typedef struct {
352   guint gdk_key;
353   gchar vi_key; /* or nethack equivalent */
354   guint8 move_x;
355   guint8 move_y;
356 } direction;
357
358 direction directions[] = {
359   { GDK_Home,      'y', -1, -1 },
360   { GDK_Left,      'h', -1,  0 },
361   { GDK_End,       'b', -1,  1 },
362   { GDK_Down,      'j',  0,  1 },
363   { GDK_Page_Down, 'n',  1,  1 },
364   { GDK_Right,     'l',  1,  0 },
365   { GDK_Page_Up,   'u',  1, -1 },
366   { GDK_Up,        'k',  0, -1 }
367 };
368
369 gboolean
370 move_robot (guint8 whichway)
371 {
372   GtkWidget *new_space;
373   gint8 dx = directions[whichway].move_x;
374   gint8 dy = directions[whichway].move_y;
375
376   const char *found;
377
378   if (robot_x+dx<0 ||
379       robot_y+dy<0 ||
380       robot_x+dx>=ARENA_WIDTH ||
381       robot_y+dy>=ARENA_HEIGHT)
382     return TRUE;
383
384   new_space = arena[robot_x+dx][robot_y+dy];
385   found = g_object_get_data (G_OBJECT (new_space), "examine");
386
387   if (found && *found)
388     {
389       show_message (found);
390
391       if (new_space == kitten)
392         {
393           switch_state (STATE_EPILOGUE);
394         }
395
396       return TRUE;
397     }
398   else
399     {
400       /* just an ordinary move into an empty space */
401
402       g_object_ref (new_space);
403
404       gtk_container_remove (GTK_CONTAINER (state_widget[STATE_PLAYING]), robot);
405       gtk_container_remove (GTK_CONTAINER (state_widget[STATE_PLAYING]), new_space);
406
407       place_in_arena_at_xy (new_space, robot_x, robot_y);
408       place_in_arena_at_xy (robot, robot_x+dx, robot_y+dy);
409
410       g_object_unref (new_space);
411
412       return FALSE;
413     }
414 }
415
416 /****************************************************************/
417 /* Event handlers.                                              */
418 /****************************************************************/
419
420 gboolean
421 on_window_clicked (GtkWidget      *widget,
422                    GdkEventButton *event,
423                    gpointer        user_data)
424 {
425   /** Centre point of robot's representation on screen */
426   int rx, ry;
427   double angle;
428
429   if (current_state!=STATE_PLAYING)
430     {
431       return TRUE;
432     }
433
434   rx = (robot->allocation.x+robot->allocation.width/2);
435   ry = (robot->allocation.y+robot->allocation.height/2);
436
437   angle = atan2(event->x - rx,
438                 event->y - ry) +
439     M_PI * (9/8);
440
441   move_robot (((int) (angle / (M_PI/4))) % 8);
442
443   return TRUE;
444 }
445
446 gboolean
447 on_key_pressed (GtkWidget      *widget,
448                 GdkEventKey    *event,
449                 gpointer        user_data)
450 {
451   gint i;
452   guint keyval = event->keyval;
453
454   if (current_state!=STATE_PLAYING)
455     {
456       return FALSE;
457     }
458
459   if (keyval>='A' && keyval<='Z')
460     {
461       keyval += ('a'-'A');
462     }
463
464   for (i=0; i<G_N_ELEMENTS(directions); i++)
465     {
466       if (keyval==directions[i].gdk_key ||
467           keyval==directions[i].vi_key)
468         {
469           if (event->state & GDK_SHIFT_MASK)
470             {
471               while (!move_robot (i))
472                 {
473                   /* keep going, robot! */
474                 }
475             }
476           else
477             {
478               move_robot (i);
479             }
480           return FALSE;
481         }
482     }
483
484   return FALSE;
485 }
486
487 /****************************************************************/
488 /* Online help.                                                 */
489 /****************************************************************/
490 gboolean
491 get_help (gpointer button, gpointer data)
492 {
493   DBusGConnection *connection;
494   GError *error = NULL;
495
496   DBusGProxy *proxy;
497
498   connection = dbus_g_bus_get (DBUS_BUS_SESSION,
499                                &error);
500   if (connection == NULL)
501     {
502       show_message (error->message);
503       g_error_free (error);
504       return FALSE;
505     }
506
507   proxy = dbus_g_proxy_new_for_name (connection,
508                                      "com.nokia.osso_browser",
509                                      "/com/nokia/osso_browser/request",
510                                      "com.nokia.osso_browser");
511
512   error = NULL;
513   if (!dbus_g_proxy_call (proxy, "load_url", &error,
514                           G_TYPE_STRING, "/usr/share/rfk/help.html",
515                           G_TYPE_INVALID,
516                           G_TYPE_INVALID))
517     {
518       show_message (error->message);
519       g_error_free (error);
520       return FALSE;
521     }
522   return FALSE;
523 }
524
525 void
526 play_game (gpointer button, gpointer data)
527 {
528   switch_state (STATE_PLAYING);
529 }
530
531 static void
532 set_up_board (void)
533 {
534   guint x, y;
535
536   if (current_state==STATE_PLAYING)
537     {
538       /* end of the game; clean up */
539
540       for (x=0; x < ARENA_WIDTH; x++)
541         for (y=0; y < ARENA_HEIGHT; y++)
542           if (arena[x][y])
543             {
544               gtk_container_remove (GTK_CONTAINER (state_widget[STATE_PLAYING]),
545                                     arena[x][y]);
546               arena[x][y] = NULL;
547             }
548
549       g_object_unref (robot);
550       g_object_unref (kitten);
551     }
552   else
553     {
554       /* make everything new */
555   
556       robot = gtk_label_new ("#");
557       g_object_ref (robot);
558       kitten = random_character ("You found kitten!  Way to go, robot!");
559       g_object_ref (kitten);
560
561       place_in_arena_randomly (robot);
562       place_in_arena_randomly (kitten);
563
564       if (nki_count < amount_of_random_stuff)
565         {
566           /* sanity check failed */
567           show_message ("There are too few non-kitten items to play a meaningful game.");
568           exit (EXIT_FAILURE);
569         }
570
571       for (x=0; x < amount_of_random_stuff; x++)
572         place_in_arena_randomly (random_character (description ()));
573
574       for (x=0; x < ARENA_WIDTH; x++)
575         for (y=0; y < ARENA_HEIGHT; y++)
576           if (!arena[x][y])
577             place_in_arena_at_xy (gtk_label_new (NULL), x, y);
578     }
579 }
580
581 static void
582 set_up_widgets (void)
583 {
584   GtkWidget *middle = gtk_hbox_new (FALSE, 0);
585   GtkWidget *buttons = gtk_hbox_new (TRUE, 0);
586   GtkWidget *explain = NULL, *help_button, *play_button, *intro;
587   const char *explanation =
588     "In this game, you are robot (#). "
589     "Your job is to find kitten. This task is complicated "
590     "by the existence of various things which are not kitten. "
591     "Robot must touch items to determine if they are kitten or "
592     "not. The game ends when robotfindskitten. You may move "
593     "robot about by tapping on any side of robot, or with the "
594     "arrow keys.";
595   GKeyFile *desktop = g_key_file_new ();
596   gchar *version;
597   guint x, y;
598   
599   /* The window */
600
601   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
602   gtk_window_set_title (GTK_WINDOW (window), "robotfindskitten");
603   gtk_widget_modify_bg (window, GTK_STATE_NORMAL, &black);
604   g_signal_connect (G_OBJECT (window), "button-press-event", G_CALLBACK (on_window_clicked), NULL);
605   g_signal_connect (G_OBJECT (window), "key-press-event", G_CALLBACK (on_key_pressed), NULL);
606   g_signal_connect (G_OBJECT (window), "delete_event", G_CALLBACK (gtk_main_quit), NULL);
607
608   /* The prologue */
609
610   if (g_key_file_load_from_file (desktop,
611                                  "/usr/share/applications/hildon/rfk.desktop",
612                                  G_KEY_FILE_NONE,
613                                  NULL))
614     {
615       version = g_strdup_printf("v%s.%d",
616                                 g_key_file_get_value (desktop, "Desktop Entry", "Version", NULL),
617                                 nki_count);
618       g_key_file_free (desktop);
619     }
620   else
621     {
622       version = g_strdup("");
623     }
624
625   help_button = hildon_button_new_with_text (HILDON_SIZE_AUTO_WIDTH | HILDON_SIZE_THUMB_HEIGHT,
626                                              HILDON_BUTTON_ARRANGEMENT_HORIZONTAL,
627                                              "Help", NULL);
628   g_signal_connect (help_button, "clicked", G_CALLBACK (get_help), NULL);
629
630   play_button = hildon_button_new_with_text (HILDON_SIZE_AUTO_WIDTH | HILDON_SIZE_THUMB_HEIGHT,
631                                              HILDON_BUTTON_ARRANGEMENT_HORIZONTAL,
632                                              "Play", NULL);
633   g_signal_connect (play_button, "clicked", G_CALLBACK (play_game), NULL);
634
635   gtk_box_pack_end (GTK_BOX (buttons), play_button, TRUE, TRUE, 0);
636   gtk_box_pack_end (GTK_BOX (buttons), help_button, TRUE, TRUE, 0);
637
638   explain = gtk_label_new (explanation);
639   gtk_label_set_line_wrap (GTK_LABEL (explain), TRUE);
640
641   gtk_box_pack_end (GTK_BOX (middle), explain, TRUE, TRUE, 0);
642   gtk_box_pack_end (GTK_BOX (middle), gtk_image_new_from_pixbuf (robot_pic), FALSE, FALSE, 0);
643
644   intro = gtk_vbox_new (FALSE, 0);
645   gtk_box_pack_end (GTK_BOX (intro), buttons, FALSE, FALSE, 0);
646   gtk_box_pack_end (GTK_BOX (intro), middle, TRUE, TRUE, 0);
647   gtk_box_pack_end (GTK_BOX (intro), gtk_label_new (version), FALSE, FALSE, 0);
648   g_free (version);
649
650   state_widget[STATE_PROLOGUE] = intro;
651
652   /* The game itself */
653
654   state_widget[STATE_PLAYING] = gtk_table_new (ARENA_HEIGHT, ARENA_WIDTH, TRUE);
655   g_signal_connect (state_widget[STATE_PLAYING], "parent-set", G_CALLBACK (set_up_board), NULL);
656
657   for (x=0; x < ARENA_WIDTH; x++)
658     for (y=0; y < ARENA_HEIGHT; y++)
659       arena[x][y] = NULL;
660
661   /* The epilogue */
662   state_widget[STATE_EPILOGUE] =  gtk_drawing_area_new ();
663   g_signal_connect (state_widget[STATE_EPILOGUE], "parent-set", G_CALLBACK (ending_animation), NULL);
664   g_signal_connect (G_OBJECT (state_widget[STATE_EPILOGUE]),
665                     "expose_event", G_CALLBACK (ending_animation_draw), NULL);
666
667   for (x=0; x<STATE_LAST; x++)
668     {
669       /* so we don't lose them when we take them offscreen */
670       g_object_ref (state_widget[x]);
671     }
672 }
673
674 /****************************************************************/
675 /* Let's kick the whole thing off...                            */
676 /****************************************************************/
677
678 int
679 main (gint argc,
680       gchar **argv)
681 {
682   gtk_init (&argc, &argv);
683   g_set_application_name ("robotfindskitten");
684   srandom (time(0));
685
686   ensure_messages_loaded ();
687   load_images ();
688
689   set_up_widgets ();
690   switch_state (STATE_PROLOGUE);
691   
692   gtk_main ();
693
694   return EXIT_SUCCESS;
695 }