TicTacToe C ++函数

时间:2018-01-19 11:11:53

标签: c++ exit

游戏不想退出/关闭。有人告诉我我错过了什么?另外,你认为我已正确编码游戏吗?

源代码:

#include<iostream>
#include<iomanip>

using namespace std;

void drawBoard(char board[][3]);
char checkWinner3by3(char board[][3]);


 int main()
{

    char board[3][3] = {{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};


  int row;
  int column;

  bool is_move;
  bool is_row;
  bool is_column;

  cout<<"********** TIC TAC TOE ************\n";

 {

    is_move = false; 
    is_row = false;
    is_column = false;

    drawBoard(board);

    cout << "Player ";
    if(player == 'X')
    {
        cout << 1;
    }
    else
    {
        cout << 2;
    }
    cout << "'s turn:" << endl;

    is_move = false;
    while(!is_move)

    {  

        while(!is_row)
        {
            cout << "Row: ";
            cin >> row;
            if(row == 1 || row == 2 || row == 3)
            {
                is_row = true;
            }
            else
            {
                cout << endl << "Invalid row!" << endl;
            }

        } 

        /
        is_column = false;
        while(!is_column)

        {
            cout << "Column: ";
            cin >> column;
            if(column == 1 || column == 2 || column == 3)
            {
                is_column = true;
            }
            else
            {
                cout << endl << "Invalid column!" << endl;
            }

        }

这里不相关的东西。

        if(board[row-1][column-1] == ' ')
        {

            board[row-1][column-1] = player;
            is_move = true;

            if(player == 'X')
            {
                player = 'O';
            }
            else
            {
                player = 'X';
            }
        }


        else
        {
            cout<<"The selected space is occupied!" << endl;
            cout << "Select a different space:" << endl << endl;
            drawBoard(board);
        }
    } 

    cout << endl;

检查获胜者

    winner = checkWinner3by3(board);


    if(winner == 'X' || winner == 'O')
    {
        drawBoard(board);


        cout<<"Congratulations! Player ";
        if(winner == 'X')
        {
            cout << 1;
        }
        else
        {
            cout << 2;
        }
        cout<<" is the winner!"<<endl;
    }

    else if(winner == 'T')
     {
        drawBoard(board);


        cout << "It's a tie!" << endl;
      }

    } 

   system("pause");
   return 0;
   }

董事会在这里。

    void drawBoard(char board[][3])
  {
    char print[][3] = {{' ',' ',' '},
                    {' ',' ',' '},
                    {' ',' ',' '}};

   cout << "     1   2   3" << endl;
   cout << "   +---+---+---+" << endl;

 cout << " 1" << " | " << print[0][0] << " | " << print[0][1] << " | " 
 << print[0][2] << " | " << endl;
 cout << "   +---+---+---+" << endl;

cout << " 2" << " | " << print[1][0] << " | " << print[1][1] << " | " 
 << print[1][2] << " | " << endl;
cout << "   +---+---+---+" << endl;

cout << " 3" << " | " << print[2][0] << " | " << print[2][1] << " | " 
 << print[2][2] << " | " << endl;
cout << "   +---+---+---+" << endl;

 }

 char checkWinner3by3(char board[][3])
 {


 for(i=0; i<3; i++) 
 {
    if(board[i][0]==board[i][1] && board[i][0]==board[i][2])
      {
         return board[i][0];
      }
   }

  for(i=0; i<3; i++) 
  {
     if(board[0][i]==board[1][i] && board[0][i]==board[2][i]) 
    {
        return board[0][i];
    }
   }

  if(board[0][0]==board[1][1] && board[1][1]==board[2][2])
  {
    return board[0][0];
   }

   if(board[0][2]==board[1][1] && board[1][1]==board[2][0])
  {
    return board[0][2];
  }   

   return ' ';
  }

这是完整的源代码 - 我想制作一款游戏,老实说我认为这是最好的方式,从了解我能做些什么来改进它。

1 个答案:

答案 0 :(得分:0)

您尚未声明变量“player”&amp; “胜利者”尚未初始化它们......但这可能是因为没有显示完整的代码。 在返回之前你有系统(“暂停”)...为什么你把它放在那里? ......现在我进一步看起来已经搞砸了

我做了一次Tic-Tac-Toe,它有点类似于你尝试做的除了通过2d数组选择之外的东西,你应该考虑使用它的一部分来纠正你的代码。

#include <iostream>
#include <iomanip>
using namespace std;

char* cBox{ new char[9]{ '1', '2', '3', '4', '5', '6', '7', '8', '9' } };               // cBox are tic tac toe squares
char* PcBox{ nullptr };                                                                 // PcBox will be pointers to cBox squares
bool EndGame{ true }, VailidMove{ true }, WinGame{ true };                              // Global bool varibles are initially set to true to test for validity
size_t PlayerMove{ 1 };
int Move;

int score(size_t PlayerMove);                                                            /********************************/
void Board();                                                                           /*                              */
void error();                                                                          /*    Function Prototypes       */
void GameOver();                                                                      /*                              */
int scoreboard(int score1, int score2);                                              /********************************/

int main() {
    int score1{}, score2{};
    int sum{};
    int winner{};
    int const total{ 756 };
    char PlayerIcon;

    // do while loop
    do {
        // print scoreboard
        scoreboard(score1, score2);

        // Print board
        Board();

        // This conditional forces the first Player to be 'X'... Player2 'O'
        (PlayerMove == 1) ? PlayerIcon = 'X' : PlayerIcon = 'O';

        // Time for the player to move
        cout << endl << setw(51) << "Player" << PlayerMove << "'s move:";
        cin >> Move;

        VailidMove = false;                                                 // ValidMove is assigned to false within the "do loop"...it will remain false until a valid key is entered..
                                                                            //... it's conditionally tested within the while loop until the player's move is true(valid)
        // Loop until we get a valid move
        while (!VailidMove) {
            system("CLS");                                                  // Clear the screen
            (PcBox = &cBox[Move - 1]);                                      // For our move selection, point PcBox to the address of the array cBox[index] on the free store

            if (!(*PcBox == 'X' || *PcBox == 'O') && (cin) && Move != 0)    // this checks the location for PlayerIcons...as one cannot place a new playericon where one already resides...
                                                                            // ...also tests whether a legit key input..aka not a "letter" or a "0"
            {
                VailidMove = true;
                *PcBox = PlayerIcon;                                        // A valid playericon is placed in a free box on the board
            }

            else
            {
                error();                                                    // Anything else other than a valid selection will throw an error and return to the beginning of the block...
                return main();                                              // ...querying the player for a valid selection until one is entered
            }
        };

        EndGame = false;                                                    // Again like "VailidMove" we set EndGame to false to test against the following conditions

        // This is a combintion of seperate win conditions... 3 the same, across or diagonal over entire board
        if (cBox[0] == cBox[1] && cBox[1] == cBox[2])
            GameOver();
        if (cBox[0] == cBox[4] && cBox[8] == cBox[4])
            GameOver();
        if (cBox[1] == cBox[4] && cBox[7] == cBox[4])
            GameOver();
        if (cBox[2] == cBox[4] && cBox[6] == cBox[4])
            GameOver();
        if (cBox[2] == cBox[8] && cBox[5] == cBox[8])
            GameOver();
        if (cBox[3] == cBox[0] && cBox[6] == cBox[0])
            GameOver();
        if (cBox[3] == cBox[4] && cBox[5] == cBox[4])
            GameOver();
        if (cBox[6] == cBox[8] && cBox[7] == cBox[8])
            GameOver();

        // If the board is full and no one wins then it is a tie...this piece just sums up all the player icons as ascii integers...
        // ...if the board is full of them, then the sum is 756 and it is a tie.
        sum += (*PcBox);                                                     // add player icon to sum...Ascii to int
        if ((sum == total) && !EndGame)                                      // if sum of playericon for entire board = 756...no win
        {
            EndGame = true;
            WinGame = false;
            sum = 0;                                                         //reset sum to zero
            scoreboard(score1, score2);
        }
        // End/Win game conditions
        if (EndGame) {                                                       // game over? test choices
            if (WinGame) {                                                   // We nest this here soley if EndGame & WinGame is true... else if just WinGame is true its a draw
                if (PlayerMove == 1) { score1 = score(PlayerMove); }
                if (PlayerMove == 2) { score2 = score(PlayerMove); }
                scoreboard(score1, score2);
                winner = PlayerMove;
            }

            Board();
            if (WinGame)
                cout << "\n" << setw(51) << "PLAYER " << winner << " WINS!" << endl;
            cout << endl << setw(57) << "Game Over!!!" << endl;
            cout << endl << setw(59) << "Play again y/n?";                      // Query the player for another game
            char PlayAgain;
            cin >> PlayAgain;

            // This resets the board, if the player wants another game, it uses a for loop to increment simultaneously it's "ascii integer", along side it's "int" equivalent...
            //... overwriting & reseting the board from 1-9 with the original characters
            if (PlayAgain == 'y' || PlayAgain == 'Y') {
                EndGame = false;
                for (int i = 0, j = 49; i < 9 && j <= 57; i++, j++)        // ASCII int 49 = char '1'... to 57 = char '9'
                {
                    (cBox[i] = (char)j);                                   // Clear the board
                }
                sum = 0;                                                   // Reset sum to zero
                system("CLS");                                             // Clear the screen  
            }

            PlayerMove = 1;

            if (PlayAgain == 'n') {
                EndGame = true;
            }
        }
        else
        {

            (PlayerMove == 1) ? PlayerMove = 2 : PlayerMove = 1;

        }
    } while (!EndGame);

    delete[] cBox;                                                        // Free up memory...
    cBox = nullptr;

    cout << "\n\t\t\t\t\t";
    return 0;
} 

// Function definiton to print game board
inline void Board() {
    {
        cout << endl << '\n' << '\n' << endl;
        cout << setw(50) << cBox[0] << "|" << cBox[1] << "|" << cBox[2] << endl;
        cout << setw(54) << "-+-+-" << endl;
        cout << setw(50) << cBox[3] << "|" << cBox[4] << "|" << cBox[5] << endl;
        cout << setw(54) << "-+-+-" << endl;
        cout << setw(50) << cBox[6] << "|" << cBox[7] << "|" << cBox[8] << endl;
    }
}

// Function definiton to keep score
int score(size_t PlayerMove)
{
    int static score1{ 1 };
    int static score2{ 1 };
    if (PlayerMove % 2)
        return score1++;
    else
        return score2++;
}

// Function definiton to print scoreboard
int scoreboard(int score1, int score2)
{
    cout << endl << setfill(' ') << setw(47) << "PLAYER 1: " << score1 << " " << "PLAYER 2: " << score2;
    return(score1, score2);
}

// Function definiton to throw an error
void error() {
    {
        cout << setfill(' ') << setw(64) << "Invalid Move. Try again." << endl;
        cin.clear();                                                //clear the error flags.
        cin.ignore();                                               //sync up the stream in case the user entered white space
    }
}

// Function definiton to end game
void GameOver()
{
    EndGame = true;
}