1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
|
// Osman Zakir
// 8 / 2 / 2017
// Bjarne Stroustrup: Programming: Principles and Practice Using C++ 2nd Edition
// Chapter 16 Exercise 3
// chapter16ex3.cpp
// Exercise Specifications:
/**
* Place an Image on top of a Button ; move both when the button is pushed.
* Use this random number generator from std_lib_facilities.h to pick a
* new location for the “image button”:
* #include<random>
*
* inline int rand_int(int min, int max)
* {
* static default_random_engine ran;
* return uniform_int_distribution<>{min,max}(ran);
* }
* It returns a random int in the range [ min , max ).
*/
#include "../../GUI.h"
#include "../../Graph.h"
#include "../../Window.h"
#include <string>
#include <iostream>
#include <stdexcept>
namespace Graph_lib
{
struct Image_button_window : Window
{
Image_button_window(Point xy, int w, int h, const std::string &title, const std::string &image_url, int button_w, int button_h,
Point xy2);
bool wait_for_button();
void move_button();
private:
Image m_image;
Button m_image_button;
bool m_button_pushed;
static void cb_button(Address, Address addr) { reference_to<Image_button_window>(addr).button_pressed(); }
void button_pressed();
};
}
int main()
{
using namespace Graph_lib;
using namespace std;
constexpr int win_width = 600;
constexpr int win_height = 400;
try
{
Image_button_window win{ Point{100, 100}, win_width, win_height, "Moving Image Button",
"Forum_Avatar.jpg", 180, 200, Point{(win_width / 2) - 100, (win_height / 2) - 100} };
win.move_button();
return gui_main();
}
catch (const runtime_error &e)
{
cerr << "Runtime_error: " << e.what() << '\n';
return 1;
}
catch (const exception &e)
{
cerr << "Exception: " << e.what() << '\n';
return 2;
}
catch (...)
{
cerr << "Some exception occurred\n";
return 3;
}
}
Graph_lib::Image_button_window::Image_button_window(Point xy, int w, int h, const std::string &title, const std::string &image_url,
int button_w, int button_h, Point xy2)
:Window{ xy, w, h, title },
m_image{ xy2, image_url },
m_image_button{ xy2, button_w, button_h, "", cb_button },
m_button_pushed{ false }
{
attach(m_image);
attach(m_image_button);
}
void Graph_lib::Image_button_window::button_pressed()
{
m_button_pushed = true;
}
void Graph_lib::Image_button_window::move_button()
{
while (wait_for_button())
{
int x = rand_int(0, x_max());
int y = rand_int(0, y_max());
m_image.move(x, y);
m_image_button.move(x, y);
}
}
bool Graph_lib::Image_button_window::wait_for_button()
{
show();
m_button_pushed = false;
#if 1
while (!m_button_pushed)
{
Fl::wait();
}
Fl::redraw();
#else
Fl::run();
#endif
return m_button_pushed;
}
|