使用类的C ++ Tic-Tac-Toe

时间:2014-09-28 19:08:45

标签: c++ class tic-tac-toe

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

这里我将展示我迄今为止的代码。 我为电路板定义了一个矩阵。 这些功能将绘制棋盘,将从玩家移动,并将切换转弯。

#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");
}

1 个答案:

答案 0 :(得分:1)

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;
    }
}