#include <iostream>
#include <cstdlib>
#include "getch.h" using namespace std; enum Role{RED=99,BLUE}; class Gobang
{
char board[15][15];
int key_x,key_y;
Role role;
public :
Gobang( int key_x=7, int key_y=7,Role role=RED):key_x(key_x),key_y(key_y),role(role) {} void start( void )
{
for (;;)
{
show_board(); get_key(); if (check_key())
{
show_board();
printf ( "%d\n" ,role);
cout << "恭喜" << (role==RED? "红方" : "蓝方" ) << "胜利!" << endl;
break ;
}
change_role();
}
}
void show_board( void )
{
system ( "clear" );
printf ( " " );
for ( int i=0; i<15; i++)
{
printf ( " %c" , 'A' +i);
}
printf ( "\n" ); for ( int x=0; x<15; x++)
{
printf ( "%2d" ,x+1);
for ( int y=0; y<15; y++)
{
if (RED==board[x][y])
{
printf ( "\33[31m" );
printf ( " @" );
printf ( "\33[0m" );
}
else if (BLUE == board[x][y])
{
printf ( "\33[34m" );
printf ( " #" );
printf ( "\33[0m" );
}
else
{
printf ( " *" );
}
}
printf ( "\n" );
}
}
void get_key( void )
{
for (;;)
{
printf ( "\33[%d;%dH" ,key_x+2,(key_y+2)*2);
switch (getch())
{
case 183: key_x>0 && key_x--; break ;
case 184: key_x<15 && key_x++; break ;
case 185: key_y<15 && key_y++; break ;
case 186: key_y>0 && key_y--; break ;
case 10: if (RED!=board[key_x][key_y] && BLUE!=board[key_x][key_y])
{
board[key_x][key_y] = role;
return ;
}
}
}
} size_t count_key( int off_x, int off_y)
{
size_t count = 0;
for ( int x=key_x+off_x,y=key_y+off_y;
x>=0 && x<15 && y>=0 && y<15 && board[x][y] == board[key_x][key_y]; x+=off_x,y+=off_y)
{
count++;
}
return count;
}
bool check_key( void )
{
if (4 <= count_key(0,-1)+count_key(0,1)) return true ;
if (4 <= count_key(-1,0)+count_key(1,0)) return true ;
if (4 <= count_key(-1,-1)+count_key(1,1)) return true ;
if (4 <= count_key(-1,1)+count_key(1,-1)) return true ;
return false ;
}
void change_role( void )
{
role = (RED==role?BLUE:RED);
}
}; int main()
{
Gobang b;
b.start();
}
|