23ae03dff9f6b52ff9031c77bdf292ed16dbbf8c
[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 = 1;
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 static gboolean
223 ending_animation_quit (gpointer data)
224 {
225   gtk_main_quit ();
226   return FALSE;
227 }
228
229 static gboolean
230 ending_animation_draw (GtkWidget *widget, GdkEventExpose *event, gpointer data)
231 {
232   /* We only run through once, so just make it static. */
233   static int cycle_count = 0;
234
235   static int robot_x = 0;
236   static int robot_stop = 0;
237   static int kitten_x = 0;
238   static int all_y = 0;
239
240   const int stepsize = 3;
241
242   if (!kitten_x)
243     {
244       all_y = (event->area.height - gdk_pixbuf_get_height (love_pic)) / 2;
245
246       robot_stop = gdk_pixbuf_get_width (robot_pic) + gdk_pixbuf_get_width (love_pic);
247       kitten_x = event->area.width - (cycle_count*stepsize + gdk_pixbuf_get_width (kitten_pic));
248     }
249
250   gdk_gc_set_foreground (widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
251                          &black);
252
253   gdk_draw_rectangle (GDK_DRAWABLE(widget->window),
254                       widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
255                       TRUE,
256                       0, 0, event->area.width, event->area.height);
257
258   gdk_draw_pixbuf (GDK_DRAWABLE(widget->window),
259                    widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
260                    robot_pic, 0, 0,
261                    robot_x, all_y,
262                    -1, -1,
263                    GDK_RGB_DITHER_NONE, 0, 0);
264
265   gdk_draw_pixbuf (GDK_DRAWABLE(widget->window),
266                    widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
267                    kitten_pic, 0, 0,
268                    kitten_x, all_y,
269                    -1, -1,
270                    GDK_RGB_DITHER_NONE, 0, 0);
271
272   cycle_count++;
273   robot_x += stepsize;
274   kitten_x -= stepsize;
275
276   if (robot_x+robot_stop >= kitten_x)
277     {
278       gdk_draw_pixbuf (GDK_DRAWABLE(widget->window),
279                        widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
280                        love_pic, 0, 0,
281                        robot_x + gdk_pixbuf_get_width (robot_pic), all_y,
282                        -1, -1,
283                        GDK_RGB_DITHER_NONE, 0, 0);
284
285       g_object_unref (love_pic);
286       love_pic = NULL;
287
288       g_timeout_add (2000, ending_animation_quit, NULL);
289     }
290
291   return TRUE;
292 }
293
294 static gboolean
295 ending_animation_step (gpointer data)
296 {
297   if (love_pic)
298     {
299       gdk_window_invalidate_rect (state_widget[STATE_EPILOGUE]->window,
300                                   NULL, TRUE);
301
302       return TRUE;
303     }
304   else
305     return FALSE;
306 }
307
308 static void
309 ending_animation ()
310 {
311   switch_state (STATE_EPILOGUE);
312   g_timeout_add (10, ending_animation_step, NULL);
313 }
314
315 /****************************************************************/
316 /* Moving the robot.  Way to go, robot!                         */
317 /****************************************************************/
318
319 typedef struct {
320   guint gdk_key;
321   gchar vi_key; /* or nethack equivalent */
322   guint8 move_x;
323   guint8 move_y;
324 } direction;
325
326 direction directions[] = {
327   { GDK_Home,      'y', -1, -1 },
328   { GDK_Left,      'h', -1,  0 },
329   { GDK_End,       'b', -1,  1 },
330   { GDK_Down,      'j',  0,  1 },
331   { GDK_Page_Down, 'n',  1,  1 },
332   { GDK_Right,     'l',  1,  0 },
333   { GDK_Page_Up,   'u',  1, -1 },
334   { GDK_Up,        'k',  0, -1 }
335 };
336
337 gboolean
338 move_robot (guint8 whichway)
339 {
340   GtkWidget *new_space;
341   gint8 dx = directions[whichway].move_x;
342   gint8 dy = directions[whichway].move_y;
343
344   const char *found;
345
346   if (robot_x+dx<0 ||
347       robot_y+dy<0 ||
348       robot_x+dx>=ARENA_WIDTH ||
349       robot_y+dy>=ARENA_HEIGHT)
350     return TRUE;
351
352   new_space = arena[robot_x+dx][robot_y+dy];
353   found = g_object_get_data (G_OBJECT (new_space), "examine");
354
355   if (found && *found)
356     {
357       show_message (found);
358
359       if (new_space == kitten)
360         {
361           ending_animation ();
362         }
363
364       return TRUE;
365     }
366   else
367     {
368       /* just an ordinary move into an empty space */
369
370       g_object_ref (new_space);
371
372       gtk_container_remove (GTK_CONTAINER (state_widget[STATE_PLAYING]), robot);
373       gtk_container_remove (GTK_CONTAINER (state_widget[STATE_PLAYING]), new_space);
374
375       place_in_arena_at_xy (new_space, robot_x, robot_y);
376       place_in_arena_at_xy (robot, robot_x+dx, robot_y+dy);
377
378       g_object_unref (new_space);
379
380       return FALSE;
381     }
382 }
383
384 /****************************************************************/
385 /* Event handlers.                                              */
386 /****************************************************************/
387
388 gboolean
389 on_window_clicked (GtkWidget      *widget,
390                    GdkEventButton *event,
391                    gpointer        user_data)
392 {
393   /** Centre point of robot's representation on screen */
394   int rx, ry;
395   double angle;
396
397   if (current_state!=STATE_PLAYING)
398     {
399       return TRUE;
400     }
401
402   rx = (robot->allocation.x+robot->allocation.width/2);
403   ry = (robot->allocation.y+robot->allocation.height/2);
404
405   angle = atan2(event->x - rx,
406                 event->y - ry) +
407     M_PI * (9/8);
408
409   move_robot (((int) (angle / (M_PI/4))) % 8);
410
411   return TRUE;
412 }
413
414 gboolean
415 on_key_pressed (GtkWidget      *widget,
416                 GdkEventKey    *event,
417                 gpointer        user_data)
418 {
419   gint i;
420   guint keyval = event->keyval;
421
422   if (current_state!=STATE_PLAYING)
423     {
424       return FALSE;
425     }
426
427   if (keyval>='A' && keyval<='Z')
428     {
429       keyval += ('a'-'A');
430     }
431
432   for (i=0; i<G_N_ELEMENTS(directions); i++)
433     {
434       if (keyval==directions[i].gdk_key ||
435           keyval==directions[i].vi_key)
436         {
437           if (event->state & GDK_SHIFT_MASK)
438             {
439               while (!move_robot (i))
440                 {
441                   /* keep going, robot! */
442                 }
443             }
444           else
445             {
446               move_robot (i);
447             }
448           return FALSE;
449         }
450     }
451
452   return FALSE;
453 }
454
455 /****************************************************************/
456 /* Online help.                                                 */
457 /****************************************************************/
458 gboolean
459 get_help (gpointer button, gpointer data)
460 {
461   DBusGConnection *connection;
462   GError *error = NULL;
463
464   DBusGProxy *proxy;
465
466   connection = dbus_g_bus_get (DBUS_BUS_SESSION,
467                                &error);
468   if (connection == NULL)
469     {
470       show_message (error->message);
471       g_error_free (error);
472       return FALSE;
473     }
474
475   proxy = dbus_g_proxy_new_for_name (connection,
476                                      "com.nokia.osso_browser",
477                                      "/com/nokia/osso_browser/request",
478                                      "com.nokia.osso_browser");
479
480   error = NULL;
481   if (!dbus_g_proxy_call (proxy, "load_url", &error,
482                           G_TYPE_STRING, "/usr/share/rfk/help.html",
483                           G_TYPE_INVALID,
484                           G_TYPE_INVALID))
485     {
486       show_message (error->message);
487       g_error_free (error);
488       return FALSE;
489     }
490   return FALSE;
491 }
492
493 void
494 play_game (gpointer button, gpointer data)
495 {
496   switch_state (STATE_PLAYING);
497 }
498
499 static void
500 set_up_widgets (void)
501 {
502   GtkWidget *middle = gtk_hbox_new (FALSE, 0);
503   GtkWidget *buttons = gtk_hbox_new (TRUE, 0);
504   GtkWidget *explain = NULL, *help_button, *play_button, *intro;
505   const char *explanation =
506     "In this game, you are robot (#). "
507     "Your job is to find kitten. This task is complicated "
508     "by the existence of various things which are not kitten. "
509     "Robot must touch items to determine if they are kitten or "
510     "not. The game ends when robotfindskitten. You may move "
511     "robot about by tapping on any side of robot, or with the "
512     "arrow keys.";
513   GKeyFile *desktop = g_key_file_new ();
514   gchar *version;
515   guint x, y;
516   
517   /* The window */
518
519   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
520   gtk_window_set_title (GTK_WINDOW (window), "robotfindskitten");
521   gtk_widget_modify_bg (window, GTK_STATE_NORMAL, &black);
522   g_signal_connect (G_OBJECT (window), "button-press-event", G_CALLBACK (on_window_clicked), NULL);
523   g_signal_connect (G_OBJECT (window), "key-press-event", G_CALLBACK (on_key_pressed), NULL);
524   g_signal_connect (G_OBJECT (window), "delete_event", G_CALLBACK (gtk_main_quit), NULL);
525
526   /* The prologue */
527
528   if (g_key_file_load_from_file (desktop,
529                                  "/usr/share/applications/hildon/rfk.desktop",
530                                  G_KEY_FILE_NONE,
531                                  NULL))
532     {
533       version = g_strdup_printf("v%s.%d",
534                                 g_key_file_get_value (desktop, "Desktop Entry", "Version", NULL),
535                                 nki_count);
536       g_key_file_free (desktop);
537     }
538   else
539     {
540       version = g_strdup("");
541     }
542
543   help_button = hildon_button_new_with_text (HILDON_SIZE_AUTO_WIDTH | HILDON_SIZE_THUMB_HEIGHT,
544                                              HILDON_BUTTON_ARRANGEMENT_HORIZONTAL,
545                                              "Help", NULL);
546   g_signal_connect (help_button, "clicked", G_CALLBACK (get_help), NULL);
547
548   play_button = hildon_button_new_with_text (HILDON_SIZE_AUTO_WIDTH | HILDON_SIZE_THUMB_HEIGHT,
549                                              HILDON_BUTTON_ARRANGEMENT_HORIZONTAL,
550                                              "Play", NULL);
551   g_signal_connect (play_button, "clicked", G_CALLBACK (play_game), NULL);
552
553   gtk_box_pack_end (GTK_BOX (buttons), play_button, TRUE, TRUE, 0);
554   gtk_box_pack_end (GTK_BOX (buttons), help_button, TRUE, TRUE, 0);
555
556   explain = gtk_label_new (explanation);
557   gtk_label_set_line_wrap (GTK_LABEL (explain), TRUE);
558
559   gtk_box_pack_end (GTK_BOX (middle), explain, TRUE, TRUE, 0);
560   gtk_box_pack_end (GTK_BOX (middle), gtk_image_new_from_pixbuf (robot_pic), FALSE, FALSE, 0);
561
562   intro = gtk_vbox_new (FALSE, 0);
563   gtk_box_pack_end (GTK_BOX (intro), buttons, FALSE, FALSE, 0);
564   gtk_box_pack_end (GTK_BOX (intro), middle, TRUE, TRUE, 0);
565   gtk_box_pack_end (GTK_BOX (intro), gtk_label_new (version), FALSE, FALSE, 0);
566   g_free (version);
567
568   state_widget[STATE_PROLOGUE] = intro;
569
570   /* The game itself */
571
572   state_widget[STATE_PLAYING] = gtk_table_new (ARENA_HEIGHT, ARENA_WIDTH, TRUE);
573
574   robot = gtk_label_new ("#");
575   g_object_ref (robot);
576   kitten = random_character ("You found kitten!  Way to go, robot!");
577
578   place_in_arena_randomly (robot);
579   place_in_arena_randomly (kitten);
580
581   if (nki_count < amount_of_random_stuff)
582     {
583       gtk_widget_show_all (window);
584       show_message ("There are too few non-kitten items to play a meaningful game.");
585       exit (EXIT_FAILURE);
586     }
587
588   for (x=0; x < amount_of_random_stuff; x++)
589     place_in_arena_randomly (random_character (description ()));
590
591   for (x=0; x < ARENA_WIDTH; x++)
592     for (y=0; y < ARENA_HEIGHT; y++)
593       if (!arena[x][y])
594         place_in_arena_at_xy (gtk_label_new (NULL), x, y);
595
596   /* The epilogue */
597   state_widget[STATE_EPILOGUE] =  gtk_drawing_area_new ();
598   g_signal_connect (G_OBJECT (state_widget[STATE_EPILOGUE]),
599                     "expose_event", G_CALLBACK (ending_animation_draw), NULL);
600
601   for (x=0; x<STATE_LAST; x++)
602     {
603       /* so we don't lose them when we take them offscreen */
604       g_object_ref (state_widget[x]);
605     }
606 }
607
608 /****************************************************************/
609 /* Let's kick the whole thing off...                            */
610 /****************************************************************/
611
612 int
613 main (gint argc,
614       gchar **argv)
615 {
616   gtk_init (&argc, &argv);
617   g_set_application_name ("robotfindskitten");
618   srandom (time(0));
619
620   ensure_messages_loaded ();
621   load_images ();
622
623   set_up_widgets ();
624   switch_state (STATE_PROLOGUE);
625   
626   gtk_main ();
627
628   return EXIT_SUCCESS;
629 }