Gå til innhold

Anbefalte innlegg

Lager et tic tac toe program i c++.

Programmet er 1 player. Dvs at computeren tar et random move ved sin tur, gitt ved:

 

srand(1);

position = rand() % 8; // tilfeldig nummer mellom 0 og 8

 

Jeg har 9 arrays som representerer de 9 felt i tic-tac-toe. Nummer 0-8.

 

Hvis jeg tester programmet, og hvis jeg f.eks taster inn 0 og deretter 2. Da vil programmet ende opp i en uendelig loop. Hva er grunnen til det? Her er programmet mitt.

 

 

 

#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
string displayBoard(string board[9]);   // displays tic tac toe board
bool isGameOver(string board[9]);	   // checks if game is over
void displayGameWelcome();			  // displays welcome message
// Credits
// http://www.codingmix.com/2010/07/simples-cplusplus-tic-tac-toe-game-ever_24.html
int main()
{
  string board[9];		  // tic tac toe, top row 0 thru 2, middle row 3 thru 5, bottom row 6 thru 8
  int position = 0;		 // player's position
  bool gameOver = false;	// flag variable to mark end of the game
  bool validMove = false;   // determines if move is valid or not
  displayGameWelcome();
  // initializing board with blank spaces
  for (int i = 0; i < 9; i++)
  {
  board[i] = " ";		
  }

  while (!gameOver)
  {
  // player #1's turn **************************
  validMove = false;

  while (!validMove)
  {
	 cout << "Enter your position: ";
	 cin >> position;
	 if (position >= 0 && position <= 8 && board[position] == " ")
	 {
		validMove = true;
		board[position] = "x";  // placing x in desired board location
	 }
	 else if (position >= 0 && position <= 8 && board[position] != " ")
	 {
		cout << "That position is already occupied." << endl;
		cout << displayBoard(board) << endl;
	 }
  else
  {
cout << "Invalid number" << endl;
  }

  }
  cout << displayBoard(board) << endl;
  if (isGameOver(board))
  {
	 gameOver = true;
  continue;
  }
  // player #2's turn **********************************
  validMove = false;

  while (!validMove)
  {
	 srand(1);
  position = rand() % 8;

  {
  if (board[0] == "x" && board[1] == "x")
  {
position = 2;
  }
  else if (board[3] == "x" && board[4] == "x")
  {
position = 5;
  }
  else if (board[6] == "x" && board[7] == "x")
  {
position = 8;
  }
  else if (board[0] == "x" && board[4] == "x" )
  {
position = 8;
  }
  else if (board[2] == "x" && board[4] == "x")
  {
position = 6;
  }
  else if (board[0] == "x" && board[3] == "x")
  {
position = 6;
  }
  else if (board[1] == "x" && board[4] == "x")
  {
position = 7;
  }
  else if (board[2] == "x" && board[5] == "x")
  {
position = 8;
  }
  }
	 if (position >= 0 && position <= 8 && board[position] == " ")
	 {
		validMove = true;
		board[position] = "o";  // placing o in desired board position
	 }
	 else if (position >= 0 && position <= 8 && board[position] != " ")
	 {
		cout << "That position is already occupied." << endl;
		cout << displayBoard(board) << endl;
	 }
  else
  {
cout << "Invalid number" << endl;
  }

  }
  cout << displayBoard(board) << endl;
  if (isGameOver(board))
  {
	 gameOver = true;
  }
  }// end of validMove while loop

  system("pause");
  return 0;
}// end of main
// ************************** functions *************************
void displayGameWelcome()
{
cout << "WELCOME TO TIC TAC TOE" << endl;\
cout << "This game is developed by Mats Gausdal" << endl;
cout << "****************************\n\n\n";
}// end of displayGameWelcome
// checks if game is over
bool isGameOver(string board[9])
{
if (board[0] == "x" && board[1] == "x" && board[2] == "x")
{
 cout << endl << "The game is over - x wins" << endl;
 return true;
}
else if (board[3] == "x" && board[4] == "x" && board[5] == "x")
{
 cout << endl << "The game is over - x wins" << endl;
 return true;
}
else if (board[6] == "x" && board[7] == "x" && board[8] == "x")
{
 cout << endl << "The game is over - x wins" << endl;
 return true;
}
else if (board[0] == "x" && board[4] == "x" && board[8] == "x")
{
 cout << endl << "The game is over - x wins" << endl;
 return true;
}
else if (board[2] == "x" && board[4] == "x" && board[6] == "x")
{
 cout << endl << "The game is over - x wins" << endl;
 return true;
}
else if (board[0] == "x" && board[3] == "x" && board[6] == "x")
{
 cout << endl << "The game is over - x wins" << endl;
 return true;
}
else if (board[1] == "x" && board[4] == "x" && board[7] == "x")
{
 cout << endl << "The game is over - x wins" << endl;
 return true;
}
else if (board[2] == "x" && board[5] == "x" && board[8] == "x")
{
 cout << endl << "The game is over - x wins" << endl;
 return true;
}
else if (board[0] == "o" && board[1] == "o" && board[2] == "o")
{
 cout << endl << "The game is over - o wins" << endl;
 return true;
}
else if (board[3] == "o" && board[4] == "o" && board[5] == "o")
{
 cout << endl << "The game is over - o wins" << endl;
 return true;
}
else if (board[6] == "o" && board[7] == "o" && board[8] == "o")
{
 cout << endl << "The game is over - o wins" << endl;
 return true;
}
else if (board[0] == "o" && board[4] == "o" && board[8] == "o")
{
 cout << endl << "The game is over - o wins" << endl;
 return true;
}
else if (board[2] == "o" && board[4] == "o" && board[6] == "o")
{
 cout << endl << "The game is over - o wins" << endl;
 return true;
}
else if (board[0] == "o" && board[3] == "o" && board[6] == "o")
{
 cout << endl << "The game is over - o wins" << endl;
 return true;
}
else if (board[1] == "o" && board[4] == "o" && board[7] == "o")
{
 cout << endl << "The game is over - o wins" << endl;
 return true;
}
else if (board[2] == "o" && board[5] == "o" && board[8] == "o")
{
 cout << endl << "The game is over - o wins" << endl;
 return true;
}
else if (board[0] != " " && board[1] != " " && board[2] != " " && board[3] != " " && board[4] != " " && board[5] != " " && board[6] != " " && board[7] != " " && board[8] != " ")
{
 cout << "It's a draw!" << endl;
 return true;
}
// more to do here (don't forget to check for draw)
return false;
}// end of isGameOver
// displays tic tac toe board in the format
// |0 1 2|
// |3 4 5|
// |6 7 8|
string displayBoard(string board[9])
{
  string str = "";

  for (int i = 0; i < 9; i++)
  {
  if (i == 0)
  {
	 str = str  + "|" + board[i];
  }
  else if (i == 2 || i == 5)
  {
	 str = str + board[i] + "|\n|";
  }
  else if (i == 8)
  {
	 str = str +  board[i] + "|\n";
  }
  else
  {
	 str = str + board[i];
  }
  }

  return str;
}// end of displayBoard

 

 

Lenke til kommentar
Videoannonse
Annonse

Du må forenkle denne koden vesentlig.

 

1. Ikke bruk string for board. Dette burde være en char[3][3].

2. Sjekken for om noen har vunnet bær være vesentlig enklere.

3. Du reseeder som gjør at datamaskinen vil prøve det samme tallet igjen og igjen og igjen

 

 

#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
const string displayBoard(const char board[3][3]);   // displays tic tac toe board
const bool isGameOver(const char board[3][3]);		  // checks if game is over
void displayGameWelcome();					    // displays welcome message
// Credits
// [url="http://www.codingmix.com/2010/07/simples-cplusplus-tic-tac-toe-game-ever_24.html"]http://www.codingmix...me-ever_24.html[/url]
int main()
{
   char board[3][3];			   // tic tac toe, top row 0 thru 2, middle row 3 thru 5, bottom row 6 thru 8
   int position = 0;			 // player's position
   displayGameWelcome();
   // initializing board with blank spaces
   for (int i = 0; i < 9; i++)
   {
    ((char*)board)[i] = ' ';
   }
   srand(time(NULL));
   while (true)
   {
    // player #1's turn **************************
    while (true)
    {
	    cout << "Enter your position: ";
	    cin >> position;
	    if(position < 0 || position > 8)
	    {
		    cout << "Invalid number." << endl;
		    continue;
	    }
	    int x = position % 3;
	    int y = position / 3;
	    if (board[x][y] == ' ')
	    {
		    board[x][y] = 'x';  // placing x in desired board location
		    break;
	    }
	    else
	    {
		    cout << "That position is already occupied." << endl;
		    cout << displayBoard(board) << endl;
		    continue;
	    }
    }
    if (isGameOver(board))
    {
	    cout << displayBoard(board) << endl;
	    break;
    }
    // player #2's turn **********************************
    while (true)
    {
	    int x = rand() % 3;
	    int y = rand() % 3;
	    if(board[x][y] == ' ')
	    {
		    board[x][y] = 'o';
		    break;
	    }
    }
    if (isGameOver(board))
    {
	    cout << displayBoard(board) << endl;
	    break;
    }
    cout << displayBoard(board) << endl;
   }// end of validMove while loop
   cin.get();
   return 0;
}// end of main
const bool equal(const char c1, const char c2, const char c3)
{
   return c1 == c2 && c3 == c1;
}
const char WhoWon(const char board[3][3])
{
 for(int i = 0; i < 3; i++)
 {
   if(equal(board[i][0], board[i][1], board[i][2]) && board[i][0] != ' ')
  return board[i][0];
   if(equal(board[0][i], board[1][i], board[2][i]) && board[0][i] != ' ')
  return board[i][0];
 }
 if(equal(board[0][0], board[1][1], board[2][2]) && board[0][0] != ' ')
   return board[0][0];
 if(equal(board[2][0], board[1][1], board[0][2]) && board[2][0] != ' ')
   return board[2][0];
 return ' ';
}
// ************************** functions *************************
void displayGameWelcome()
{
   cout << "WELCOME TO TIC TAC TOE" << endl;
   cout << "This game is developed by Mats Gausdal" << endl;
   cout << "****************************\n\n\n";
}// end of displayGameWelcome
// checks if game is over
const bool isGameOver(const char board[3][3])
{
   const char result = WhoWon(board);
   if(result == ' ')
    return false;
   cout << "Game is over - " << result << " won!" << endl;
   return true;
}// end of isGameOver
// displays tic tac toe board in the format
// |0 1 2|
// |3 4 5|
// |6 7 8|
const string displayBoard(const char board[3][3])
{
   string str = "";
   for (int i = 0; i < 3; i++)
   {
    str += "|";
    for(int j = 0; j < 3; j++)
    {
	    str += board[j][i];
	    if(j < 2)
		    str += ' ';
    }
    str += "|";
    str += "\n";
   }
   return str;
}// end of displayBoard

 

Endret av GeirGrusom
  • Liker 1
Lenke til kommentar

Hvor oppstår den uendelige loopen - den første while'n (player 1) eller den andre (player 2)?

 

Det er player 2.

 

@GeirGrusom

 

Jeg gjør dette for et prosjekt i c++ klassen. Læreren min krever at jeg må bruke srand(1); Takk for svar.

Lenke til kommentar

Det er player 2.

 

@GeirGrusom

 

Jeg gjør dette for et prosjekt i c++ klassen. Læreren min krever at jeg må bruke srand(1); Takk for svar.

Men hvis du gjør det foran rand() så vil den prøve det samme tallet igjen og igjen kan være grunnen til den evige loopen. Kall srand(1) én gang på starten av programmet.

Lenke til kommentar

Har testet programmet du gav meg. Trenger hjelp med dette.

 

 

const bool equal(const char c1, const char c2, const char c3)
{
return c1 == c2 && c3 == c1;
}
const char WhoWon(const char board[3][3])
{
 for(int i = 0; i < 3; i++)
 {
if(equal(board[i][0], board[i][1], board[i][2]) && board[i][0] != ' ')
	  return board[i][0];
if(equal(board[0][i], board[1][i], board[2][i]) && board[0][i] != ' ')
	  return board[i][0];
 }
 if(equal(board[0][0], board[1][1], board[2][2]) && board[0][0] != ' ')
return board[0][0];
 if(equal(board[2][0], board[1][1], board[0][2]) && board[2][0] != ' ')
return board[2][0];
 return ' ';
}

 

Hva er funksjonen til equal?

 

Og WhoWon sjekker x og y koordinatene mot hverandre, og etter mine øyner burde den funke 100% men allikevel så klarer den ikke f.eks. denne:

 

1446587.jpeg

 

Litt vanskelig og se. Men int x = (board[0][3], board[1][3], board[2][3])

 

Og hvorfor vinner "o" her?

1446586.jpeg

 

Samme xy koordinater for "x" som forrige. Den viser at "o" vinner, når "x" burde vinne.

Endret av matshg
Lenke til kommentar

equal er bare korthåndsfunksjon for å sjekke om de tre verdiene er like. Den sjekker om a = b og c = a som vil si at alle tre er like.

 

Det er en programmeringsfeil fra min side i koden:

 

const bool equal(const char c1, const char c2, const char c3)
{
    return c1 == c2 && c3 == c1;
}
const char WhoWon(const char board[3][3])
{
 for(int i = 0; i < 3; i++)
 {
    if(equal(board[i][0], board[i][1], board[i][2]) && board[i][0] != ' ')
			  return board[i][0];
    if(equal(board[0][i], board[1][i], board[2][i]) && board[0][i] != ' ')
			  return board[0][i];
 }
 if(equal(board[0][0], board[1][1], board[2][2]) && board[0][0] != ' ')
    return board[0][0];
 if(equal(board[2][0], board[1][1], board[0][2]) && board[2][0] != ' ')
    return board[2][0];
 return ' ';
}

Lenke til kommentar

equal er bare korthåndsfunksjon for å sjekke om de tre verdiene er like. Den sjekker om a = b og c = a som vil si at alle tre er like.

 

Det er en programmeringsfeil fra min side i koden:

 

Takk for hjelpen. Bare en liten ting. Hvis det blir uavgjort, hvordan får jeg programmet til å vise det er draw?

Lenke til kommentar

Fant det ut ved å gjøre dette

 

const bool isGameOver(const char board[3][3])
{
   const char result = WhoWon(board);
   if(result == ' ')
	    return false;
   cout << "Game is over - " << result << " won!" << endl;

if (result !=' ')
{
 cout << "It's a draw" << endl;
}
   return true;
}// end of isGameOver

Lenke til kommentar

Opprett en konto eller logg inn for å kommentere

Du må være et medlem for å kunne skrive en kommentar

Opprett konto

Det er enkelt å melde seg inn for å starte en ny konto!

Start en konto

Logg inn

Har du allerede en konto? Logg inn her.

Logg inn nå
  • Hvem er aktive   0 medlemmer

    • Ingen innloggede medlemmer aktive
×
×
  • Opprett ny...