黑白棋Chess

黑白棋Chess

1.chess.h

#ifndef CHESS_H
#define CHESS_H

#include <QWidget>
#include <QPainter>
#include <QResizeEvent>
#include <QMouseEvent>
#define GRIDCOUNT  10

class Chess : public QWidget
{
    Q_OBJECT
public:
    Chess(QWidget *parent = nullptr);
    ~Chess();
    //外部调用方法,改变内部背景图
    void setBgImage(const QString fileName);
    void setLineParams(const QColor color,const Qt::PenStyle style, const int width);
    //棋子类型
    enum ChessType{Empty=0, White, Black};
    //改变棋盘显示的值
    void setChessStatus(void *p);


protected:
    void paintEvent(QPaintEvent *event);
    void resizeEvent(QResizeEvent *event);
    void mousePressEvent(QMouseEvent *event);

private:
    QString bgFilename;
    QColor lineColor;
    Qt::PenStyle lineStyle;
    int lineWidth;
    //每隔格子的宽高,划线开始xy位置
    int gridWidth, gridHeight, startX, startY;

    void Init();
    void InitChess();
    //保存棋子数据容器
    int chessData[8][8];

signals:
    // 发送click的坐标index: x,y
    void SignalSendChessData(int i, int j);

};
#endif // CHESS_H

2.chess.cpp

#include "chess.h"
#include <QDebug>

Chess::Chess(QWidget *parent)
    : QWidget(parent)
{
    Init();
    //InitChess();
}
Chess::~Chess()
{
}

//----------------events--------------------
//绘图
void Chess::paintEvent(QPaintEvent *event){
    QPainter painter(this);
    //1.画大背景
    QRect rect(0,0, this->width(),this->height());
    QPixmap pix(bgFilename);
    //pix.load("../myChess/image/background.jpg");
    painter.drawPixmap(rect, pix);
    //2.画线
    QPen pen1;
    pen1.setColor(lineColor);
    pen1.setStyle(lineStyle);
    pen1.setWidth(lineWidth);
    painter.setPen(pen1);

    for(int i=0; i<=8; i++) { // draw 9 line.
        //x:水平线条
        painter.drawLine(startX, startY+gridHeight*i,
                         9*gridWidth, startY+gridHeight*i);
        //y:垂直线条
        painter.drawLine(startX+gridWidth*i, startY,
                         startX+gridWidth*i, 9*gridHeight);
    }
    //3.画棋子
    QString chessFileName;
    for(int i=0; i<8; i++) {
        for(int j=0; j<8; j++) {
            if(chessData[i][j] == White) {
                //chessFileName ="../myChess/image/white.jpg";
                chessFileName =":/Images/white.png";
            } else if(chessData[i][j] == Black) {
                chessFileName =":/Images/black.png";
            } else {
                chessFileName.clear();
                continue;
            }
            painter.drawPixmap(startX + i*gridWidth, startY + j*gridHeight,
                               gridWidth, gridHeight, QPixmap(chessFileName));
        }
    }

}

//窗体改变的回调
void Chess::resizeEvent(QResizeEvent *event){
    gridWidth = event->size().width() / GRIDCOUNT;
    gridHeight = event->size().height() / GRIDCOUNT;
    startX = gridWidth;
    startY = gridHeight;
    //qDebug() <<"x:"<< startX <<" y:" << startY << endl;
}
void Chess::mousePressEvent(QMouseEvent *e){
    int x = e->x();
    int y = e->y();
    // 判断x, y是否在有效的范围内
    if(x >= startX && x <= (startX + 8*gridWidth)) {
        if(y >= startY && y <= (startY+8*gridHeight)) {
            // 改变数组里面的值
            int i=0, j=0;
            i = (x-startX)/gridWidth;
            j = (y-startY)/gridHeight;
//          qDebug() << i << j << endl;
//          chessData[i][j] = Black;
//          update();
            SignalSendChessData(i, j);
        }
    }
}

//----------------events end--------------------


//----------------functions --------------------
//private methods
void Chess::Init(){
    bgFilename.clear();
    bgFilename = "../myChess/image/background.jpg";

    lineColor = Qt::red; // default values.
    lineStyle = Qt::SolidLine;
    lineWidth = 3;
}

void Chess:: InitChess(){
    // init
//    memset(chessData, 0, sizeof(int)*64); //set default value
    for(int i=0;i<8;i++){
        for(int j=0;j<8;j++) {
            chessData[i][j] = Empty;
        }
    }
//    chessData[3][4] = White; //default 4 chess.
//    chessData[4][3] = White;
//    chessData[4][4] = Black;
//    chessData[3][3] = Black;
}


//public methods
void Chess::setBgImage(const QString filename) {
    this->bgFilename = filename;
    update();
}
void Chess::setLineParams(const QColor color,
                       const Qt::PenStyle style,
                       const int width){
    this->lineColor = color;
    this->lineStyle = style;
    this->lineWidth = width;
    update();
}
void Chess::setChessStatus(void *p) {
    memcpy(chessData, p, sizeof(int)*8*8);
    this->update();
}

//----------------functions end--------------------

//----------------slots --------------------

//----------------slots end--------------------

3.chessform.h

#ifndef CHESSFORM_H
#define CHESSFORM_H

#include <QWidget>
#include "chess.h"
#include <QPainter>

namespace Ui {
class ChessForm;
}

class ChessForm : public QWidget
{
    Q_OBJECT

public:
    explicit ChessForm(QWidget *parent = nullptr);
    ~ChessForm();
protected:
    void paintEvent(QPaintEvent *event);

private slots:
    void on_btn_pvp_clicked();
    //处理棋盘发送过来的信号
    void doProcessChessData(int i,int j);


    void on_btn_pvc_clicked();

private:
    enum PKType{PVP, PVC, NVN};
    PKType currentPK;

    Ui::ChessForm *ui;
    Chess *myChess;
    Chess::ChessType currentRole;//当前谁在下子
    int formChessData[8][8];

    void Init();
    //黑白棋吃子规则
    int judgeRule(int x, int y, void *chess,
                  Chess::ChessType currentRole, bool eatChess);
    void RoleInit(const QString whiteFilename, const QString blackFilename);
    void setRole(Chess::ChessType currentRole); //设置谁先谁后 下棋
    void setChessInit(); // 对棋盘初始化
    void RoleChange(); //角色切换
    void ChessShow();
    void RebootRole(Chess::ChessType role); //机器下子
};

#endif // CHESSFORM_H

4.chessform.cpp

#include "chessform.h"
#include "ui_chessform.h"
#include <QDebug>

ChessForm::ChessForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ChessForm)
{
    ui->setupUi(this);
    Init();
}

ChessForm::~ChessForm()
{
    delete ui;
}

//--------Functions----------------------
void ChessForm::Init(){
    QStringList array;
    array.append("白子先");
    array.append("黑子先");
    ui->cbox_item->addItems(array);
    RoleInit(":/Images/white.png", ":/Images/black.png");
    currentRole = Chess::Empty;

    //申请棋盘类的空间,显示到当前容器中
    myChess = new Chess();
    connect(myChess, SIGNAL(SignalSendChessData(int,int)),
            this, SLOT(doProcessChessData(int,int)));


    ui->gridLayout->addWidget(myChess);

}
void ChessForm::RoleInit(const QString whiteFilename, const QString blackFilename)
{
    ui->lbl1->setPixmap(QPixmap(whiteFilename)); // image url.
    ui->lbl1->setScaledContents(true);
    ui->lbl2->setPixmap(QPixmap(blackFilename));
    ui->lbl2->setScaledContents(true);
}
// who first
void ChessForm::setRole(Chess::ChessType role){
    currentRole = role;
    if (currentRole == Chess::Black){
        ui->lbl2->setVisible(true);
        ui->lbl1->setVisible(false);
    } else {
        ui->lbl1->setVisible(true);
        ui->lbl2->setVisible(false);
    }
    ui->lcdNumber1->display(0);
    ui->lcdNumber2->display(0);
}
void ChessForm::setChessInit(){
    for(int i=0;i<8;i++) {
        for(int j=0; j<8; j++){
            formChessData[i][j] = Chess::Empty;
        }
    }
    formChessData[3][4] = Chess::White; //default 4 chess.
    formChessData[4][3] = Chess::White;
    formChessData[4][4] = Chess::Black;
    formChessData[3][3] = Chess::Black;
    myChess->setChessStatus(formChessData);

    ui->lcdNumber1->display(2);
    ui->lcdNumber2->display(2);
}
void ChessForm::RoleChange(){
    if(currentRole == Chess::White) {
        currentRole = Chess::Black;
    } else{
        currentRole = Chess::White;
    }
    if (currentRole == Chess::Black){
        ui->lbl2->setVisible(true);
        ui->lbl1->setVisible(false);
    } else {
        ui->lbl1->setVisible(true);
        ui->lbl2->setVisible(false);
    }
}
void ChessForm::ChessShow(){
    int blackCount =0, whiteCount =0;
    for(int i=0; i<8; i++){
        for(int j=0; j<8; j++){
            if(formChessData[i][j] == Chess::White){
                whiteCount++;
            }else if(formChessData[i][j] == Chess::Black) {
                blackCount++;
            }
        }
    }
    ui->lcdNumber1->display(whiteCount);
    ui->lcdNumber2->display(blackCount);
}
//机器下子
void ChessForm::RebootRole(Chess::ChessType role) {
    int flag = 0; //遍历,看能否下子
    int ret, oldret=-1;
    int c_i, c_j;
    for(int i=0; i<8; i++){
        for(int j=0; j<8; j++){
            //看能否下子
            if(formChessData[i][j] == Chess::Empty) {
                ret = judgeRule(i,j,formChessData,role,false);
                if(ret > 0){
                    flag ++;
                    c_i = i, c_j=j;
                    oldret = ret;
                }
            }
        }
    }

    if(flag){ //能下子
        judgeRule(c_i, c_j, formChessData,role,true);
        myChess->setChessStatus(formChessData); //update UI.
        RoleChange();
    }else {
        RoleChange();
    }
}


/**
 * @brief  黑白棋吃子规则
 * @param x,y: 棋盘数组的坐标位置
 * @param chess 棋子的状态
 * @param currentRole:Chess类中的枚举变量(Empty,Black,White)
 * @param eatChess:true代表吃子,false只是判断有子可吃,默认为true
 * @return 能吃子的个数。
 */
int ChessForm::judgeRule(int x, int y, void *chess,
                         Chess::ChessType currentRole, bool eatChess){
    //黑白棋落子规则
    //除非至少翻转了对手的一个棋子,否则就不能落子。如果一方没有合法棋步,也就是说不管他下到哪里,
    //都不能至少翻转对手的一个棋子,那他这一轮只能弃权,而由他的对手继续落子直到他有合法棋步可下。
    //棋盘的8个方向
    int dir[8][2]={{1,0},{1,-1},{0,-1},{-1,-1},
                   {-1,0},{-1,1},{0,1},{1,1}};
    //临时保存棋盘数组坐标位置
    int temp_x=x, temp_y=y;
    int i=0, eatNum=0; //初始化数据
    typedef int (*p)[8]; //自定义类型
    p chessFlag = p(chess); //类型转换

    if(chessFlag[temp_x][temp_y] != Chess::Empty) //如果次方个内已有棋子,返回
        return 0;

    //棋盘的八个方向
    for(i=0;i<8;i++)
    {
        temp_x +=dir[i][0];
        temp_y +=dir[i][1];      //准备判断相邻的棋子

        //如果没有出界,且相邻棋子是对方棋子,才有吃子的可能
        if(temp_x<8 && temp_x>=0 && temp_y<8 && temp_y>=0
                &&(chessFlag[temp_x][temp_y] != currentRole)
                && (chessFlag[temp_x][temp_y] != Chess::Empty))
        {
            temp_x +=dir[i][0];
            temp_y +=dir[i][1];   //判断下一个,向前走一步
            while(temp_x <8 && temp_x >=0 && temp_y<8 && temp_y >=0)
            {
                if(chessFlag[temp_x][temp_y] == Chess::Empty) //遇到空位跳出
                    break;
                if(chessFlag[temp_x][temp_y] == currentRole) //找到自己的棋子,代表可以吃子
                {
                    if(eatChess == true) //确定吃子
                    {
                        chessFlag[x][y]=currentRole;
                        temp_x -= dir[i][0];
                        temp_y -= dir[i][1]; //后退一步
                        while(temp_x != x || temp_y != y)  //只要没有回到开始位置就执行
                        {
                            chessFlag[temp_x][temp_y] = currentRole;  //标志为自己的棋子
                            temp_x -= dir[i][0];   //继续后退一步
                            temp_y -= dir[i][1];
                            eatNum++;  //累计
                        }
                    }
                    else //不吃子,只是判断这个位置能不能吃子
                    {
                        temp_x -= dir[i][0];
                        temp_y -= dir[i][1];  //后退一步
                        while(temp_x != x || temp_y != y)  //只计算可以吃子的个数
                        {
                            temp_x -= dir[i][0];
                            temp_y -= dir[i][1]; //继续后退一步
                            eatNum++;
                        }
                    }
                    break; // 跳出循环
                } //没有找到自己的棋子,就向前走一步
                temp_x += dir[i][0];
                temp_y += dir[i][1]; //向前走一步
            }
        }
        //如果这个方向不能吃子,就换一个方向
        temp_x =x;
        temp_y =y;
    }
    return eatNum; // 返回能吃子的个数。
}

//--------Functions end------------------

//--------Events----------------------
void ChessForm::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPixmap(this->rect(), QPixmap(":/Images/bg.png"));


}



//--------Events----------------------



//--------Slots----------------------
//人人对战
void ChessForm::on_btn_pvp_clicked()
{   currentPK = PVP;
    //界面初始化,棋盘初始化
    if(ui->cbox_item->currentIndex() ==0) {//white first.
        setRole(Chess::White);
    } else {
        setRole(Chess::Black);
    }
    setChessInit();
}
//人机对战
void ChessForm::on_btn_pvc_clicked()
{
    currentPK = PVC;
    if(ui->cbox_item->currentIndex() ==0) {//white first.
        setRole(Chess::White);
    } else {
        setRole(Chess::Black);
    }
    setChessInit();
}

void ChessForm::doProcessChessData(int i, int j)
{
    qDebug() <<"i:" <<i << " j:" << j << endl;
    //判断能否瞎子,x>0能
    int ret = judgeRule(i,j, formChessData, currentRole,true);
    if(ret ){
        //把数据传送给棋盘类,用于更新UI
        myChess->setChessStatus(formChessData);
        if(currentPK == PVP){
            RoleChange(); // 角色切换
            ChessShow(); // 数据统计
        }
        else if(currentPK == PVC) {
            //机器下子
             RoleChange();
             RebootRole(currentRole);
             ChessShow(); // 数据统计
        }
    }
}

//--------Slots----------------------

main.cpp

#include "chessform.h"
#include <QApplication>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    ChessForm w;
    w.show();
    return a.exec();
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容