Exemple #1
0
int moveSnake() {
	
	if(headPositionX==foodPositionX && headPositionY==foodPositionY)
	{
		bodyLength++;
		foodEaten = 0;
	}
	else {
		/*Removing the tail ie. the last block*/
		gotoxy(bodyPositionX[bodyLength], bodyPositionY[bodyLength]); 
		putchar(' ');
	}	
	
	/*Moving the head forward and then other blocks follow*/	
	int i;
	for(i=bodyLength;i>0;i--) {
		if(i == 1) {
			bodyPositionX[i] = headPositionX;
			bodyPositionY[i] = headPositionY;
			gotoxy(bodyPositionX[i], bodyPositionY[i]);
			putchar(snakeBody);					
		}
		else {
			bodyPositionX[i] = bodyPositionX[i-1];
			bodyPositionY[i] = bodyPositionY[i-1];
			gotoxy(bodyPositionX[i], bodyPositionY[i]);
			putchar(snakeBody);
		}
	}
	
	
	if(direction == 'd' || direction == 'D') 
		moveSnakeRight();
	else if(direction == 'a' || direction == 'A') 
		moveSnakeLeft();
	else if(direction == 's' || direction == 'S') 
		moveSnakeDown();
	else if(direction == 'w' || direction == 'W') 
		moveSnakeUp();
		
	
	/*Suicide case*/
	for(i=0; i<=bodyLength; i++) {
			if(headPositionX==bodyPositionX[i] && headPositionY==bodyPositionY[i]) {
				/*code to end the game*/
				printf("\t\t\tGame Over\n\n\n\n\n\n");
				getch();
				exit(1);
			}
		}

		
	/*Speed of snake ie. sleepe time in ms time unit.*/
	usleep(SLEEP_TIME);
	fflush(stdout);	
	return 0;
}
Exemple #2
0
void Game()
{
	while (true)
	{
		drawBoard();
		removeSnake();
		if (GetAsyncKeyState(VK_LEFT) && !moveSnakeRight_b)
		{
			if (!moveSnakeLeft_b)
			{	
				moveSnakeLeft();
				drawSnake();
				checkSnakeCollision();
			}
		}
		else if (GetAsyncKeyState(VK_RIGHT) && !moveSnakeLeft_b)
		{
			if (!moveSnakeRight_b)
			{
				moveSnakeRight();
				checkSnakeCollision();
			}
		}
		else if (GetAsyncKeyState(VK_UP) && !moveSnakeDown_b)
		{
			if (!moveSnakeUp_b)
			{
				moveSnakeUp();
				checkSnakeCollision();
			}
		}
		else if (GetAsyncKeyState(VK_DOWN) && !moveSnakeUp_b)
		{
			if (!moveSnakeDown_b)
			{
				moveSnakeDown();
				checkSnakeCollision();
			}
		} // Automatic moves
	    else if (moveSnakeDown_b)
		{
			moveSnakeDown();
			checkSnakeCollision();
		}
		else if (moveSnakeUp_b)
		{
			moveSnakeUp();
			checkSnakeCollision();
		}
		else if (moveSnakeRight_b)
		{
			moveSnakeRight();
			checkSnakeCollision();
		}
		else if (moveSnakeLeft_b)
		{
			moveSnakeLeft();
			checkSnakeCollision();
		}

		drawSnake();

		Sleep(100);
	}
}