robot vibrates when robotfindskitten
[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   used[r] = TRUE;
60
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
189 void
190 load_images (void)
191 {
192   robot_pic = gdk_pixbuf_new_from_file ("/usr/share/rfk/rfk-robot.png", NULL);
193   love_pic = gdk_pixbuf_new_from_file ("/usr/share/rfk/rfk-love.png", NULL);
194   kitten_pic = gdk_pixbuf_new_from_file ("/usr/share/rfk/rfk-kitten.png", NULL);
195 }
196
197 /****************************************************************/
198 /* Stop doing that, and do something else.                      */
199 /****************************************************************/
200 static void
201 switch_state (StateOfPlay new_state)
202 {
203   if (current_state != STATE_LAST)
204     {
205       gtk_container_remove (GTK_CONTAINER (window), state_widget[current_state]);
206     }
207   gtk_container_add (GTK_CONTAINER (window), state_widget[new_state]);
208
209   gtk_widget_show_all (window);
210   gdk_window_set_events (GTK_WIDGET (window)->window,
211                          gdk_window_get_events(GTK_WIDGET (window)->window) | GDK_BUTTON_PRESS_MASK);
212
213   current_state = new_state;
214 }
215
216 /****************************************************************/
217 /* Things we need DBus for: online help, and vibration.         */
218 /****************************************************************/
219 static void
220 call_dbus (DBusBusType type,
221            char *name,
222            char *path,
223            char *interface,
224            char *method,
225            char *parameter)
226 {
227   DBusGConnection *connection;
228   GError *error = NULL;
229
230   DBusGProxy *proxy;
231
232   connection = dbus_g_bus_get (type,
233                                &error);
234   if (connection == NULL)
235     {
236       show_message (error->message);
237       g_error_free (error);
238       return;
239     }
240
241   proxy = dbus_g_proxy_new_for_name (connection, name, path, interface);
242
243   error = NULL;
244   if (!dbus_g_proxy_call (proxy, method, &error,
245                           G_TYPE_STRING, parameter,
246                           G_TYPE_INVALID,
247                           G_TYPE_INVALID))
248     {
249       show_message (error->message);
250       g_error_free (error);
251     }
252 }
253
254 static gboolean
255 get_help (gpointer button, gpointer data)
256 {
257   call_dbus (DBUS_BUS_SESSION,
258              "com.nokia.osso_browser",
259              "/com/nokia/osso_browser/request",
260              "com.nokia.osso_browser",
261              "load_url",
262              "/usr/share/rfk/help.html");
263   return FALSE;
264 }
265
266 static void
267 vibrate (void)
268 {
269   call_dbus (DBUS_BUS_SYSTEM,
270              "com.nokia.mce",
271              "/com/nokia/mce/request",
272              "com.nokia.mce.request",
273              "req_vibrator_pattern_activate",
274              "PatternIncomingMessage");
275 }
276
277 /****************************************************************/
278 /* The ending animation.                                        */
279 /****************************************************************/
280
281 gboolean animation_running = FALSE;
282
283 /*
284 static gboolean
285 love_animation_draw
286 */
287 static gboolean
288 ending_animation_quit (gpointer data)
289 {
290   switch_state (STATE_PROLOGUE);
291   return FALSE;
292 }
293
294 static gboolean
295 ending_animation_draw (GtkWidget *widget, GdkEventExpose *event, gpointer data)
296 {
297   static int cycle_count = 0;
298
299   static int robot_x = 0;
300   static int robot_stop = 0;
301   static int kitten_x = 0;
302   static int all_y = 0;
303   static GdkGC *gc = NULL;
304
305   const int stepsize = 3;
306   static int love_size = 40;
307
308   if (!kitten_x)
309     {
310       gc = gdk_gc_new (GDK_DRAWABLE (widget->window));
311
312       all_y = (event->area.height - gdk_pixbuf_get_height (love_pic)) / 2;
313
314       robot_stop = gdk_pixbuf_get_width (robot_pic) + gdk_pixbuf_get_width (love_pic);
315       kitten_x = event->area.width - (cycle_count*stepsize + gdk_pixbuf_get_width (kitten_pic));
316     }
317
318   gdk_gc_set_foreground (gc, &black);
319
320   gdk_draw_rectangle (GDK_DRAWABLE (widget->window),
321                       gc,
322                       TRUE,
323                       0, 0, event->area.width, event->area.height);
324
325   gdk_draw_pixbuf (GDK_DRAWABLE (widget->window),
326                    gc,
327                    robot_pic, 0, 0,
328                    robot_x, all_y,
329                    -1, -1,
330                    GDK_RGB_DITHER_NONE, 0, 0);
331
332   gdk_draw_pixbuf (GDK_DRAWABLE (widget->window),
333                    gc,
334                    kitten_pic, 0, 0,
335                    kitten_x, all_y,
336                    -1, -1,
337                    GDK_RGB_DITHER_NONE, 0, 0);
338
339   if (robot_x+robot_stop < kitten_x)
340     {
341       cycle_count++;
342       robot_x += stepsize;
343       kitten_x -= stepsize;
344     }
345   else
346     {
347       GdkPixbuf *scaled_love_pic =
348         gdk_pixbuf_scale_simple (love_pic,
349                                  love_size,
350                                  love_size,
351                                  GDK_INTERP_BILINEAR);
352
353       gdk_draw_pixbuf (GDK_DRAWABLE(widget->window),
354                        gc,
355                        scaled_love_pic, 0, 0,
356                        robot_x + gdk_pixbuf_get_width (robot_pic), all_y,
357                        -1, -1,
358                        GDK_RGB_DITHER_NONE, 0, 0);
359
360       love_size ++;
361
362       if (love_size >= gdk_pixbuf_get_width (love_pic))
363         {
364           /* all done! */
365           
366           vibrate ();
367           
368           animation_running = FALSE;
369
370           g_timeout_add (2000, ending_animation_quit, NULL);
371
372           gdk_gc_unref (gc);
373           love_size = 40;
374           cycle_count = 0;
375           robot_x = 0;
376           robot_stop = 0;
377           kitten_x = 0;
378           all_y = 0;
379           gc = NULL;
380         }
381     }
382
383   return TRUE;
384 }
385
386 static gboolean
387 ending_animation_step (gpointer data)
388 {
389   if (animation_running)
390     {
391       gdk_window_invalidate_rect (state_widget[STATE_EPILOGUE]->window,
392                                   NULL, TRUE);
393
394       return TRUE;
395     }
396   else
397     return FALSE;
398 }
399
400 static void
401 ending_animation ()
402 {
403   if (current_state!=STATE_EPILOGUE)
404     {
405       animation_running = TRUE;
406       g_timeout_add (10, ending_animation_step, NULL);
407     }
408 }
409
410 /****************************************************************/
411 /* Moving the robot.  Way to go, robot!                         */
412 /****************************************************************/
413
414 typedef struct {
415   guint gdk_key;
416   gchar vi_key; /* or nethack equivalent */
417   guint8 move_x;
418   guint8 move_y;
419 } direction;
420
421 direction directions[] = {
422   { GDK_Home,      'y', -1, -1 },
423   { GDK_Left,      'h', -1,  0 },
424   { GDK_End,       'b', -1,  1 },
425   { GDK_Down,      'j',  0,  1 },
426   { GDK_Page_Down, 'n',  1,  1 },
427   { GDK_Right,     'l',  1,  0 },
428   { GDK_Page_Up,   'u',  1, -1 },
429   { GDK_Up,        'k',  0, -1 }
430 };
431
432 gboolean
433 move_robot (guint8 whichway)
434 {
435   GtkWidget *new_space;
436   gint8 dx = directions[whichway].move_x;
437   gint8 dy = directions[whichway].move_y;
438
439   const char *found;
440
441   if (robot_x+dx<0 ||
442       robot_y+dy<0 ||
443       robot_x+dx>=ARENA_WIDTH ||
444       robot_y+dy>=ARENA_HEIGHT)
445     return TRUE;
446
447   new_space = arena[robot_x+dx][robot_y+dy];
448   found = g_object_get_data (G_OBJECT (new_space), "examine");
449
450   if (found && *found)
451     {
452       show_message (found);
453
454       if (new_space == kitten)
455         {
456           switch_state (STATE_EPILOGUE);
457         }
458
459       return TRUE;
460     }
461   else
462     {
463       /* just an ordinary move into an empty space */
464
465       g_object_ref (new_space);
466
467       gtk_container_remove (GTK_CONTAINER (state_widget[STATE_PLAYING]), robot);
468       gtk_container_remove (GTK_CONTAINER (state_widget[STATE_PLAYING]), new_space);
469
470       place_in_arena_at_xy (new_space, robot_x, robot_y);
471       place_in_arena_at_xy (robot, robot_x+dx, robot_y+dy);
472
473       g_object_unref (new_space);
474
475       return FALSE;
476     }
477 }
478
479 /****************************************************************/
480 /* Event handlers.                                              */
481 /****************************************************************/
482
483 gboolean
484 on_window_clicked (GtkWidget      *widget,
485                    GdkEventButton *event,
486                    gpointer        user_data)
487 {
488   /** Centre point of robot's representation on screen */
489   int rx, ry;
490   double angle;
491
492   if (current_state!=STATE_PLAYING)
493     {
494       return TRUE;
495     }
496
497   rx = (robot->allocation.x+robot->allocation.width/2);
498   ry = (robot->allocation.y+robot->allocation.height/2);
499
500   angle = atan2(event->x - rx,
501                 event->y - ry) +
502     M_PI * (9/8);
503
504   move_robot (((int) (angle / (M_PI/4))) % 8);
505
506   return TRUE;
507 }
508
509 gboolean
510 on_key_pressed (GtkWidget      *widget,
511                 GdkEventKey    *event,
512                 gpointer        user_data)
513 {
514   gint i;
515   guint keyval = event->keyval;
516
517   if (current_state!=STATE_PLAYING)
518     {
519       return FALSE;
520     }
521
522   if (keyval>='A' && keyval<='Z')
523     {
524       keyval += ('a'-'A');
525     }
526
527   for (i=0; i<G_N_ELEMENTS(directions); i++)
528     {
529       if (keyval==directions[i].gdk_key ||
530           keyval==directions[i].vi_key)
531         {
532           if (event->state & GDK_SHIFT_MASK)
533             {
534               while (!move_robot (i))
535                 {
536                   /* keep going, robot! */
537                 }
538             }
539           else
540             {
541               move_robot (i);
542             }
543           return FALSE;
544         }
545     }
546
547   if (keyval=='d' && event->state & GDK_CONTROL_MASK)
548     {
549       /* secret debugging key */
550       show_message (gtk_label_get_text (GTK_LABEL (kitten)));
551     }
552
553   return FALSE;
554 }
555
556 void
557 play_game (gpointer button, gpointer data)
558 {
559   switch_state (STATE_PLAYING);
560 }
561
562 static void
563 set_up_board (void)
564 {
565   guint x, y;
566
567   if (current_state==STATE_PLAYING)
568     {
569       /* end of the game; clean up */
570
571       for (x=0; x < ARENA_WIDTH; x++)
572         for (y=0; y < ARENA_HEIGHT; y++)
573           if (arena[x][y])
574             {
575               gtk_container_remove (GTK_CONTAINER (state_widget[STATE_PLAYING]),
576                                     arena[x][y]);
577               arena[x][y] = NULL;
578             }
579
580       g_object_unref (robot);
581       g_object_unref (kitten);
582     }
583   else
584     {
585       /* make everything new */
586   
587       g_free (used);
588       used = g_malloc0 (nki_count * sizeof(gboolean));
589
590       robot = gtk_label_new ("#");
591       g_object_ref (robot);
592       kitten = random_character ("You found kitten!  Way to go, robot!");
593       g_object_ref (kitten);
594
595       place_in_arena_randomly (robot);
596       place_in_arena_randomly (kitten);
597
598       if (nki_count < amount_of_random_stuff)
599         {
600           /* sanity check failed */
601           show_message ("There are too few non-kitten items to play a meaningful game.");
602           exit (EXIT_FAILURE);
603         }
604
605       for (x=0; x < amount_of_random_stuff; x++)
606         place_in_arena_randomly (random_character (description ()));
607
608       for (x=0; x < ARENA_WIDTH; x++)
609         for (y=0; y < ARENA_HEIGHT; y++)
610           if (!arena[x][y])
611             place_in_arena_at_xy (gtk_label_new (NULL), x, y);
612     }
613 }
614
615 static void
616 set_up_widgets (void)
617 {
618   GtkWidget *middle = gtk_hbox_new (FALSE, 0);
619   GtkWidget *buttons = gtk_hbox_new (TRUE, 0);
620   GtkWidget *explain = NULL, *help_button, *play_button, *intro;
621   const char *explanation =
622     "In this game, you are robot (#). "
623     "Your job is to find kitten. This task is complicated "
624     "by the existence of various things which are not kitten. "
625     "Robot must touch items to determine if they are kitten or "
626     "not. The game ends when robotfindskitten. You may move "
627     "robot about by tapping on any side of robot, or with the "
628     "arrow keys.";
629   GKeyFile *desktop = g_key_file_new ();
630   gchar *version;
631   guint x, y;
632   
633   /* The window */
634
635   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
636   gtk_window_set_title (GTK_WINDOW (window), "robotfindskitten");
637   gtk_widget_modify_bg (window, GTK_STATE_NORMAL, &black);
638   g_signal_connect (G_OBJECT (window), "button-press-event", G_CALLBACK (on_window_clicked), NULL);
639   g_signal_connect (G_OBJECT (window), "key-press-event", G_CALLBACK (on_key_pressed), NULL);
640   g_signal_connect (G_OBJECT (window), "delete_event", G_CALLBACK (gtk_main_quit), NULL);
641
642   /* The prologue */
643
644   if (g_key_file_load_from_file (desktop,
645                                  "/usr/share/applications/hildon/rfk.desktop",
646                                  G_KEY_FILE_NONE,
647                                  NULL))
648     {
649       version = g_strdup_printf("v%s.%d",
650                                 g_key_file_get_value (desktop, "Desktop Entry", "Version", NULL),
651                                 nki_count);
652       g_key_file_free (desktop);
653     }
654   else
655     {
656       version = g_strdup("");
657     }
658
659   help_button = hildon_button_new_with_text (HILDON_SIZE_AUTO_WIDTH | HILDON_SIZE_THUMB_HEIGHT,
660                                              HILDON_BUTTON_ARRANGEMENT_HORIZONTAL,
661                                              "Help", NULL);
662   g_signal_connect (help_button, "clicked", G_CALLBACK (get_help), NULL);
663
664   play_button = hildon_button_new_with_text (HILDON_SIZE_AUTO_WIDTH | HILDON_SIZE_THUMB_HEIGHT,
665                                              HILDON_BUTTON_ARRANGEMENT_HORIZONTAL,
666                                              "Play", NULL);
667   g_signal_connect (play_button, "clicked", G_CALLBACK (play_game), NULL);
668
669   gtk_box_pack_end (GTK_BOX (buttons), play_button, TRUE, TRUE, 0);
670   gtk_box_pack_end (GTK_BOX (buttons), help_button, TRUE, TRUE, 0);
671
672   explain = gtk_label_new (explanation);
673   gtk_label_set_line_wrap (GTK_LABEL (explain), TRUE);
674
675   gtk_box_pack_end (GTK_BOX (middle), explain, TRUE, TRUE, 0);
676   gtk_box_pack_end (GTK_BOX (middle), gtk_image_new_from_pixbuf (robot_pic), FALSE, FALSE, 0);
677
678   intro = gtk_vbox_new (FALSE, 0);
679   gtk_box_pack_end (GTK_BOX (intro), buttons, FALSE, FALSE, 0);
680   gtk_box_pack_end (GTK_BOX (intro), middle, TRUE, TRUE, 0);
681   gtk_box_pack_end (GTK_BOX (intro), gtk_label_new (version), FALSE, FALSE, 0);
682   g_free (version);
683
684   state_widget[STATE_PROLOGUE] = intro;
685
686   /* The game itself */
687
688   state_widget[STATE_PLAYING] = gtk_table_new (ARENA_HEIGHT, ARENA_WIDTH, TRUE);
689   g_signal_connect (state_widget[STATE_PLAYING], "parent-set", G_CALLBACK (set_up_board), NULL);
690
691   for (x=0; x < ARENA_WIDTH; x++)
692     for (y=0; y < ARENA_HEIGHT; y++)
693       arena[x][y] = NULL;
694
695   /* The epilogue */
696   state_widget[STATE_EPILOGUE] =  gtk_drawing_area_new ();
697   g_signal_connect (state_widget[STATE_EPILOGUE], "parent-set", G_CALLBACK (ending_animation), NULL);
698   g_signal_connect (G_OBJECT (state_widget[STATE_EPILOGUE]),
699                     "expose_event", G_CALLBACK (ending_animation_draw), NULL);
700
701   for (x=0; x<STATE_LAST; x++)
702     {
703       /* so we don't lose them when we take them offscreen */
704       g_object_ref (state_widget[x]);
705     }
706 }
707
708 /****************************************************************/
709 /* Let's kick the whole thing off...                            */
710 /****************************************************************/
711
712 int
713 main (gint argc,
714       gchar **argv)
715 {
716   gtk_init (&argc, &argv);
717   g_set_application_name ("robotfindskitten");
718   srandom (time(0));
719
720   ensure_messages_loaded ();
721   load_images ();
722
723   set_up_widgets ();
724   switch_state (STATE_PROLOGUE);
725   
726   gtk_main ();
727
728   return EXIT_SUCCESS;
729 }