c++写的井字棋(tic_tac_toe)
看见网上的好多算法 参差不齐,几百行的判断,懒得抄了 果断自己写一个
这个算法可优化的地方在于,稍微改一下就可以封装做成类,但是我不想封装了,有需要的自己封装
拿走的同学点个赞?有什么看法直接提出呗。
#include <iostream>
#include <time.h>
#include <random>
using namespace std;
void print(int s[3][3]);
bool check(int s[3][3]);
bool isEmpty(int s[3][3],int num);
bool isFull(int s[3][3]);
bool value(int s[3][3],int num,int flag);
int play(int s[3][3],int flag); //结束返回1 否则返回0
void MakeNull(int s[3][3]);
int main()
{
int s[3][3] = {};
int flag = 1;//选择先手
print(s);
while(flag)
{
MakeNull(s);
cout<<"请选择先手 电脑先手-- 2 你先手-- 1 退出请输入:0\n";
cin>>flag;
while(flag)
{
if(!isFull(s))
{
if(flag==1)
{
if(!play(s,flag))
flag=2;
else
break;
}
if(flag==2)
{
if(!play(s,flag))
flag=1;
else
break;
}
}
else
break;
}
cout<<"继续游戏请输入1,退出请输入0\n";
cin>>flag;
}
if(flag==0)
{
cout<<"游戏结束!\n";
exit(0);
}
}
void print(int s[3][3])
{
cout << "-------" << endl;
for(int x = 0; x < 3; x++)
{
cout << "|";
for(int y = 0; y < 3; y++)
{
if(s[x][y] == 0)
cout << " ";
else if(s[x][y] == 1)
cout << "O";
else if(s[x][y] == 2)
cout << "X";
cout << "|";
}
cout << endl << "-------" << endl;
}
cout << endl;
}
//检查是否结束
bool check(int s[3][3])
{
//行列检查
for(int x = 0;x<3;x++)
{
if(s[x][0]==s[x][1]&&s[x][1]==s[x][2]&&s[x][2]!=0)
return true;
if(s[0][x]==s[1][x]&&s[1][x]==s[2][x]&&s[2][x]!=0)
return true;
}
//对角检查
if(s[0][0]==s[1][1]&&s[1][1]==s[2][2]&&s[2][2]!=0)
return true;
if(s[0][2]==s[1][1]&&s[1][1]==s[2][0]&&s[2][0]!=0)
return true;
return false;
}
//检查是否满
bool isFull(int s[3][3])
{
int full_flag = 1;
for(int x=0;x<3;x++)
{
for(int y = 0;y<3;y++)
{
if(s[x][y]==0)
full_flag=0;
}
}
return full_flag;
}
//检查该处是否为空
bool isEmpty(int s[3][3],int num)
{
if(num>9||num<1)
{
cout<<"输入错误!\n";
return 0;
}
else
{
num=num-1;
if(s[num/3][num%3]==0)
return true;
else
return false;
}
}
bool value(int s[3][3],int num,int flag) //flag用来判断是谁传进来的值
{
num=num-1;
s[num/3][num%3]=flag;
}
/*
*游戏运行
*传进判断参数、看谁先手进行一次判断其后进行循环即可
*/
int play(int s[3][3],int flag)//flag第一个传入的参数 判断是电脑先手还是人先手 人是1 电脑是2
{
//不用判断是不是有效的flag 因为在case那里已经判断过了
int location;
srand(time(0));
if(flag==1)
{
//执行一遍 然后跳到循环
while(1){
cout<<"请输入你的位置1-9:";
cin>>location;
if(isEmpty(s,location)&&!isFull(s))
{
value(s,location,flag);
print(s);
break;
}
}
}
else
{
//执行一遍 然后跳到循环
if(!isFull(s))
{
while(1)
{
location = rand()%9+1;
if(isEmpty(s,location))
{
value(s,location,flag);
print(s);
break;
}
}
}
}
if(!isFull(s))
{
if(check(s))
{
if(flag==1)
{
cout<<"游戏结束!你赢了\n";
return 1;
}
else
{
cout<<"游戏结束!你输了\n";
return 1;
}
}
}
if(isFull(s))
{
cout<<"游戏结束,你们平局!\n";
return 1;
}
return 0;
}
void MakeNull(int s[3][3])
{
for(int i = 0;i<3;i++)
{
for(int j = 0 ;j<3 ;j++)
{
s[i][j]=0;
}
}
}
效果图:
可以不断玩下去,挺好玩的。