(上大学后重学C++系列) 虽然标题是面向对象,但是写出来感觉和面向过程也差不多。
写了两个多小时,但是只实现了基本的双人对弈功能…
棋盘的样式参考了这一篇:
|---|---|
| X | O |
|---|---|
wsad控制光标移动,回车下子。控制光标的方法参考了这篇blog。 然后不回显的输入字符用的getch(),注意windows下getch读回车是读的’\r\n’,也就是只保留了 ‘\r’。 判断是否连成五子的方式是每下一步就检测其四条线上是否有连续相邻的5个子。
Code:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<conio.h>
#include<windows.h>
struct Position{
int x,y;
};
class ChessBoard{
private:
int sta[25][25];
HANDLE Cursor;
public:
int winner,N;
ChessBoard(){
N=17,memset(sta,0,sizeof sta),winner=0;
Cursor = GetStdHandle(STD_OUTPUT_HANDLE);
}
void show(){
system("cls");
char ch[3]={' ','O','X'};
for(int i=1;i<=N;i++){
for(int j=1;j<=N;j++) printf("|---");
printf("|\n");
for(int j=1;j<=N;j++) printf("| %c ",ch[sta[i][j]]);
printf("|\n");
}
for(int j=1;j<=N;j++) printf("|---");
printf("|\n");
}
void movecursor(Position p){
SetConsoleCursorPosition(Cursor,{p.y*4-2,p.x*2-1});
}
bool checkwin(int x,int y){
int dir[4][2][2]={{{-1,0},{1,0}},{{0,-1},{0,1}},{{-1,-1},{1,1}},{{-1,1},{1,-1}}};
int t=sta[x][y];
for(int k=0;k<4;k++){
int L=1,R=1;
while(sta[x+L*dir[k][0][0]][y+L*dir[k][0][1]]==t) L++;
while(sta[x+R*dir[k][1][0]][y+R*dir[k][1][1]]==t) R++;
if(L+R>5) return 1;
}
return 0;
}
Position Setchess(int type, Position p){
movecursor(p);
char ch;
while((ch=getch())!='\r'||sta[p.x][p.y]!=0){
if(ch=='w'&&p.x>1) p.x--;
if(ch=='s'&&p.x<N) p.x++;
if(ch=='a'&&p.y>1) p.y--;
if(ch=='d'&&p.y<N) p.y++;
movecursor(p);
}
sta[p.x][p.y] = type;
winner = checkwin(p.x,p.y) ? type : 0;
return p;
}
};
class Player{
public:
char name[25];
int chesstype;
Position p;
void init(int id,int N){
chesstype = id;
p.x = p.y = (N+1)/2;
printf("Please enter player %d 's name: (without space)\n",id);
scanf("%s",name);
}
};
class Game{
public:
void Prepare(){
printf("------ Gobang Instructions ------\n");
printf("Use 'w', 's', 'a', 'd' to move the cursor.\n");
printf("Push 'Enter' to set the chess.\n\n");
printf("Now Push 'Enter' to start the game.\n");
while(getch()!='\r');
}
void start(){
Prepare();
ChessBoard Board;
Player A,B;
A.init(1,Board.N),B.init(2,Board.N);
Board.show();
int win = 0;
for(int t=0;Board.winner==0;t=!t){
if(t==0){
printf("It's %s's turn.\n",A.name);
A.p = Board.Setchess(A.chesstype,B.p);
}
else{
printf("It's %s's turn.\n",B.name);
B.p = Board.Setchess(B.chesstype,A.p);
}
Board.show();
}
printf("Player %s wins!\n",Board.winner==A.chesstype?A.name:B.name);
}
};
int main()
{
Game G;
G.start();
return 0;
}
|