Example #1
0
int main(int argc, char **argv)
{
	time_t t1, t2;
	double dur;
	dir_t dir, tempDir;
	bool receivedDir = false;

	int speed = 100; //default speed

	if (argc >= 2) //if user gives a more preferred speed (as command-libne arg), we use that.
	{
		if (isdigit(argv[1][0])) //but only if it is a digit
			speed = atoi(argv[1]);
	}
	
	Snake* pSnake = new Snake(speed);
	
	time(&t1); //get current time

	while (true) //show welcome message for 5 seconds
	{
	    time(&t2);
		dur = difftime(t2, t1); //calculate difference

		if (dur >= 5) // <-- that is the magic 5 :D
			break;
		
		pSnake->displWelcome((int)5-dur); //display welcome message with remaining time
	}

	pSnake->displ(); //display the (inital)snake

	time(&t1);
	
	while (true) //the main game loop
	{
		receivedDir = false;

		// we get <pSnake->speed> milliseconds of frametime (ncurses timeout is set to 1ms)
		for (int i = 0; i < pSnake->speed; i++) // this might seem weird ("Why not just a simple time delay? wtf..")
		{                                       // but I had problems with <sys/time>::gettimeofday()
			                                    // so its curses' delay doing the job..
			tempDir = pSnake->getdir(); //get input
			
			if (tempDir != DIR_VOID) //if no input was received, we keep the previous direction.
			{
				receivedDir = true; //we have received input, so DIR_VOID has no power anymore
				dir = tempDir;  //
			}
		}

		if (receivedDir) //if we received input..
			pSnake->curDir = dir; //..we set the new direction as the current one
		
	    //time to move the snake and do other thingys!
			
		if (pSnake->move(dir) == INTERSECT) //interscetion -> game over
		{
			pSnake->gameOver();			
			delete pSnake;
			return 0;
		}
			
		pSnake->displ(); //re-render the snake
	}

	return 0;
}