c++ - 使用事件处理程序

标签 c++ c events mouse bgi

有没有一种方法可以在 c/c++ 中使用鼠标作为事件处理程序,我正在制作蛇和梯子游戏(著名的棋盘游戏),并尝试使用基本的 borland c++ 编译器和名为 graphics 的头文件来制作它。 h,这是非常基本的并提供 640 X 480 res 的输出,所以我想知道是否有可能使用鼠标作为事件处理程序(我对此没有经验)来控制板上的 palyer 硬币。

最佳答案

我不确定您使用的是哪个版本的 graphics.h,但是有函数 getmouseygetmouseyclearmouseclick获取鼠标点击See this获取一些可能对您有用的文档。

看来您可以使用 registermousehandler 和回调函数来执行某种级别的基于事件的编程。这是我发送给您的文档中的示例。

// The click_handler will be called whenever the left mouse button is
// clicked. It checks copies the x,y coordinates of the click to
// see if the click was on a red pixel. If so, then the boolean
// variable red_clicked is set to true. Note that in general
// all handlers should be quick. If they need to do more than a little
// work, they should set a variable that will trigger the work going,
// and then return.
bool red_clicked = false;
void click_handler(int x, int y)
{
    if (getpixel(x,y) == RED)
    red_clicked = true;
}

// Call this function to draw an isosoles triangle with the given base and
// height. The triangle will be drawn just above the botton of the screen.
void triangle(int base, int height)
{
    int maxx = getmaxx( );
    int maxy = getmaxy( );
    line(maxx/2 - base/2, maxy - 10, maxx/2 + base/2, maxy - 10);
    line(maxx/2 - base/2, maxy - 10, maxx/2, maxy - 10 - height);
    line(maxx/2 + base/2, maxy - 10, maxx/2, maxy - 10 - height);
}
void main(void)
{
    int maxx, maxy; // Maximum x and y pixel coordinates
    int divisor; // Divisor for the length of a triangle side
    // Put the machine into graphics mode and get the maximum coordinates:
    initwindow(450, 300);
    maxx = getmaxx( );
    maxy = getmaxy( );
    // Register the function that handles a left mouse click
    registermousehandler(WM_LBUTTONDOWN, click_handler);
    // Draw a white circle with red inside and a radius of 50 pixels:
    setfillstyle(SOLID_FILL, RED);
    setcolor(WHITE);
    fillellipse(maxx/2, maxy/2, 50, 50);
    // Print a message and wait for a red pixel to be double clicked:
    settextstyle(DEFAULT_FONT, HORIZ_DIR, 2);
    outtextxy(20, 20, "Left click in RED to end.");
    setcolor(BLUE);
    red_clicked = false;
    divisor = 2;
    while (!red_clicked)
    {
        triangle(maxx/divisor, maxy/divisor);
        delay(500);
        divisor++;
    }
    cout << "The mouse was clicked at: ";
    cout << "x=" << mousex( );
    cout << " y=" << mousey( ) << endl;
    // Switch back to text mode:
    closegraph( );
}

关于c++ - 使用事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/492366/

相关文章:

python - 在线程之间使用 pydispatch

C++引用类型必须初始化

c - C 语言中的循环切换菜单

C 队列字符数组

javascript - 如何选择 href ="#xyz"的所有 a 标签

events - Laravel 监听器监听多个事件

c++ - 除非指定了较低的字体质量,否则 ExtTextOut 会因非常长的字符串而失败

c++ - 如何传递二维结构数组给函数?

c++ - 填充矩形类型的 PictureBox,C++ WINAPI

c - 如何找到正确的 mtrace 脚本来解释 mtrace 输出?