C++五子棋(三)——判断鼠标有效点击

2021-07-07  本文已影响0人  无聊的CairBin

分析

在鼠标左键点击时,我们不能让新棋子在已有棋子的位置落下,同时我们还要让棋子在规定位置落下——棋盘线的交点处。

功能实现

创建数据类型

#include "chessData.h"
const float BLOCKSIZE = 67.4;
const int BLOCK_GRAD_SIZE = 13;
const int POS_OFFSET = BLOCKSIZE * 0.4;
struct ChessData{
  //储存当前游戏棋盘的情况,空白为0,黑棋为1,白棋为-1
  int chessMap[BLOCK_GRAD_SIZE][BLOCK_GRAD_SIZE];
  //储存各点的评分情况,用于之后的AI走棋
  int scoreMap[BLOCK_GRAD_SIZE][BLOCK_GRAD_SIZE];
  
  bool playFlag;    //表示下棋放,true黑棋,false白棋(AI)
  
};
ChessData game;

初始化数据类型

void initChessData(ChessData*);
void initChessData(ChessData *data){
  if(!data) return;
  memset(data->chessMap,0,sizeof(data->chessMap));
  memset(data->scoreMap,0,sizeof(data->scoreMap));
  data->playFlag = true;
  
}

判断有效点击

算法原理

原理

实现

int clickPosRow, clickPosCol;   //用于储存点击位置
//有效点击返回true,无效点击返回false
//MOUSEMSG为鼠标信息类型
bool clickBoard(MOUSEMSG msg){
  
  //(鼠标点击坐标 - 边界长度)/ 格宽 = 行(列)数
  
  //计算列数并取整
  int col = (msg.x - MARGIN_X) / BLOCKSIZE;
  //计算行数取整
  int row = (msg.y - MARGIN_Y) / BLOCKSIZE;
  
  //计算棋子正确坐标,即格子左上角棋子应在的棋盘格线交点处坐标
  int leftTopPosX = MARGIN_X + BLOCKSIZE * col;
  int leftTopPosY = MARGIN_Y + BLOCKSIZE * row;
  
  
}
#include <math.h>
int len;    //用于计算两点见的距离(根据中学所学两点间距离公式)
int selectPos = false;  //作为返回值

do{
  //左上角
  len = sqrt((msg.x - leftTopPosX)*(msg.x - leftTopPosX) + (y - leftTopPosY)*(msg.y - leftTopPosY));
  if(len < POS_OFFSET){
    clickPosRow = row;
    clickPosCol = col;
    if ( game.chessMap[clickPosRow][clickPosCol] == 0 ){
      selectPos = true;
    }
    break;
  }
  
  //右上角
  len = sqrt((msg.x - leftTopPosX - BLOCKSIZE)*(msg.x - leftTopPosX - BLOCKSIZE) + (y - leftTopPosY)*(msg.y - leftTopPosY));
  if(len < POS_OFFSET){
    clickPosRow = row;
    clickPosCol = col + 1;
    if ( game.chessMap[clickPosRow][clickPosCol] == 0 ){
      selectPos = true;
    }
    break;
  }
  
  //左下角
  len = sqrt((msg.x - leftTopPosX)*(msg.x - leftTopPosX) + (y - leftTopPosY - BLOCKSIZE)*(msg.y - leftTopPosY - BLOCKSIZE));
  if(len < POS_OFFSET){
    clickPosRow = row + 1;
    clickPosCol = col;
    if ( game.chessMap[clickPosRow][clickPosCol] == 0 ){
      selectPos = true;
    }
    break;
  }
  
  //右下角
  
  len = sqrt((msg.x - leftTopPosX - BLOCKSIZE)*(msg.x - leftTopPosX - BLOCKSIZE) + (y - leftTopPosY - BLOCKSIZE)*(msg.y - leftTopPosY - BLOCKSIZE));
  if(len < POS_OFFSET){
    clickPosRow = row + 1;
    clickPosCol = col + 1;
    if ( game.chessMap[clickPosRow][clickPosCol] == 0 ){
      selectPos = true;
    }
    break;
  }
  
  
}while(0);

return selectPos;

更新底层数据

void updateGameMap(ChessData* data, int row, int col);
void updateGameMap(ChessData* data, int row, int col){
  if(!data) return;
  
  if(data->playFlag){
    data->chessMap[row][col] = 1;
  }else{
    data->chessMap[row][col] = -1;
  }
  
  data->playFlag = !data->playFlag; //换下棋方
  
}
//玩家走棋
void manGo(){
  chessDown(clickPosRow,clickPosCol,CHESS_BLACK);
  updateGameMap(&game, clickPosRow, clickPosCol);
  
}
上一篇 下一篇

猜你喜欢

热点阅读