写个签到题。C++项目课见到一个项目题叫《五子棋在线游戏系统》,感觉五子棋+聊天室也不是很难。吃完晚饭闲来无事就简单实现了下五子棋。
#include <iostream>
using namespace std;
const int N = 110;
int n;
char g[N][N]; // 棋盘
int d[N][N]; // 标记棋盘状态(也可直接用g)
int dx[] = {-1, -1, 0, 1, 1, 1, 0, -1}, dy[] = {0, 1, 1, 1, 0, -1, -1, -1}; // 位移矢量
char sign[] = {'+', 'O', 'X'}; // 棋盘格子标志,玩家1和2的标志
bool iswin(int x, int y, int who){
for(int i = 0; i < 4; i ++){ // 4条直线
int t = 1; // 落子处
int xx = x + dx[i], yy = y + dy[i];
while(xx >= 0 && xx < n && yy >= 0 && yy < n && d[xx][yy] == who){
t ++;
xx += dx[i], yy += dy[i];
if(t == 5) return true;
}
int idx = i + 4;
xx = x + dx[idx], yy = y + dy[idx];
while(xx >= 0 && xx < n && yy >= 0 && yy < n && d[xx][yy] == who){
t ++;
xx += dx[idx], yy += dy[idx];
if(t == 5) return true;
}
}
return false;
}
bool isvalid(int x, int y){
if(x >= 0 && x < n && y >= 0 && y < n && d[x][y] == 0){
return true;
}
else{
return false;
}
}
void go(int x, int y, int who){
if(who == 1){
g[x][y] = sign[who], d[x][y] = who;
}
if(who == 2){
g[x][y] = sign[who], d[x][y] = who;
}
}
void plot(){
cout << " " ;
for(int i = 0; i < n; i ++ ){
if(i >= 10) cout << i - 10 << " ";
else cout << i << " ";
}
cout << endl << endl;
// 棋盘
for(int i = 0; i < n; i ++ ){
if(i >= 10) cout << i - 10 << " " ;
else cout << i << " " ;
for(int j = 0; j < n; j ++ ) cout << g[i][j] << " ";
cout << endl;
}
}
int main(){
cout << "输入棋盘大小:" << endl;
cin >> n;
for(int i = 0; i < n; i ++ ){
for(int j = 0; j < n; j ++ ){
g[i][j] = sign[0];
}
}
cout << "棋盘:" << endl;
plot();
int who = 1, pingju = 0; // 玩家1和2 ,操作数
while(true){
cout << "现在到你了:玩家" << who << ", 标志:" << sign[who] << ",请输入落子坐标x y:" << endl;
int x, y;
cin >> x >> y;
if(isvalid(x, y)){
pingju ++;
go(x, y, who);
cout << "目前棋局:" << endl;
plot();
if(iswin(x, y, who)){
cout << who << "获胜了" << endl;
break;
}
if(pingju == n * n){
break;
cout << "平局" << endl;
}
who = 3 - who;
}
else cout << "请在正确范围内下棋:" << endl;
}
return 0;
}
效果图: