c++控制台五子棋
今天有半个小时的时间闲来无聊,就想起最开始写程序的时候写的五子棋,就想写写看。用的VS2010,实现起来也比较简单。
首先先构思棋盘,首先得标注棋牌边缘设计,随便设计了一个13 × 13,中间肯定棋盘得存储,就用简单的数组。用了cout和cin,然后用了setw(4)
#include <iostream>
using namespace std;
#include <iomanip>
int num[13][13] = {0};
下棋肯定得循环吧,写一个while,让玩家输入一个位置,那么肯定得在1-13之间,其他好像就没有什么要求了。
int _tmain(int argc, _TCHAR* argv[])
{
int a,b,c,d;
int res = 0;
display();
while(1)
{
loop:
cout << "请1输入位置 x y: ";
cin >> a >> b;
if(a < 0 || a > 13 || b < 0 || b > 13)
{
cout << "请输入范围数字" <<endl;
}
else
{
if(num[a - 1][b - 1] == 0)
{
num[a - 1][b - 1] = 1;
}
else
{
cout << "请下在空棋盘上 " <<endl;
goto loop;
}
}
display();
int res = win();
if(res == 1 || res == 2)
{
cout << res << " Win the game" <<endl;
break;
}
loop2:
cout << "请2输入位置 x y: ";
cin >> c >> d;
if(c < 0 || c > 13 || d < 0 || d > 13)
{
cout << "请输入范围数字" <<endl;
}
else
{
if(num[c - 1][d - 1] == 0)
{
num[c - 1][d - 1] = 2;
}
else
{
cout << "请下在空棋盘上 " <<endl;
goto loop2;
}
}
display();
res = win();
if(res == 1 || res == 2)
{
cout << res << " win the game" <<endl;
break;
}
}
return 0;
}
这个是mian函数,没有多花时间构思啊,突然想起不能够下在别人或者自己下过的位置,又懒得改了,直接加了loop,我是不怎么喜欢loop这个东西的,但是写都写了就这样吧。
main函数的display,就比较简单,
void display()
{
int k = 0;
cout << setw(4) << "0" << setw(4) << "一" << setw(4) << "二" << setw(4) << "三" << setw(4) << "四" << setw(4) << "五" << setw(4)
<< "六" << setw(4) << "七" << setw(4) << "八" << setw(4) << "九" << setw(4) << "十" << setw(4) << "11" << setw(4) << "12"
<< setw(4) << "13" << endl << endl;
for(int j = 1; j <= 13; j++)
{
cout << setw(4) << j;
for(int m = 1;m <= 13;m ++)
{
cout << setw(4) << num[j-1][m-1];
}
cout << endl << endl;
}
}
最后就是判断win了,三三禁手点没写,如果要写加入win的判断就行了,也没什么技术含量就是很长就懒得写了。至于人机对战没啥意思,自动生成点太简单,要真实下又太难,就省略吧。
int win()
{
int i ,j ,k ;
for(i = 0;i < 13; i ++)
{
for(j = 0; j < 13 ;j ++)
{
if((num[i][j] == num[i][j+1]) && (num[i][j] == num[i][j+2]) && (num[i][j] == num[i][j+3]) && (num[i][j] == num[i][j+4]) && num[i][j] != 0 && (j+5 <= 13))
{
k = num[i][j];
return k;
}
if((num[i][j] == num[i+1][j]) && (num[i][j] == num[i+2][j]) && (num[i][j] == num[i+3][j]) && (num[i][j] == num[i+4][j]) && num[i][j] != 0 && (i+5 <= 13))
{
k = num[i][j];
return k;
}
if((num[i][j] == num[i+1][j+1]) && (num[i][j] == num[i+2][j+2]) && (num[i][j] == num[i+3][j+3]) && (num[i][j] == num[i+4][j+4]) && num[i][j] != 0 && (j+5 <= 13 && i+5 <= 13))
{
k = num[i][j];
return k;
}
}
}
return 0;
}
靠着这半个小时怀念大学时光,哈哈。