C++实现简易五子棋
程序员文章站
2022-03-13 15:35:30
...
#include<iostream>
#include<string>
#include <windows.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
using namespace std;
string a[1000];
int n,m;
void init(int n,int m) {
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
a[i][j]='-';
}
}
}
void star() {
for(int i=1;i<=10;i++)
cout<<endl;
for(int i=1;i<=10;i++) {
cout<<" ";
}
cout<<"请输入棋盘尺寸";
}
bool check1(int x,int y,int play) {
int ans=1;
/*if(play==2) {
return false;
}*/
int q=x;
while(q>=1&&a[q][y]=='*') {//上
ans++;
q--;
}
int p=x;
while(p<=n&&a[p][y]=='*') {//下
ans++;
p++;
}
p=y;
while(p<=m&&a[x][p]=='*') {//右
ans++;
p++;
}
p=y;
while(p>=1&&a[x][p]=='*') {//左
ans++;
p--;
}
int xx,yy;
xx=x;yy=y;
while(xx>=1&&yy>=1&&a[xx][yy]=='*') {//左上
ans++;
xx--;
yy--;
}
xx=x;yy=y;
while(yy<=m&&xx>=1&&a[xx][yy]=='*') {//右上
ans++;
xx--;
yy++;
}
xx=x;yy=y;
while(xx<=n&&yy>=1&&a[xx][yy]=='*') {//左下
ans++;
xx++;
yy--;
}
xx=x;yy=y;
while(xx<=n&&yy<=m&&a[xx][yy]=='*') {//右下
ans++;
xx++;
yy++;
}
ans-=8;
if(ans==5) {
return true;
}else {
return false;
}
}
bool check2(int x,int y,int play) {
int ans=0;
ans++;
int q=x;
while(q>=1&&a[q][y]=='#') {//上
ans++;
q--;
}
int p=x;
while(p<=n&&a[p][y]=='#') {//下
ans++;
p++;
}
p=y;
while(p<=m&&a[x][p]=='#') {//右
ans++;
p++;
}
p=y;
while(p>=1&&a[x][p]=='#') {//左
ans++;
p--;
}
int xx,yy;
xx=x;yy=y;
while(xx>=1&&yy>=1&&a[xx][yy]=='#') {//左上
ans++;
xx--;
yy--;
}
xx=x;yy=y;
while(yy<=m&&xx>=1&&a[xx][yy]=='#') {//右上
ans++;
xx--;
yy++;
}
xx=x;yy=y;
while(xx<=n&&yy>=1&&a[xx][yy]=='#') {//左下
ans++;
xx++;
yy--;
}
xx=x;yy=y;
while(xx<=n&&yy<=m&&a[xx][yy]=='#') {//右下
ans++;
xx++;
yy++;
}
ans-=8;
if(ans==5) {
return true;
}else {
return false;
}
}
void init1(int x,int y,int play) {
if(play==1) {
a[x][y]='*';
}else {
a[x][y]='#';
}
}
void pr(int x,int y,int play) {
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
cout<<a[i][j];
}
cout<<endl;
}
}
int main() {
star();
while(1) {
cin>>n>>m;
init(n,m);
system("cls");
int x,y,play;
cout<<"请输入棋盘坐标x,y输入玩家1或2"<<endl;
while(cin>>x>>y>>play) {
init1(x,y,play);
if(check1(x,y,play)==false&&check2(x,y,play)==false) {
pr(x,y,play);
}else {
system("cls");
if(check1(x,y,play)==true) {
cout<<"*"<<" you is winner";
}else if(check2(x,y,play)==true){
cout<<"#"<<" you is winner";
}
cout<<endl;
cout<<"game over"<<endl;
cout<<"play game again";
}
}
}
}