OpenGL超级宝典(第7版)笔记14 前三章实例 下个五子棋 (下)
前言
上一篇我们把从数据到画面的过程说完了,这一篇我们说说如何获取输入,并且修改数据,判断输赢。
1 获取鼠标点击输入
我们之前在笔记2中的输入输出小节中谈到过对鼠标的位置获取,通过mouse_callback()函数来获取鼠标的位置信息,通过glfwSetCursorPosCallback();将当前窗口的鼠标位置回调函数设置为我们写的mouse_callback()。
具体如下
void mouse_callback(GLFWwindow* window, double xpos, double ypos) {
lastx=xpos;
lasty=ypos;
//存储鼠标位置信息到全局变量lastx、lasty
}
glfwSetCursorPosCallback(window, mouse_callback);
但是我们并不会获取鼠标的点击信息,这里我们将介绍mouse_button_callback()和glfwSetMouseButtonCallback()来获取鼠标的点击操作:
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods){
//...
return;
}
glfwSetMouseButtonCallback(window, mouse_button_callback);
鼠标按键回调函数会获取4个参数,分别是window表示当前窗口,button表示鼠标的按键信息,action表示当前是按下还是松开等状态信息,mods(不太清楚)。
我们现在来编写具体的内容,首先在我们点击发生后,回调函数会启用,我们要立即保存下当前的鼠标位置(用于判断点击的位置是在哪里,需要相应有哪些处理)。我们这里约定鼠标左键为下子,右键为切换棋子种类(白变黑,黑变白),中键为悔棋。具体代码如下(cout便于查找错误):
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods){
int whichkey=0;//左键为1右键为2中键为3
if (action == GLFW_PRESS)
switch (button){
case GLFW_MOUSE_BUTTON_LEFT:
kickx = lastx;
kicky = lasty;
whichkey=1;
std::cout << "left down" << std::endl;
std::cout << lastx << " " << lasty << std::endl;
break;
case GLFW_MOUSE_BUTTON_MIDDLE:
kickx = lastx;
kicky = lasty;
whichkey=3;
std::cout << "mid down" << std::endl;
std::cout << lastx << " " << lasty << std::endl;
break;
case GLFW_MOUSE_BUTTON_RIGHT:
kickx = lastx;
kicky = lasty;
whichkey=2;
std::cout << "right down" << std::endl;
std::cout << lastx << " " << lasty << std::endl;
if (nowkind == 1) {
nowkind = 2;
}
else {
nowkind = 1;
}
break;
default:
return;
}
//上方为part1
//...
return;
}
在part1中我们把各种信息写到了全局变量nowkind、kickx、kicky、whichkey中,他们分别记录了当前棋子种类、点击时的xy值、点击的是鼠标上的哪个键。下面我们要根据不同的按键,进行分类处理。
左键按下后:
判断位置是否在棋盘中,判断点击位置对应的棋盘二维数组的下标,判断改棋盘位置是否有棋子,下子后在chessboard和chess_draw_list中添加对应的数据,并且让计数器chess_number加一,下子后判断是否五子连珠(并把结果写入全局变量iswin中,指示后面有人赢得对局了)。
中间按下后:
按照chess_draw_list的指示位置,把chessboard的棋子删除,并且chess_draw_list中抹去最后一个棋子,让计数器chess_number减一。
(cout便于查找错误)
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods){
//上方的part1省略
switch(whichkey){
case 1:
if (kickx > 150 && kicky > 150 && kickx < 850 && kicky < 850) {
arrayx = (kickx - 170) / 38.75f + 1.0f;
arrayy = (kicky - 170) / 38.75f + 1.0f;
std::cout << "arrayx=" << arrayx <<