五子棋——人人玩法

#include <iostream>

#include <cstdlib> 
#define N 10        // 棋盘尺寸 N*N
using namespace std

//棋子类型 
typedef enum{
    CT_NONE, CT_WHITE, CT_BLACK
}CHESS_TYPE;

CHESS_TYPE board[N][N];            
CHESS_TYPE downType;          

//初始化棋盘 
void lnit()
{
    downType = CT_BLACK;          
    for(int i = 0; i < N; ++ i){
        for(int j = 0; j < N; ++ j){
            board[i][j] = CT_NONE;
        }
    }
} 

//判断棋子是否落在棋盘内 
bool IsInBoard(int x, int y)
{
        return x >= 0 && x < N && y >= 0 && y < N;
}

//定义一组方向向量 
const int dx[8] = {0, 0, 1, -1, 1, -1, -1, 1};
const int dy[8] = {1, -1, 0, 0, 1, -1, 1, -1};

//判断某一方是否胜利
bool IsWin(int x0, int y0)       
{
    int count[8] = {0};
    int x = x0, y = y0;

    for(int i = 0; i < 8; ++ i){
        int x = x0, y = y0;
        while(true){
            x += dx[i];
            y += dy[i];
            if(IsInBoard(x, y) && board[x][y] == board[x0][y0]){
            ++ count[i];
        }
        else{
            break;
        }
    }
}

for(int i = 0; i < 8; i += 2){
    if(count[i] + count[i + 1] >= 4){
        return true;
        } 
    }
    return false;
}

//打印棋盘 
void Print()
{
    cout << "  ";
    for(int i = 0; i < N; ++ i){
        cout << " " << (char)('A' + i ) ;   
    }
    cout << endl;
    for(int i = 0; i < N; ++ i){

    if(i >= 9){
        cout << i + 1; 
    }  
    else {
        cout << i + 1 << " ";         
    }

    for(int j = 0; j < N; ++ j){
        if(board[i][j] == CT_NONE){
            cout << "□";
        }
        if(board[i][j] == CT_WHITE){
            cout << "●";            
        }
        if(board[i][j] == CT_BLACK){
            cout << "○";           
        }
    }
    cout << endl;
} 
}

//游戏过程 
void Process()
{
    Print(); 
    char a, b;
    int k = 0;
    for(int i = 0; i < N*N; ++ i){
        cout << "请根据图示坐标类型,依次输入棋子的横纵坐标" << endl;
        cin >> a >> b;
        a -= '1'; 
        b -= 'A';

        if(!IsInBoard(a, b) || board[a][b] != CT_NONE){
            cout << "ERROR" << endl;
            continue;
        }

        board[a][b] = downType;
        system("cls");
        Print();

        if(IsWin(a, b)){
            cout << (downType == CT_WHITE ? "白棋赢" : "黑棋赢") << endl; 
            k ++;
            break;
        }

        downType = (downType == CT_BLACK )? CT_WHITE : CT_BLACK;
}
    if(!k){
        cout << "平局" << endl;
    } 
}

int main()
{
    lnit();
    Process();
    return 0;
}


下面是这个程序的运行结果:

五子棋运行结果

首先,再输入棋子之前,程序会弹出一个空白的棋盘,注意,一定要根据棋盘周围所标注的横纵坐标来确定落子的位置。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值