alternative to recursion

Started by
12 comments, last by spock 21 years ago
Calling main recursively is not just a bad idea - it''s illegal to do so. The C++ standard forbids you from using main (ie calling it or taking it''s address) in a program.
Advertisement
You can use functions?
Just call the function in main.

.lick
Your playAgain() method should just reset the board to its original setup (and return).
I just realized this is "For Beginners". I suppose I could have been a little more helpful. :-)

Try to make your functions return values and leave further decisions (such as whether to exit the program) up to the caller; that will make changes to the program structure much easier. A couple of suggestions:


int main() {
int menu;
srand(time(NULL)); // you only need to do this once
do {
/* show menu */
cin >> menu;
switch(menu) {
case 1: GameMain();
break;
case 2: /* show about screen, wait for keypress */
break;
}
} while(menu != 3);
return 0;
}


main must return an int (your compiler may not complain about void main but others will). Avoid error messages when the user selects invalid menu choices, simply show the menu again.


void GameMain() {
int player = rand() % 2;

/* restore Grid array to numbers 1-9 */

if(player == 0) {
cout << "Player 1 (X) goes first.";
} else {
cout << "Player 2 (O) goes first.";
}

do {
if(++player > 2)
player = 1;
ShowGrid();
Write2Grid(GetInput(player),player);
} while(CheckWin() == false);
/* congratulate winning player */
}

int GetInput(int player) {
int choice;
do {
/* show prompt */
cin >> choice;
} while(ValidChoice(choice) == false);
return choice;
}

bool ValidChoice(choice) {
if(choice < 1 || choice > 9) {
return false;
int c = 2 - (choice-1)/3;
int d = (choice-1)%3;
if(Grid[c][d] == ''X'' || Grid[c][d] == ''O'')
return false;
return true;
}

void Write2Grid(int choice,int player) {
int c = 2 - (choice-1)/3;
int d = (choice-1)%3;
if(player == 1) {
Grid[c][d] = ''X'';
} else {
Grid[c][d] = ''O'';
}
}


I hope you get the idea.

This topic is closed to new replies.

Advertisement