Quote:
Originally Posted by KliPPy
You initialize it in main() and pass it to both Setup() and DrawMap(). You pass it to any function that needs to access it.
|
Thanks, now I get it. What's the difference between int &Score and int *Score?
PHP Code:
#include <iostream>
#include <stdlib.h>
#include <conio.h>
#include <ctime>
#include <Windows.h>
using namespace std;
const int MapX = 50;
const int MapY = 20;
int SnakeX;
int SnakeY;
int FruitX;
int FruitY;
bool gameOver;
// Map Over-view
/*
012345678911234567892
0: ########################### --> X
1: # #
2: # #
3: # #
4: # #
5: # #
6: # #
7: # # Y
8: ###########################*/
enum eDirections
{
UP,
DOWN,
LEFT,
RIGHT
};
eDirections dir;
void RandomizeFruit( )
{
FruitX = rand( ) % ( MapX - 1 ) + 1;
FruitY = rand( ) % ( MapY - 1 ) + 1;
}
void Setup( int &Score )
{
srand( time ( 0 ) );
SnakeX = MapX / 2;
SnakeY = MapY / 2;
RandomizeFruit( );
Score = 0;
}
void DrawMap( int &Score )
{
system( "cls" );
int x, y, spaces;
for( y = 0; y < MapY; y++ )
{
if( ( y == 0 || y == MapY - 1 ) ) // first or last row
{
for( x = 0; x <= MapX; x++ ) // print X 10 times
{
cout << "#";
}
}
else // 1-9 row
{
cout << "#"; // # which goes to the first space of the line
spaces = 0;
while( spaces != MapX - 1 ) // keep putting spaces till we reach the end of the line - 1
{
if( spaces == SnakeX && y == SnakeY )
{
cout << "O";
}
else if( spaces == FruitX && y == FruitY )
{
cout << "F";
}
else
{
cout << " ";
}
spaces++;
}
cout << "#"; // finally print # at the end of the line
}
cout << endl;
}
cout << "Score: " << Score;
}
void Logic( int &Score )
{
switch( dir )
{
case LEFT:
{
SnakeX--;
break;
}
case RIGHT:
{
SnakeX++;
break;
}
case UP:
{
SnakeY--;
break;
}
case DOWN:
{
SnakeY++;
break;
}
}
if( SnakeX == FruitX && SnakeY == FruitY )
{
Score++;
RandomizeFruit( );
}
if( SnakeX > MapX - 2 )
SnakeX = 0;
else if( SnakeY > MapY - 2 )
SnakeY = 1;
else if( SnakeX < 0 )
SnakeX = MapX - 2;
else if( SnakeY < 1 )
SnakeY = MapY - 2;
}
int Input()
{
switch (_getch())
{
case 'a':
{
dir = LEFT;
return 1;
}
case 'd':
{
dir = RIGHT;
return 1;
}
case 'w':
{
dir = UP;
return 1;
}
case 's':
{
dir = DOWN;
return 1;
}
case 'x':
{
gameOver = true;
return 1;
}
}
return 0;
}
void ShowConsoleCursor(bool showFlag)
{
HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cursorInfo;
GetConsoleCursorInfo(out, &cursorInfo);
cursorInfo.bVisible = showFlag; // set the cursor visibility
SetConsoleCursorInfo(out, &cursorInfo);
}
int main()
{
ShowConsoleCursor(false);
int Score;
Score = 0;
Setup(Score);
DrawMap(Score);
while (!gameOver)
{
if (Input() == 1)
{
Logic(Score);
DrawMap(Score);
Sleep(100);
}
}
return 0;
}
__________________