Aug 20, 2015 at 12:56pm UTC
Hi, I started to learn C++ a few days ago and I'm stuck on an assignment.
It's a console program that is supposed to work like a reaction game. It says something like "Get ready!" and somewhere between 3-10 seconds it will say "Now!" and you press enter, after that it should show you how many milliseconds it took you to react.
The tips I got was to look up "C++ sleep" and "C++ tickcount". Would appreciate any help I can get, thanks!
Aug 20, 2015 at 2:38pm UTC
Something like this (tested in Borland C++ Builder 5.0):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
DWORD qmscdelay,qmscb,qmsce;
int nchr;
printf("Get ready!\n" );
qmscdelay=3000+random(7001);
Sleep(qmscdelay);
printf("Now!\n" );
qmscb=GetTickCount();
for (;;)
{
if (kbhit())
{
nchr=getch();
if (!nchr)
getch();
else
{
if (nchr==13)
break ;
}
}
}
qmsce=GetTickCount();
printf("%i milliseconds\n" ,qmsce-qmscb);
Last edited on Aug 20, 2015 at 2:39pm UTC
Aug 20, 2015 at 4:08pm UTC
Portable standard C++11 implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#include <chrono>
#include <iostream>
#include <random>
#include <thread>
int main()
{
namespace aion = std::chrono;
using clock_type = std::conditional<aion::high_resolution_clock::is_steady,
aion::high_resolution_clock,
aion::steady_clock>::type;
using frac_second = aion::duration<double >;
std::random_device rd;
std::mt19937_64 gen(rd());
std::uniform_int_distribution<> random_time(3000, 10000);
auto wait_time = aion::milliseconds(random_time(gen));
std::cout << "Wait...\n" ;
std::this_thread::sleep_for(wait_time);
std::cout << "Now!\n" ;
auto start = clock_type::now();
std::cin.get();
auto end = clock_type::now();
std::cout << "It took you " << aion::duration_cast<frac_second>(end-start).count() <<
" seconds to react." ;
}
Last edited on Aug 20, 2015 at 4:13pm UTC