Reputation: 1069
I want to print out the coordinates of my mouse in the graphical window, and when the user clicks it, there should appear a message "clicked". But the problem is when the user does click it, instead of 1 message, I get around 5-10 messages. I understand it's probably because of how fast I release the button. Is there a way to print just one time?
#include <allegro.h>
#include <iostream>
int main(){
allegro_init();
install_keyboard();
install_mouse();
set_color_depth(32);
set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0);
BITMAP *pic = load_bitmap("mouse.bmp",NULL);
BITMAP *buffer = create_bitmap(640,480);
int x = 0, y = 0;
while(!key[KEY_ESC]){
blit(buffer, screen, 0,0,0,0, buffer->w,buffer->h);
draw_sprite(buffer, pic, mouse_x, mouse_y);
blit(buffer, screen, 0,0,0,0, buffer->w, buffer->h);
clear_bitmap(buffer);
if(mouse_x!=x && mouse_y!=y){
std::cout<<mouse_x<<":"<<mouse_y<<std::endl;
}
if(mouse_b&1){
std::cout<<std::endl<<">>CLICKED<<"<<std::endl;
}
x=mouse_x, y=mouse_y;
}
destroy_bitmap(pic);
destroy_bitmap(buffer);
return 0;
}
END_OF_MAIN()
Upvotes: 1
Views: 2781
Reputation: 92
It is much easier to use allegro events. Here is how allegro wiki explains events.
The following code would accomplish your task.
if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
std::cout<<std::endl<<">>CLICKED<<"<<std::endl;
}
else if(ev.type == ALLEGRO_EVENT_MOUSE_AXES ||
ev.type == ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY) {
std::cout<<mouse_x<<":"<<mouse_y<<std::endl;
}
Upvotes: 0
Reputation: 31952
Does mouse_b
hold the state of the mouse? If so it could be outputing the messages once every frame for however long your mouse is down.
Similar to how you handle x
,y
store the previous state of the button and only send a message if the state changes, this should give you just 1 message.
Upvotes: 1