Click here to Skip to main content
15,888,136 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
#include "stdafx.h"                           // Used for Visual Studio
#include <iostream>                           // Used for cout/cin 
#include <conio.h>                            // Used for getch()
#include <windows.h>                          // Used for clearing screen
#include <ctime>                              // Used for managing time (speeding/slowing gmae)
#include <vector>                             // Used for items
#include <fstream>                            // USed for high score


using namespace std;
#define WIDTH 20
#define HEIGHT 20
char Level[HEIGHT][WIDTH];

// FUNCTION DECLARATIONS
void Initialize(int size, int snakeX[], int snakeY[]);                                                      // Initialise snake
void ClearScreen();                                                                                         // Clear screen
void BuildLevel();                                                                                          // Build level
void ReDraw();                                                                                              // Redraw level
void Update(int &size, int snakeX[], int snakeY[], int tempX[], int tempY[], int &item_count, int &points); // Update game loop
void SpeedUpdate();                                                                                         // Update snakes speed
void Items(vector<int> &itemX, vector<int> &itemY, int &item_count, int snakeX[], int snakeY[], int &size, int tailX, int tailY, int &points);  // Show and eat items
bool IsGameOver(int snakeX[], int snakeY[], int size);                                                      // Check if game is over
void HighScore(int points);                                                                                 // Read and saves high scores

// MAIN
int main()
{
	int size = 3;                  // Set snakes initial size to 3
	int item_count = 0;
	int points = 0;
	int snakeX[100], snakeY[100], tempX[100], tempY[100];

	Initialize(size, snakeX, snakeY);
	BuildLevel();
	Update(size, snakeX, snakeY, tempX, tempY, item_count, points);
	HighScore(points);

	_getch();
	return 0;
}

// INITIALIZE SNAKE
void Initialize(int size, int snakeX[], int snakeY[])
{
	snakeX[0] = WIDTH / 2;     snakeY[0] = 3;  // Initialize snakes initial position
	snakeX[1] = WIDTH / 2;     snakeY[1] = 2;
	snakeX[2] = WIDTH / 2;     snakeY[2] = 1;
	for (int i = 3; i < 100; i++)
	{
		snakeX[i] = NULL;
		snakeY[i] = NULL;
	}

	// Set snakes initial position in level
	for (int i = 0; i < size; i++)
		Level[snakeY[i]][snakeX[i]] = 'o';
}

// BUILD LEVEL
void BuildLevel()
{
	for (int i = 0; i<height;>	{
		for (int j = 0; j<width;>		{
			Level[0][j] = '*';
			Level[i][0] = '*';
			Level[i][WIDTH - 1] = '*';
			Level[HEIGHT - 1][j] = '*';
		}
	}
}

// DISPLAY LEVEL
void ReDraw()
{
	for (int i = 0; i < HEIGHT; i++)
	{
		cout << endl;
		for (int j = 0; j < WIDTH; j++)
			 cout << " " << Level[i][j];
	}
}

// CLEAR SCREEN
void ClearScreen()
{
	HANDLE hOut;
	COORD Position;
	hOut = GetStdHandle(STD_OUTPUT_HANDLE);
	Position.X = 0;
	Position.Y = 0;
	SetConsoleCursorPosition(hOut, Position);
}

// UPDATE
void Update(int &size, int snakeX[], int snakeY[], int tempX[], int tempY[], int &item_count, int &points)
{
	int count = 0;
	char input = ' ';
	char previnput = 's';
	int tailX, tailY;
	bool gameOver = false;
	vector<int> itemX, itemY;

	while (!gameOver)                           // Loops until game is over
	{
		SpeedUpdate();                          // Speed

		// Save tail to delete trace as it moves
		tailY = snakeY[size - 1];
		tailX = snakeX[size - 1];

		// Delete previous tail trace
		Level[tailY][tailX] = ' ';
		Items(itemX, itemY, item_count, snakeX, snakeY, size, tailX, tailY, points);

		// Copy snake (except tail) into temp array, and displace 1 element to the right
		// Leave the first element empty for head
		for (int i = 0; i < size - 1; i++)
		{
			tempX[i + 1] = snakeX[i];            // copy y values
			tempY[i + 1] = snakeY[i];          // copy x values
		}

		// Copy a duplicate of the head into first element so it can be moved by user
		tempX[0] = snakeX[0];
		tempY[0] = snakeY[0];

		// Copy temp array back into snake array, including previous head position
		// First 2 elements will be a duplicate of the head with same x and y position
		for (int i = 0; i < size; i++)
		{
			snakeX[i] = tempX[i];              // Copy y values
			snakeY[i] = tempY[i];              // Copy x values
		}

		// Stores keystroke
		if (_kbhit())
			input = _getch();

		// WHILE MOVING DOWN
		if (previnput == 's')
		{
			snakeY[0] += 1;                           // Set heads new position
			if (input == 'a'  || input == 'A')        // Go left
				previnput = 'a';
			else if (input == 'd'  || input == 'D')   // Go right
				previnput = 'd';
		}
		// WHILE MOVING UP
		else if (previnput == 'w')
		{
			snakeY[0] -= 1;                            // Set heads new position
			if (input == 'a'  || input == 'A')         // Go left
				previnput = 'a';
			else if (input == 'd'  || input == 'D')    // Go right
				previnput = 'd';
		}
		// WHILE MOVING RIGHT
		else if (previnput == 'd')
		{
			snakeX[0] += 1;                         // Set heads new position
			if (input == 'w' || input == 'W')       // Go up
				previnput = 'w';
			else if (input == 's' || input == 'S')  // Go down
				previnput = 's';
		}
		// WHILE MOVING LEFT
		else if (previnput == 'a')
		{
			snakeX[0] -= 1;                         // Set heads new position
			if (input == 'w' || input == 'N')       // Go up
				previnput = 'w';
			else if (input == 's' || input == 'S')  // Go down
				previnput = 's';
		}

		// Set snakes new position
		for (int i = 0; i < size; i++)
			Level[snakeY[i]][snakeX[i]] = 'o';

		// Check if game is over 
		gameOver = IsGameOver(tempX, tempY, size);
		if (gameOver == true)
		{
			cout << "\a\a";
			break;
		}

		// Redraw
		ClearScreen();
		ReDraw();
	}
}

// ITEMS
void Items(vector<int> &itemX, vector<int> &itemY, int &item_count, int snakeX[], int snakeY[], int &size, int tailX, int tailY, int &points)
{
	clock_t interval = clock() % 3000;
	cout << "\t\t    Points: " << points << endl;

	// Show items at certain intervals
	if (interval > 2800)
	{
		item_count++;
		srand((unsigned)time(NULL));
		// Item is placed at random locations
		itemX.push_back( rand() % (WIDTH - 2) + 1);
		itemY.push_back( rand() % (HEIGHT - 2) + 1);

		Level[itemY.back()][itemX.back()] = '@';
	}

	// Check collision with item
	for (int i = 0; i < item_count; i++)
	{
		if ( (snakeX[0] == itemX.at(i)) && (snakeY[0] == itemY.at(i)) )
		{
			points += 100;
			// Deletes item
			item_count--;
			itemY.erase(itemY.begin() + i);
			itemX.erase(itemX.begin() + i);
			// Snake grows
			size++;
			snakeX[size - 1] = tailX;
			snakeY[size - 1] = tailY;
			cout << "\a";
		}
	}
}

// SPEED
void SpeedUpdate()
{
	if (clock() <= 9000)                                 // Level 1
	{
		Sleep(100);
		cout << endl << " Level 1";
	}
	else if ((clock() > 9000) && (clock() < 18000))      // Level 2
	{
		Sleep(50);
		cout << endl << " Level 2";
	}
	else if ((clock() > 18000) && (clock() < 36000))      // Level 3
	{
		Sleep(25);
		cout << endl << " Level 3";
	}
	else
		cout << endl << " Level 4";                       // Level 4

}

// IS GAME OVER
bool IsGameOver(int snakeX[], int snakeY[], int size)
{
	// If snake collides with tail
	for (int i = 2; i << size; i++)
	{
		if ( (snakeX[0] == snakeX[i]) && (snakeY[0] == snakeY[i]) )
		{
			cout << endl << "\t\t  YOU LOSE!";
			_getch();
			return true;
		}
	}
	if ((snakeX[0] == WIDTH - 1) || (snakeY[0] == HEIGHT - 1) || (snakeX[0] == 0) || (snakeY[0] == 0))
	{
		cout << endl << "\t\t  YOU LOSE!";
		_getch();
		return true;
	}
	else
		return false;
}
// HIGH SCORES
void HighScore(int points)
{
	char fileName[] = "HighScore.txt";
	int score[5];
	int temp[5];
	int count = 0;
	int position = 5;
	bool save = false;

	system("cls");                                        // Clear Screen
	ifstream inputFile;
	inputFile.open(fileName);                             // Read from file

	while (inputFile.eof())                              // Read until end of file
	{
		inputFile >> score[count];                        // Extracts current points from file and store array
		count++;
	}
	inputFile.close();                                    // Close file

	for (int i = 4; i > 0; i--)                           // Check if score is to be save in board
	{
		if (points > score[i])                            // If score is higher than scores in board
		{
			if (position > 0)
				position--;                               // Increase position
			save = true;                                  // Set save to true
		}
	}

	if (save == true)                                     // Save score in sorted array
	{
		if (position == 0)
			cout << "CONGRATULATIONS, YOU HAVE ACHIEVED THE HIGHEST SCORE!" << endl;
		else
			cout << "Well done, you are now raked #" << position + 1 << "!" << endl;

		for (int i = 4; i >= position; i--)
			temp[i + 1] = score[i];                       // Copies scores to be rearranged into temp array

		for (int i = 4; i >= position + 1; i--)
			score[i] = temp[i];                           // Rearranges ranking

		cout << endl << "Score: " << points << endl << endl;
		score[position] = points;                         // Saves user score in the correct position

		ofstream outputFile;
		outputFile.open(fileName);                        // Write to file

		cout << "HIGH SCORES" << endl;
		cout << "-----------" << endl;
		for (int i = 0; i < 5; i++)
		{
			cout << i + 1 << ". " << score[i] << endl;
			outputFile << score[i] << endl;               // Overwrite file with new scoreboard
		}

		outputFile.close();                               // Close file 
	}
	else
	{
		cout << "You did't make it to the hall of fame..." << endl << "Make sure you do better next time!" << endl;
		cout << endl << "Score: " << points << endl << endl;

		inputFile.open(fileName);                         // Read from file
		while (!inputFile.eof())                          // Read until end of file
			inputFile >> score[count];                    // Extracts current points from file and store into array

		cout << "HIGH SCORES" << endl;
		cout << "-----------" << endl;
		for (int i = 0; i < 5; i++)
			cout << i + 1 << ". " << score[i] << endl;
		inputFile.close();                                // Close file
	}
}
Posted
Updated 10-Nov-14 2:30am
v2
Comments
Richard MacCutchan 10-Nov-14 8:32am    
Why have you dumped all this code for such a simple question? Where is the stdafx.h file in relation to your project?

You also need to understand that this file is nothing to do with Visual Studio, it is used by the preprocessor to create a precompiled header file to speed up compilation.

1 solution

As already mentioned by Richard, the stdafx.h file is a Microsoft specific file used when enabling precompiled headers. If you don't use Visual Studio or VS without precompiled headers it must not be included.

You should use a debugger to set breakpoints to find out why your program stops playing.

However, this line in IsGameOver looks suspicious:
for (int i = 2; i << size; i++)
 
Share this answer
 
v2
Comments
Aescleal 10-Nov-14 11:39am    
One of the many reasons why using things like std::copy and std::for_each can be so much better than fiddling about with manual loops...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900