简体   繁体   English

使用 switch case 的 C++ Tic-Tac-Toe

[英]C++ Tic-Tac-Toe using switch case

I was trying out a C++ code for the Tic Tac Toe program with help of classes .我在 classes 的帮助下尝试了 Tic Tac Toe 程序的 C++ 代码。 I am new to coding and would appreciate some help.This is what I have done till now.我是编码新手,希望得到一些帮助。这就是我迄今为止所做的。

#include <iostream>
using namespace std;

int turn=1;
class abc
{
private:
int a[9];
char ch1,ch2;
public:


void accept()
{
    if(turn==1)
     {
     cout<<"\n\nPlayer 1 enter choice : ";
     cin>>ch1;
     turn=2;
     }
    else
    {
     cout<<"\n\nPlayer 2 enter choice :";
     cin>>ch2;
     turn=1;
     }
}

void layout()
{
a[0]=1;
a[1]=2;
a[2]=3;
a[3]=4;
a[4]=5;
a[5]=6;
a[6]=7;
a[7]=8;
a[8]=9;

cout<<"\n\n"<<"-----------"<<" "<<a[0]<<"     "<<a[1]<<"     "<<a[2]<<" -----------";       
cout<<"\n"<<"-----------"<<" "<<a[3]<<"     "<<a[5]<<"     "<<a[6]<<" -----------";
cout<<"\n"<<"-----------"<<" "<<a[6]<<"     "<<a[7]<<"     "<<a[8]<<" -----------";
}

void process ()
{
if (turn==1)
{

switch(ch1)
{
    case 1:     
    a[0]='x';
    break;

}
}
}

/*void check()
{
if(a[0]==a[1] && a[1]=a[2]
}
*/

};

int main()
{
abc def;
cout<<"-----------TIC - TAC - TOE-----------";
def.layout();
do
{
    do
    {
    def.accept();
    def.process();
    def.layout();       
    //def.check();
    }while(turn==2);

    }while(turn==1);

    return 0;
}

So , I can switch from player 1 to player 2 , I intend to use the process function for modifying the layout ie if the turn 1 player enters 1 then the array should be layout should be modified accordingly .所以,我可以从玩家 1 切换到玩家 2,我打算使用 process 函数来修改布局,即如果第 1 轮玩家输入 1,那么应该相应地修改数组布局。 And basically I think I know the logic for the check function ie a[0]==a[1] && a[1]=a[2] and the other 7 conditions .基本上我想我知道检查函数的逻辑,即 a[0]==a[1] && a[1]=a[2] 和其他 7 个条件。 I just want to know how to use switch case in this condition.我只想知道在这种情况下如何使用 switch case。

As the comments on your question have implied, your code needs better formatting.正如对您的问题的评论所暗示的那样,您的代码需要更好的格式。 However, to answer your question, you could do something along the lines of:但是,要回答您的问题,您可以执行以下操作:

void process() {
    if (turn == 1) {
        a[ch1 - '0'] = 'x'; //char - '0' to convert char to int
    } else {
        a[ch2 = '0'] = 'o';
    }
};

As you can see, you don't really need a switch here.如您所见,这里并不真正需要开关。 Just use their input to directly access the correct spot in the array.只需使用他们的输入直接访问阵列中的正确位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM