Back to Top

Home/Tutorials

Reaction Time Tester


Howdy, folks! In this tutorial we will create a small application that will test your reaction time. We will learn quite a few new things, but don't worry, the code isn't complicated at all.


reaction time

Take a good look at the code below; it is all that's required to make it run. We'd need to include in a standard C program, for a C++ application, or for lite-C.

var random_number;

PANEL* number =

{

digits (260, 200, 1, "Arial#150b", 1, random_number);

flags = OUTLINE;

}


TEXT* info =

{

font = "Arial#30b";

string("Reaction Time Test\nPress the 1...5 keys as soon as the corresponding number shows up\nHit any key to start the test");

pos_x = 10;

pos_x = 10;

}

The code begins with a variable definition, which will store a random number from 1 to 5. Then, we define a panel that will display our random number, and a text that will show the test rules. You should note the \n sequence, which is similar with carriage return, placing bits of text on a new line.

function main()

{

screen_size.x = 900;

   screen_size.y = 600;

screen_color.blue = 150;

video_window(NULL, NULL, 0, "Reaction Time Test");

   random_seed(0);

The first lines of code inside function main() set the screen resolution to 900x600 pixels and a blue background color. Then, we set the title of the window and we initialize the random number generator.

while(1)

{

  set(info, SHOW);

  while (!key_any) wait(1);

  reset(info, SHOW);

  double average_time = 0;

  var counter;

The while loop displays the information, and then waits until a key is pressed. When this happens, the info text is hidden, and two variables are defined.

  for (counter = 0; counter < 5; counter++)

  {

   reset(number, SHOW);

   wait(-2 - random(2));    

   random_number = 1 + integer(random(5));

   set(number, SHOW);

   dtimer();

The random number will be displayed five times, with a pause of 2...4 seconds between two consecutive numbers. The code generates an integer that ranges from 1 to 5, displays it, and then starts a timer that counts the reaction time.

   while (!key_any) wait(1);

   if (random_number != str_to_num(str_for_key(NULL, key_lastpressed)))

   {

      var i;

      for (i=0; i<3; i++)

      {

     vec_set(number.blue,COLOR_RED);

     wait(-0.1);

     vec_set(number.blue,COLOR_WHITE);

     wait(-0.1);

    }

    counter--;

    continue;

   }

If the wrong key has been hit, the displayed number flashes using a red color, and a new one will be generated.

   average_time += dtimer() / 5.;

  }

  reset(number, SHOW);

  str_printf((info.pstring)[0], "Average reaction time: %.3f seconds\nEsc to quit, other key to restart", average_time / 1000000.);

  while (key_any) wait(1);

}

}

The average time is computed, and then the result is displayed. The application will then allow its user to restart the test by pressing any key, or to quit by pressing Esc.