-
Notifications
You must be signed in to change notification settings - Fork 0
/
TwoClickOrDrag.h
72 lines (62 loc) · 1.69 KB
/
TwoClickOrDrag.h
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
/* Summary:
TwoClickOrDrag makes only valid moves, using either two click input
or a mousedrag, given mousedown/up events. It is assumed that you cannot move onto your own piece, but this can be changed easily
*/
/* Contract:
TCallBackHandler must implement:
bool ownPiece(std::pair<int,int> mouseTile);
void select(std::pair<int,int> mouseTile);
void deselect();
bool validMove(std::pair<int,int> from, std::pair<int,int> to);
void makeMove(std::pair<int,int> from, std::pair<int,int> to);
*/
template<class TCallBackHandler>
class TwoClickOrDrag { // that is the question
public:
TwoClickOrDrag(TCallBackHandler & ch) : _callbackHandler(ch) {
}
bool HasSelection(){
return pieceSelected;
}
void MouseDown(std::pair<int,int> mouseTile){
if( _callbackHandler.ownPiece(mouseTile) ){
if( pieceSelected ){
_callbackHandler.deselect();
if( selection != mouseTile ){
_callbackHandler.select(mouseTile);
selection = mouseTile;
}
} else {
_callbackHandler.select(mouseTile);
selection = mouseTile;
}
} else if( pieceSelected ){
TryMove(selection, mouseTile);
pieceSelected = false;
_callbackHandler.deselect();
}
}
void MouseUp(std::pair<int,int> mouseTile){
if( pieceSelected ){
if( selection == mouseTile ){
return;
}
if( TryMove(selection, mouseTile) ){
_callbackHandler.deselect();
}
} else {
TryMove(selection, mouseTile);
}
}
private:
TCallBackHandler & _callbackHandler;
bool pieceSelected { false };
std::pair<int,int> selection;
bool TryMove(std::pair<int,int> from, std::pair<int,int> to){
if( _callbackHandler.validMove(from, to) ){
_callbackHandler.makeMove(from, to);
return true;
}
return false;
}
};