Howdy, y'all!
I'm trying to make a simple little game, but redrawing the game board is a lot stower than I'd like. Any suggestions to optimize my code?
I'm using a Console program because I'm still a novice and am not ready to tackle a real GUI yet.
Here is my source code:
#include <iostream>
#include <Windows.h>
#include <conio.h>
#include <sstream>
#include "Game.h"
using namespace std;
void startGame()
{
while(1)
{
int ch = ' ';
Gameboard GB;
vector pos(1, 1);
GB.setPos(pos, '*');
GB.printGameboard();
while(ch != 27)
{
while(!_kbhit());
ch = _getch();
if(ch == 0)
_getch();
else if(ch == 224)
{
ch = _getch();
vector newPos = pos;
if(ch == 72)
{
newPos.y--;
if(GB.BoardChar(newPos) == ' ')
{
GB.setPos(pos, ' ');
pos = newPos;
GB.setPos(pos, '*');
GB.printGameboard();
}
}
if(ch == 75)
{
newPos.x--;
if(GB.BoardChar(newPos) == ' ')
{
GB.setPos(pos, ' ');
pos = newPos;
GB.setPos(pos, '*');
GB.printGameboard();
}
}
if(ch == 77)
{
newPos.x++;
if(GB.BoardChar(newPos) == ' ')
{
GB.setPos(pos, ' ');
pos = newPos;
GB.setPos(pos, '*');
GB.printGameboard();
}
}
if(ch == 80)
{
newPos.y++;
if(GB.BoardChar(newPos) == ' ')
{
GB.setPos(pos, ' ');
pos = newPos;
GB.setPos(pos, '*');
GB.printGameboard();
}
}
}
}
if(ch == 27)
exit(0);
}
}
void vector::operator=(vector& prevVector)
{
x = prevVector.x;
y = prevVector.y;
}
vector::vector(int newX, int newY)
{
x = newX;
y = newY;
}
void Gameboard::printGameboard()
{
stringstream sout;
system("clear");
for(int ROW = 0; ROW < 61; ROW++)
{
for(int COLUMN = 0; COLUMN < 124; COLUMN++)
sout << Board[ROW][COLUMN];
}
string board = sout.str();
cout << board;
}
void Gameboard::setBoard()
{
//First Row
Board[0][0] = ' ';
for(int COLUMN = 1; COLUMN < 123; COLUMN++)
Board[0][COLUMN] = '-';
Board[0][123] = ' ';
//Middle Rows
for(int ROW = 1; ROW < 60; ROW++)
{
Board[ROW][0] = '|';
for(int COLUMN = 1; COLUMN < 123; COLUMN++)
{
Board[ROW][COLUMN] = ' ';
}
Board[ROW][123] = '|';
}
//Last Row
Board[60][0] = ' ';
for(int COLUMN = 1; COLUMN < 123; COLUMN++)
Board[60][COLUMN] = '-';
Board[60][123] = ' ';
}
void Gameboard::setPos(vector& V, char C)
{
Board[V.y][V.x] = C;
}
char Gameboard::BoardChar(vector& V)
{
return Board[V.y][V.x];
}
Gameboard::Gameboard()
{
setBoard();
}
printGameboarh() is the function I'm most concerned with.
I used sout.str() to pass a single string to cout rather than make repetitive calls to cout. This didn't appear to change the speed at all.
I've been told <conio> is deprecated. Is their a better replacement?