C++ Tic-Tac-Toe using classes

C++ Tic-Tac-Toe using classes

本文关键字:classes using Tic-Tac-Toe C++      更新时间:2023-10-16

游戏显示矩阵,但不更新当前移动。我该怎么做?

在这里,我将显示到目前为止的代码。我为董事会定义了一个矩阵。这些功能将绘制棋盘,从玩家那里获得移动,并切换回合。

#ifndef TICTACTOE_H
#define TICTACTOE_H
class TicTacToe
{
private:
    char board[3][3];
public:
    void DrawBoard();
    void PrintBoard();
    void GetMove(int move);
    void TogglePlayer(char player);
    bool DetermineDraw();
};
#endif

以下是实现文件:我绘制棋盘的功能显示矩阵,但不更新移动。

#include <iostream>
#include "TicTacToe.h"
using namespace std;

void TicTacToe::DrawBoard()
{
    system("cls");
    cout <<"tWelcome to the Classes Tic Tac Toe! n";
    char board[3][3] =
    { 
      {'1','2','3'},
      {'4','5','6'},
      {'7','8','9'},
    };
    for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
        {
            cout << board[i][j] << " ";
        }
        cout << endl;
    }
}

void TicTacToe::GetMove(int move)
{
    char player = 'X';
    cout <<"nEnter the number of the field you would like to move:n";
    cin >> move;
    if( move == 1)
    {
        board[0][0] = player;
    }
    else if(move == 2)
    {
        board[0][1] = player;
    }
    else if(move == 3)
    {
        board[0][2] = player;
    }
    else if(move == 4)
    {
        board[1][0] = player;
    }
    else if(move == 5)
    {
        board[1][1] = player;
    }
    else if(move == 6)
    {
        board[1][2] = player;
    }
    else if(move == 7)
    {
        board[2][0] = player;
    }
    else if(move == 8)
    {
        board[2][1] = player;
    }
    else if(move == 9)
    {
        board[2][2] = player;
    }
}
void TicTacToe::TogglePlayer(char player)
{
    if (player == 'X')
        player = 'O';
    else if(player == 'O')
        player = 'X';
}
bool TicTacToe::DetermineDraw()
{
    for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
        {
            if(board[i][j] == 'X' && board[i][j] == 'O')
                return true;
            else 
                return false;
        }
    }
}

这是主文件,我会继续循环游戏,而不是平局。我不知道为什么棋盘上没有显示这个动作。

 #include <iostream>
#include "TicTacToe.h"
using namespace std;
int main()
{
    TicTacToe game;
    char player = 'X';
    while(game.DetermineDraw() == false)
    {
        game.DrawBoard();
        game.GetMove(player);
        game.TogglePlayer(player);
    }
    system("pause");
}

TicTacToe::DrawBoard()总是绘制同一块板,因为它使用了本地定义的变量board。要更正:删除本地定义并初始化构造函数中的类变量board

TicTacToe::TicTacToe()
{
     for (int i = 0; i < 9; i++)
         board[i / 3][i % 3] = '1' + i;
}
void TicTacToe::DrawBoard()
{
    system("cls");
    cout <<"tWelcome to the Classes Tic Tac Toe! n";
    for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
        {
            cout << board[i][j] << " ";
        }
        cout << endl;
    }
}