1 /*
2 SPDX-FileCopyrightText: 2008-2010 Stefan Majewsky <majewsky@gmx.net>
3
4 SPDX-License-Identifier: GPL-2.0-or-later
5 */
6
7 #include "diamond.h"
8
9 #include <QGraphicsSceneMouseEvent>
10
colorKey(KDiamond::Color color)11 QString colorKey(KDiamond::Color color)
12 {
13 QString colors[] = {
14 QLatin1String("kdiamond-selection"),
15 QLatin1String("kdiamond-red"),
16 QLatin1String("kdiamond-green"),
17 QLatin1String("kdiamond-blue"),
18 QLatin1String("kdiamond-yellow"),
19 QLatin1String("kdiamond-white"),
20 QLatin1String("kdiamond-black"),
21 QLatin1String("kdiamond-orange")
22 };
23 return colors[(color < 0 || color >= KDiamond::ColorsCount) ? 0 : color];
24 }
25
Diamond(KDiamond::Color color,KGameRenderer * renderer,QGraphicsItem * parent)26 Diamond::Diamond(KDiamond::Color color, KGameRenderer *renderer, QGraphicsItem *parent)
27 : KGameRenderedObjectItem(renderer, colorKey(color), parent)
28 , m_color(color)
29 {
30 //selection markers do not react to mouse events; they should also appear behind diamonds
31 if (color == KDiamond::Selection) {
32 setAcceptedMouseButtons({});
33 setZValue(-1);
34 } else {
35 setAcceptedMouseButtons(Qt::LeftButton);
36 }
37 }
38
color() const39 KDiamond::Color Diamond::color() const
40 {
41 return m_color;
42 }
43
mousePressEvent(QGraphicsSceneMouseEvent * event)44 void Diamond::mousePressEvent(QGraphicsSceneMouseEvent *event)
45 {
46 m_mouseDown = true;
47 m_mouseDownPos = event->pos();
48 }
49
mouseMoveEvent(QGraphicsSceneMouseEvent * event)50 void Diamond::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
51 {
52 if (m_mouseDown) {
53 //check if diamond was dragged onto another one
54 const QPointF pos = event->pos();
55 const qreal dx = pos.x() - m_mouseDownPos.x(), dy = pos.y() - m_mouseDownPos.y();
56 const QSizeF diamondSize = boundingRect().size();
57 static const qreal draggingFuzziness = 2.0 / 3.0;
58 if (qAbs(dx) > qAbs(dy)) {
59 if (qAbs(dx) >= diamondSize.width() * draggingFuzziness) {
60 Q_EMIT dragged(QPoint(dx < 0 ? -1 : 1, 0));
61 m_mouseDown = false; //mouse action has been handled
62 }
63 } else {
64 if (qAbs(dy) >= diamondSize.height() * draggingFuzziness) {
65 Q_EMIT dragged(QPoint(0, dy < 0 ? -1 : 1));
66 m_mouseDown = false;
67 }
68 }
69 }
70 }
71
mouseReleaseEvent(QGraphicsSceneMouseEvent * event)72 void Diamond::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
73 {
74 if (m_mouseDown && boundingRect().contains(event->pos())) {
75 Q_EMIT clicked();
76 m_mouseDown = false;
77 }
78 }
79
80