~neon/kolf/master

714 by Simon Huerlimann
Make EBN happy: Add best-guess copyright headers.
1
/*
2
    Copyright (C) 2002-2005, Jason Katz-Brown <jasonkb@mit.edu>
983 by Stefan Majewsky
Replace the Object classes by the new ItemFactory.
3
    Copyright 2010 Stefan Majewsky <majewsky@gmx.net>
714 by Simon Huerlimann
Make EBN happy: Add best-guess copyright headers.
4
5
    This program is free software; you can redistribute it and/or modify
6
    it under the terms of the GNU General Public License as published by
7
    the Free Software Foundation; either version 2 of the License, or
8
    (at your option) any later version.
9
10
    This program is distributed in the hope that it will be useful,
11
    but WITHOUT ANY WARRANTY; without even the implied warranty of
12
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
    GNU General Public License for more details.
14
15
    You should have received a copy of the GNU General Public License
16
    along with this program; if not, write to the Free Software
17
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18
*/
19
646 by Stephan Kulow
with MSVC there exists a symbol clash with Ellipse, so rename
20
#include "game.h"
983 by Stefan Majewsky
Replace the Object classes by the new ItemFactory.
21
#include "itemfactory.h"
980 by Stefan Majewsky
Clean include statements and forward declarations.
22
#include "kcomboboxdialog.h"
1066 by Stefan Majewsky
Fix cleanup of Windmill, and remove some obsolete includes.
23
#include "obstacles.h"
1018 by Stefan Majewsky
Adapt Kolf::Overlay and Kolf::Shape from playground/games/kolf2/base.
24
#include "shape.h"
980 by Stefan Majewsky
Clean include statements and forward declarations.
25
991 by Stefan Majewsky
First use of Tagaro::Scene, Board, and SpriteObjectItem in KolfGame class.
26
#include "tagaro/board.h"
27
980 by Stefan Majewsky
Clean include statements and forward declarations.
28
#include <QApplication>
1066 by Stefan Majewsky
Fix cleanup of Windmill, and remove some obsolete includes.
29
#include <QBoxLayout>
586 by Laurent Montel
#include <q...h> -> #include <Q...>
30
#include <QCheckBox>
980 by Stefan Majewsky
Clean include statements and forward declarations.
31
#include <QLabel>
32
#include <QMouseEvent>
589 by Laurent Montel
#include <q...h> -> #include <Q...>
33
#include <QTimer>
980 by Stefan Majewsky
Clean include statements and forward declarations.
34
#include <KFileDialog>
989 by Stefan Majewsky
Very very straight port of Kolf to KGameRenderer.
35
#include <KGameRenderer>
1123 by Stefan Majewsky
Add the KgTheme framework.
36
#include <KgTheme>
980 by Stefan Majewsky
Clean include statements and forward declarations.
37
#include <KLineEdit>
38
#include <KMessageBox>
39
#include <KNumInput>
40
#include <KRandom>
41
#include <KStandardDirs>
1023 by Stefan Majewsky
Execute Box2D steps aside the internal advance()s.
42
#include <Box2D/Dynamics/b2Body.h>
1112 by Stefan Majewsky
Fix some more Z-ordering bugs with static struts and b2ContactListener.
43
#include <Box2D/Dynamics/Contacts/b2Contact.h>
1075 by Stefan Majewsky
More Z-order fixing: Remove obsolete setZValue() calls and check strut level on collisions.
44
#include <Box2D/Dynamics/b2Fixture.h>
1021 by Stefan Majewsky
Create a Box2D world, and attach Box2D bodies to all CanvasItems.
45
#include <Box2D/Dynamics/b2World.h>
1075 by Stefan Majewsky
More Z-order fixing: Remove obsolete setZValue() calls and check strut level on collisions.
46
#include <Box2D/Dynamics/b2WorldCallbacks.h>
697 by Simon Huerlimann
Make EBN happy, include own header first.
47
699 by Matt Williams
EBN Fixes
48
inline QString makeGroup(int id, int hole, const QString &name, int x, int y)
54 by Jason Katz-Brown
get rid of makgroup stuff in objects (improved design), optimize floaters
49
{
50
	return QString("%1-%2@%3,%4|%5").arg(hole).arg(name).arg(x).arg(y).arg(id);
51
}
52
70 by Jason Katz-Brown
undo shot! :-)
53
inline QString makeStateGroup(int id, const QString &name)
54
{
55
	return QString("%1|%2").arg(name).arg(id);
56
}
57
1112 by Stefan Majewsky
Fix some more Z-ordering bugs with static struts and b2ContactListener.
58
class KolfContactListener : public b2ContactListener
1075 by Stefan Majewsky
More Z-order fixing: Remove obsolete setZValue() calls and check strut level on collisions.
59
{
60
	public:
1112 by Stefan Majewsky
Fix some more Z-ordering bugs with static struts and b2ContactListener.
61
		virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
1075 by Stefan Majewsky
More Z-order fixing: Remove obsolete setZValue() calls and check strut level on collisions.
62
		{
1112 by Stefan Majewsky
Fix some more Z-ordering bugs with static struts and b2ContactListener.
63
			Q_UNUSED(oldManifold)
64
			CanvasItem* citemA = static_cast<CanvasItem*>(contact->GetFixtureA()->GetBody()->GetUserData());
65
			CanvasItem* citemB = static_cast<CanvasItem*>(contact->GetFixtureB()->GetBody()->GetUserData());
1075 by Stefan Majewsky
More Z-order fixing: Remove obsolete setZValue() calls and check strut level on collisions.
66
			if (!CanvasItem::mayCollide(citemA, citemB))
1112 by Stefan Majewsky
Fix some more Z-ordering bugs with static struts and b2ContactListener.
67
				contact->SetEnabled(false);
1075 by Stefan Majewsky
More Z-order fixing: Remove obsolete setZValue() calls and check strut level on collisions.
68
		}
69
};
70
71
class KolfWorld : public b2World
72
{
73
	public:
74
		KolfWorld()
75
			: b2World(b2Vec2(0, 0), true) //parameters: no gravity, objects are allowed to sleep
76
		{
1112 by Stefan Majewsky
Fix some more Z-ordering bugs with static struts and b2ContactListener.
77
			SetContactListener(&m_listener);
1075 by Stefan Majewsky
More Z-order fixing: Remove obsolete setZValue() calls and check strut level on collisions.
78
		}
79
	private:
1112 by Stefan Majewsky
Fix some more Z-ordering bugs with static struts and b2ContactListener.
80
		KolfContactListener m_listener;
1075 by Stefan Majewsky
More Z-order fixing: Remove obsolete setZValue() calls and check strut level on collisions.
81
};
82
1123 by Stefan Majewsky
Add the KgTheme framework.
83
class KolfTheme : public KgTheme
84
{
85
	public:
86
		KolfTheme() : KgTheme("pics/default_theme.desktop")
87
		{
88
			setSvgPath(KStandardDirs::locate("appdata", "pics/default_theme.svgz"));
89
		}
90
};
91
991 by Stefan Majewsky
First use of Tagaro::Scene, Board, and SpriteObjectItem in KolfGame class.
92
class KolfRenderer : public KGameRenderer
93
{
94
	public:
1123 by Stefan Majewsky
Add the KgTheme framework.
95
		KolfRenderer() : KGameRenderer(new KolfTheme)
991 by Stefan Majewsky
First use of Tagaro::Scene, Board, and SpriteObjectItem in KolfGame class.
96
		{
97
			setStrategyEnabled(KGameRenderer::UseDiskCache, false);
98
			setStrategyEnabled(KGameRenderer::UseRenderingThreads, false);
99
		}
100
};
101
102
K_GLOBAL_STATIC(KolfRenderer, g_renderer)
1075 by Stefan Majewsky
More Z-order fixing: Remove obsolete setZValue() calls and check strut level on collisions.
103
K_GLOBAL_STATIC(KolfWorld, g_world)
989 by Stefan Majewsky
Very very straight port of Kolf to KGameRenderer.
104
105
KGameRenderer* Kolf::renderer()
106
{
107
	return g_renderer;
108
}
109
993 by Stefan Majewsky
Move all items on the scene into the Tagaro::Board.
110
Tagaro::Board* Kolf::findBoard(QGraphicsItem* item_)
111
{
112
	//This returns the toplevel board instance in which the given parent resides.
113
	return item_ ? dynamic_cast<Tagaro::Board*>(item_->topLevelItem()) : 0;
114
}
115
1021 by Stefan Majewsky
Create a Box2D world, and attach Box2D bodies to all CanvasItems.
116
b2World* Kolf::world()
117
{
118
	return g_world;
119
}
120
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
121
/////////////////////////
122
1021 by Stefan Majewsky
Create a Box2D world, and attach Box2D bodies to all CanvasItems.
123
Putter::Putter(QGraphicsItem* parent, b2World* world)
1052 by Stefan Majewsky
Kill now useless HintedLineItem class.
124
: QGraphicsLineItem(parent)
1021 by Stefan Majewsky
Create a Box2D world, and attach Box2D bodies to all CanvasItems.
125
, CanvasItem(world)
1 by Jason Katz-Brown
here's kolf, read the TODO
126
{
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
127
	setData(0, Rtti_Putter);
1112 by Stefan Majewsky
Fix some more Z-ordering bugs with static struts and b2ContactListener.
128
	setZBehavior(CanvasItem::FixedZValue, 10001);
72 by Jason Katz-Brown
undo if ball leaves course
129
	m_showGuideLine = true;
169 by Jason Katz-Brown
make putter use radians and not degrees
130
	oneDegree = M_PI / 180;
1007 by Stefan Majewsky
Remove obsolete scaling code in Putter, StrokeCircle and KolfGame.
131
	guideLineLength = 9;
132
	putterWidth = 11;
192 by Jason Katz-Brown
fix bad typo
133
	angle = 0;
72 by Jason Katz-Brown
undo if ball leaves course
134
1052 by Stefan Majewsky
Kill now useless HintedLineItem class.
135
	guideLine = new QGraphicsLineItem(this);
1007 by Stefan Majewsky
Remove obsolete scaling code in Putter, StrokeCircle and KolfGame.
136
	guideLine->setPen(QPen(Qt::white));
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
137
	guideLine->setZValue(998.8);
1 by Jason Katz-Brown
here's kolf, read the TODO
138
1007 by Stefan Majewsky
Remove obsolete scaling code in Putter, StrokeCircle and KolfGame.
139
	setPen(QPen(Qt::black, 4));
169 by Jason Katz-Brown
make putter use radians and not degrees
140
	maxAngle = 2 * M_PI;
3 by Jason Katz-Brown
*** empty log message ***
141
142
	hideInfo();
5 by Jason Katz-Brown
143
144
	// this also sets Z
169 by Jason Katz-Brown
make putter use radians and not degrees
145
	resetAngles();
3 by Jason Katz-Brown
*** empty log message ***
146
}
147
148
void Putter::showInfo()
149
{
72 by Jason Katz-Brown
undo if ball leaves course
150
	guideLine->setVisible(isVisible());
3 by Jason Katz-Brown
*** empty log message ***
151
}
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
152
3 by Jason Katz-Brown
*** empty log message ***
153
void Putter::hideInfo()
154
{
72 by Jason Katz-Brown
undo if ball leaves course
155
	guideLine->setVisible(m_showGuideLine? isVisible() : false);
1 by Jason Katz-Brown
here's kolf, read the TODO
156
}
157
158
void Putter::moveBy(double dx, double dy)
159
{
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
160
	QGraphicsLineItem::moveBy(dx, dy);
161
	guideLine->setPos(x(), y());
1068 by Stefan Majewsky
Refactor Z ordering.
162
	CanvasItem::moveBy(dx, dy);
1 by Jason Katz-Brown
here's kolf, read the TODO
163
}
164
72 by Jason Katz-Brown
undo if ball leaves course
165
void Putter::setShowGuideLine(bool yes)
166
{
167
	m_showGuideLine = yes;
168
	setVisible(isVisible());
169
}
170
1 by Jason Katz-Brown
here's kolf, read the TODO
171
void Putter::setVisible(bool yes)
172
{
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
173
	QGraphicsLineItem::setVisible(yes);
72 by Jason Katz-Brown
undo if ball leaves course
174
	guideLine->setVisible(m_showGuideLine? yes : false);
1 by Jason Katz-Brown
here's kolf, read the TODO
175
}
176
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
177
void Putter::setOrigin(double _x, double _y)
1 by Jason Katz-Brown
here's kolf, read the TODO
178
{
179
	setVisible(true);
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
180
	setPos(_x, _y);
1007 by Stefan Majewsky
Remove obsolete scaling code in Putter, StrokeCircle and KolfGame.
181
	guideLineLength = 9; //reset to default
1 by Jason Katz-Brown
here's kolf, read the TODO
182
	finishMe();
183
}
184
169 by Jason Katz-Brown
make putter use radians and not degrees
185
void Putter::setAngle(Ball *ball)
1 by Jason Katz-Brown
here's kolf, read the TODO
186
{
169 by Jason Katz-Brown
make putter use radians and not degrees
187
	angle = angleMap.contains(ball)? angleMap[ball] : 0;
1 by Jason Katz-Brown
here's kolf, read the TODO
188
	finishMe();
189
}
190
537 by Albert Astals Cid
only slope.cpp and newgame.cpp do not compile
191
void Putter::go(Direction d, Amount amount)
1 by Jason Katz-Brown
here's kolf, read the TODO
192
{
194 by Jason Katz-Brown
add ctrl-arrows for fine-tuned rotation
193
	double addition = (amount == Amount_More? 6 * oneDegree : amount == Amount_Less? .5 * oneDegree : 2 * oneDegree);
194
1 by Jason Katz-Brown
here's kolf, read the TODO
195
	switch (d)
196
	{
197
		case Forwards:
1007 by Stefan Majewsky
Remove obsolete scaling code in Putter, StrokeCircle and KolfGame.
198
			guideLineLength -= 1;
1 by Jason Katz-Brown
here's kolf, read the TODO
199
			guideLine->setVisible(false);
200
			break;
201
		case Backwards:
1007 by Stefan Majewsky
Remove obsolete scaling code in Putter, StrokeCircle and KolfGame.
202
			guideLineLength += 1;
1 by Jason Katz-Brown
here's kolf, read the TODO
203
			guideLine->setVisible(false);
204
			break;
205
		case D_Left:
194 by Jason Katz-Brown
add ctrl-arrows for fine-tuned rotation
206
			angle += addition;
169 by Jason Katz-Brown
make putter use radians and not degrees
207
			if (angle > maxAngle)
208
				angle -= maxAngle;
1 by Jason Katz-Brown
here's kolf, read the TODO
209
			break;
210
		case D_Right:
194 by Jason Katz-Brown
add ctrl-arrows for fine-tuned rotation
211
			angle -= addition;
169 by Jason Katz-Brown
make putter use radians and not degrees
212
			if (angle < 0)
213
				angle = maxAngle - fabs(angle);
1 by Jason Katz-Brown
here's kolf, read the TODO
214
			break;
215
	}
216
217
	finishMe();
218
}
219
220
void Putter::finishMe()
221
{
660 by Paul Broadbent
added resizing and started fixing edit mode
222
	midPoint.setX(cos(angle) * guideLineLength);
223
	midPoint.setY(-sin(angle) * guideLineLength);
1 by Jason Katz-Brown
here's kolf, read the TODO
224
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
225
	QPointF start;
226
	QPointF end;
1 by Jason Katz-Brown
here's kolf, read the TODO
227
228
	if (midPoint.y() || !midPoint.x())
229
	{
169 by Jason Katz-Brown
make putter use radians and not degrees
230
		start.setX(midPoint.x() - putterWidth * sin(angle));
231
		start.setY(midPoint.y() - putterWidth * cos(angle));
232
		end.setX(midPoint.x() + putterWidth * sin(angle));
233
		end.setY(midPoint.y() + putterWidth * cos(angle));
1 by Jason Katz-Brown
here's kolf, read the TODO
234
	}
235
	else
236
	{
237
		start.setX(midPoint.x());
238
		start.setY(midPoint.y() + putterWidth);
239
		end.setY(midPoint.y() - putterWidth);
240
		end.setX(midPoint.x());
241
	}
242
660 by Paul Broadbent
added resizing and started fixing edit mode
243
	guideLine->setLine(midPoint.x(), midPoint.y(), -cos(angle) * guideLineLength * 4, sin(angle) * guideLineLength * 4);
1 by Jason Katz-Brown
here's kolf, read the TODO
244
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
245
	setLine(start.x(), start.y(), end.x(), end.y());
1 by Jason Katz-Brown
here's kolf, read the TODO
246
}
247
248
/////////////////////////
249
250
HoleConfig::HoleConfig(HoleInfo *holeInfo, QWidget *parent)
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
251
: Config(parent)
1 by Jason Katz-Brown
here's kolf, read the TODO
252
{
253
	this->holeInfo = holeInfo;
254
571 by Dmitry Suzdalev
deprecated--
255
	QVBoxLayout *layout = new QVBoxLayout(this);
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
256
	layout->setMargin( marginHint() );
257
	layout->setSpacing( spacingHint() );
1 by Jason Katz-Brown
here's kolf, read the TODO
258
571 by Dmitry Suzdalev
deprecated--
259
	QHBoxLayout *hlayout = new QHBoxLayout;
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
260
	hlayout->setSpacing( spacingHint() );
261
	layout->addLayout( hlayout );
1 by Jason Katz-Brown
here's kolf, read the TODO
262
	hlayout->addWidget(new QLabel(i18n("Course name: "), this));
288 by Jason Katz-Brown
read untranslated entries in the editor so I don't always save my courses with Japanese names
263
	KLineEdit *nameEdit = new KLineEdit(holeInfo->untranslatedName(), this);
1 by Jason Katz-Brown
here's kolf, read the TODO
264
	hlayout->addWidget(nameEdit);
1107 by Laurent Montel
Normalize signals/slots
265
	connect(nameEdit, SIGNAL(textChanged(QString)), this, SLOT(nameChanged(QString)));
1 by Jason Katz-Brown
here's kolf, read the TODO
266
571 by Dmitry Suzdalev
deprecated--
267
	hlayout = new QHBoxLayout;
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
268
	hlayout->setSpacing( spacingHint() );
269
	layout->addLayout( hlayout );
1 by Jason Katz-Brown
here's kolf, read the TODO
270
	hlayout->addWidget(new QLabel(i18n("Course author: "), this));
271
	KLineEdit *authorEdit = new KLineEdit(holeInfo->author(), this);
272
	hlayout->addWidget(authorEdit);
1107 by Laurent Montel
Normalize signals/slots
273
	connect(authorEdit, SIGNAL(textChanged(QString)), this, SLOT(authorChanged(QString)));
1 by Jason Katz-Brown
here's kolf, read the TODO
274
275
	layout->addStretch();
276
571 by Dmitry Suzdalev
deprecated--
277
	hlayout = new QHBoxLayout;
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
278
	hlayout->setSpacing( spacingHint() );
279
	layout->addLayout( hlayout );
344 by Stephan Binner
CVS_SILENT Style guide text fix, use "cvslastchange" or X-WebCVS header to view
280
	hlayout->addWidget(new QLabel(i18n("Par:"), this));
936 by Andrius Å tikonas
Replace i18n() with ki18np() and QSpinBox with KIntSpinBox in order to enable plurals.
281
	KIntSpinBox *par = new KIntSpinBox(this);
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
282
	par->setRange( 1, 15 );
283
	par->setSingleStep( 1 );
1 by Jason Katz-Brown
here's kolf, read the TODO
284
	par->setValue(holeInfo->par());
285
	hlayout->addWidget(par);
286
	connect(par, SIGNAL(valueChanged(int)), this, SLOT(parChanged(int)));
30 by Jason Katz-Brown
elliptical slopes!! and other things!
287
	hlayout->addStretch();
1 by Jason Katz-Brown
here's kolf, read the TODO
288
335 by Stephan Binner
CVS_SILENT Style guide text fix, use "cvslastchange" or X-WebCVS header to view
289
	hlayout->addWidget(new QLabel(i18n("Maximum:"), this));
936 by Andrius Å tikonas
Replace i18n() with ki18np() and QSpinBox with KIntSpinBox in order to enable plurals.
290
	KIntSpinBox *maxstrokes = new KIntSpinBox(this);
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
291
	maxstrokes->setRange( holeInfo->lowestMaxStrokes(), 30 );
292
	maxstrokes->setSingleStep( 1 );
560 by Laurent Montel
Compile/link
293
	maxstrokes->setWhatsThis( i18n("Maximum number of strokes player can take on this hole."));
294
	maxstrokes->setToolTip( i18n("Maximum number of strokes"));
103 by Jason Katz-Brown
scoreboard par changing bugfix
295
	maxstrokes->setSpecialValueText(i18n("Unlimited"));
1 by Jason Katz-Brown
here's kolf, read the TODO
296
	maxstrokes->setValue(holeInfo->maxStrokes());
297
	hlayout->addWidget(maxstrokes);
298
	connect(maxstrokes, SIGNAL(valueChanged(int)), this, SLOT(maxStrokesChanged(int)));
30 by Jason Katz-Brown
elliptical slopes!! and other things!
299
300
	QCheckBox *check = new QCheckBox(i18n("Show border walls"), this);
301
	check->setChecked(holeInfo->borderWalls());
302
	layout->addWidget(check);
303
	connect(check, SIGNAL(toggled(bool)), this, SLOT(borderWallsChanged(bool)));
1 by Jason Katz-Brown
here's kolf, read the TODO
304
}
305
306
void HoleConfig::authorChanged(const QString &newauthor)
307
{
308
	holeInfo->setAuthor(newauthor);
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
309
	changed();
1 by Jason Katz-Brown
here's kolf, read the TODO
310
}
311
312
void HoleConfig::nameChanged(const QString &newname)
313
{
314
	holeInfo->setName(newname);
288 by Jason Katz-Brown
read untranslated entries in the editor so I don't always save my courses with Japanese names
315
	holeInfo->setUntranslatedName(newname);
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
316
	changed();
1 by Jason Katz-Brown
here's kolf, read the TODO
317
}
318
319
void HoleConfig::parChanged(int newpar)
320
{
321
	holeInfo->setPar(newpar);
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
322
	changed();
1 by Jason Katz-Brown
here's kolf, read the TODO
323
}
324
325
void HoleConfig::maxStrokesChanged(int newms)
326
{
327
	holeInfo->setMaxStrokes(newms);
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
328
	changed();
1 by Jason Katz-Brown
here's kolf, read the TODO
329
}
330
30 by Jason Katz-Brown
elliptical slopes!! and other things!
331
void HoleConfig::borderWallsChanged(bool yes)
332
{
333
	holeInfo->borderWallsChanged(yes);
334
	changed();
335
}
336
1 by Jason Katz-Brown
here's kolf, read the TODO
337
/////////////////////////
338
993 by Stefan Majewsky
Move all items on the scene into the Tagaro::Board.
339
StrokeCircle::StrokeCircle(QGraphicsItem *parent)
340
: QGraphicsItem(parent)
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
341
{
342
	dvalue = 0;
343
	dmax = 360;
344
	iwidth = 100;
345
	iheight = 100;
346
	ithickness = 8;
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
347
	setZValue(10000);
1007 by Stefan Majewsky
Remove obsolete scaling code in Putter, StrokeCircle and KolfGame.
348
1009 by Stefan Majewsky
Change signature of CanvasItem::setSize from (double, double) to (QSizeF).
349
	setSize(QSizeF(80, 80));
1007 by Stefan Majewsky
Remove obsolete scaling code in Putter, StrokeCircle and KolfGame.
350
	setThickness(8);
700 by Paul Broadbent
fixed the advanced putter and added advanced putter resize
351
}
352
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
353
void StrokeCircle::setValue(double v)
354
{
355
	dvalue = v;
356
	if (dvalue > dmax)
357
		dvalue = dmax;
700 by Paul Broadbent
fixed the advanced putter and added advanced putter resize
358
359
	update();
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
360
}
361
362
double StrokeCircle::value()
363
{
364
	return dvalue;
365
}
366
802 by Albert Astals Cid
overload the correct functions
367
bool StrokeCircle::collidesWithItem(const QGraphicsItem*, Qt::ItemSelectionMode) const { return false; }
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
368
369
QRectF StrokeCircle::boundingRect() const { return QRectF(x(), y(), iwidth, iheight); }
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
370
371
void StrokeCircle::setMaxValue(double m)
372
{
373
	dmax = m;
374
	if (dvalue > dmax)
375
		dvalue = dmax;
376
}
1009 by Stefan Majewsky
Change signature of CanvasItem::setSize from (double, double) to (QSizeF).
377
void StrokeCircle::setSize(const QSizeF& size)
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
378
{
1009 by Stefan Majewsky
Change signature of CanvasItem::setSize from (double, double) to (QSizeF).
379
	if (size.width() > 0)
380
		iwidth = size.width();
381
	if (size.height() > 0)
382
		iheight = size.height();
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
383
}
700 by Paul Broadbent
fixed the advanced putter and added advanced putter resize
384
void StrokeCircle::setThickness(double t)
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
385
{
386
	if (t > 0)
387
		ithickness = t;
388
}
389
700 by Paul Broadbent
fixed the advanced putter and added advanced putter resize
390
double StrokeCircle::thickness() const
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
391
{
392
	return ithickness;
393
}
394
700 by Paul Broadbent
fixed the advanced putter and added advanced putter resize
395
double StrokeCircle::width() const
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
396
{
397
	return iwidth;
398
}
399
700 by Paul Broadbent
fixed the advanced putter and added advanced putter resize
400
double StrokeCircle::height() const
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
401
{
402
	return iheight;
403
}
404
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
405
void StrokeCircle::paint (QPainter *p, const QStyleOptionGraphicsItem *, QWidget * )
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
406
{
169 by Jason Katz-Brown
make putter use radians and not degrees
407
	int al = (int)((dvalue * 360 * 16) / dmax);
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
408
	int length, deg;
409
	if (al < 0)
410
	{
411
		deg = 270 * 16;
412
		length = -al;
96 by Dirk Mueller
--enable-final fixes
413
	}
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
414
	else if (al <= (270 * 16))
415
	{
416
		deg = 270 * 16 - al;
417
		length = al;
96 by Dirk Mueller
--enable-final fixes
418
	}
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
419
	else
420
	{
421
		deg = (360 * 16) - (al - (270 * 16));
422
		length = al;
96 by Dirk Mueller
--enable-final fixes
423
	}
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
424
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
425
	p->setBrush(QBrush(Qt::black, Qt::NoBrush));
426
	p->setPen(QPen(Qt::white, ithickness / 2));
427
	p->drawEllipse(QRectF(x() + ithickness / 2, y() + ithickness / 2, iwidth - ithickness, iheight - ithickness));
428
429
	if(dvalue>=0)
430
		p->setPen(QPen(QColor((int)((0xff * dvalue) / dmax), 0, (int)(0xff - (0xff * dvalue) / dmax)), ithickness));
431
	else
432
		p->setPen(QPen(QColor("black"), ithickness));
433
434
	p->drawArc(QRectF(x() + ithickness / 2, y() + ithickness / 2, iwidth - ithickness, iheight - ithickness), deg, length);
435
436
	p->setPen(QPen(Qt::white, 1));
437
	p->drawEllipse(QRectF(x(), y(), iwidth, iheight));
438
	p->drawEllipse(QRectF(x() + ithickness, y() + ithickness, iwidth - ithickness * 2, iheight - ithickness * 2));
439
	p->setPen(QPen(Qt::white, 3));
440
	p->drawLine(QPointF(x() + iwidth / 2, y() + iheight - ithickness * 1.5), QPointF(x() + iwidth / 2, y() + iheight));
441
	p->drawLine(QPointF(x() + iwidth / 4 - iwidth / 20, y() + iheight - iheight / 4 + iheight / 20), QPointF(x() + iwidth / 4 + iwidth / 20, y() + iheight - iheight / 4 - iheight / 20));
442
	p->drawLine(QPointF(x() + iwidth - iwidth / 4 + iwidth / 20, y() + iheight - iheight / 4 + iheight / 20), QPointF(x() + iwidth - iwidth / 4 - iwidth / 20, y() + iheight - iheight / 4 - iheight / 20));
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
443
}
444
/////////////////////////////////////////
445
983 by Stefan Majewsky
Replace the Object classes by the new ItemFactory.
446
KolfGame::KolfGame(const Kolf::ItemFactory& factory, PlayerList *players, const QString &filename, QWidget *parent)
763.1.1 by Bernhard Loos
port kdegames to kconfig changes
447
: QGraphicsView(parent)
983 by Stefan Majewsky
Replace the Object classes by the new ItemFactory.
448
, m_factory(factory)
1021 by Stefan Majewsky
Create a Box2D world, and attach Box2D bodies to all CanvasItems.
449
, holeInfo(g_world)
1 by Jason Katz-Brown
here's kolf, read the TODO
450
{
1010 by Stefan Majewsky
Add EllipticalCanvasItem class as common base class for Ball, Bumper, Cup, Puddle, Sand.
451
	setRenderHint(QPainter::Antialiasing);
26 by Jason Katz-Brown
kick-ass. 1) mouse support. 2) wallpoints fixed FOR GOOD. 3) random hole. 4) better save stuff still, prompt on close/quit.
452
	// for mouse control
220 by Jason Katz-Brown
borders
453
	setMouseTracking(true);
97 by Jason Katz-Brown
good stuff
454
	viewport()->setMouseTracking(true);
88 by Jason Katz-Brown
make independent ball moving more feasible. There might still be a few bugs in the implementation -- it's messy as hell!
455
	setFrameShape(NoFrame);
26 by Jason Katz-Brown
kick-ass. 1) mouse support. 2) wallpoints fixed FOR GOOD. 3) random hole. 4) better save stuff still, prompt on close/quit.
456
166 by Jason Katz-Brown
get rid of one timer (consolidate into other)
457
	regAdv = false;
96 by Dirk Mueller
--enable-final fixes
458
	curHole = 0; // will get ++'d
1 by Jason Katz-Brown
here's kolf, read the TODO
459
	cfg = 0;
460
	setFilename(filename);
461
	this->players = players;
462
	curPlayer = players->end();
463
	curPlayer--; // will get ++'d to end and sent back
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
464
	// to beginning
192 by Jason Katz-Brown
fix bad typo
465
	paused = false;
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
466
	modified = false;
1 by Jason Katz-Brown
here's kolf, read the TODO
467
	inPlay = false;
468
	putting = false;
469
	stroking = false;
470
	editing = false;
175 by Jason Katz-Brown
add new Slope Practice course, clean up some code
471
	strict = false;
205 by Jason Katz-Brown
stuff
472
	lastDelId = -1;
201 by Jason Katz-Brown
good fixes, black holes accept harder ball speeds, and most important new Show Info toggle action
473
	m_showInfo = false;
175 by Jason Katz-Brown
add new Slope Practice course, clean up some code
474
	ballStateList.canUndo = false;
603 by Stephan Kulow
KStandardDirs::locate change
475
	soundDir = KStandardDirs::locate("appdata", "sounds/");
100 by Jason Katz-Brown
make the game end if there's no competition, make it work better when putter is showing and ball goes into hole or puddle
476
	dontAddStroke = false;
1 by Jason Katz-Brown
here's kolf, read the TODO
477
	addingNewHole = false;
478
	scoreboardHoles = 0;
479
	infoShown = false;
27 by Jason Katz-Brown
fix 2 critical bugs: 1) don't crash when editing and mouse moves 2) make holes not disappear off of floaters (and floater saving is all better now thank heaven :)
480
	m_useMouse = true;
96 by Dirk Mueller
--enable-final fixes
481
	m_useAdvancedPutting = true;
482
	m_sound = true;
177 by Jason Katz-Brown
add spiffy intro infinite-loop hole
483
	m_ignoreEvents = false;
28 by Jason Katz-Brown
various stuff.. fixes mostly
484
	highestHole = 0;
133 by Jason Katz-Brown
485
	recalcHighestHole = false;
822 by Mauricio Piacentini
Fix garbage in intro screen, put new Kolf SVG banner.
486
	banner = 0;
1 by Jason Katz-Brown
here's kolf, read the TODO
487
725 by Paul Broadbent
fixed reszing bug and disabled sound
488
#ifdef SOUND
739 by Matthias Kretz
adapt to phonon-Trolltech branch API changes
489
	m_player = Phonon::createPlayer(Phonon::GameCategory);
725 by Paul Broadbent
fixed reszing bug and disabled sound
490
#endif
611 by Dmitry Suzdalev
Use Phonon::AudioPlayer
491
30 by Jason Katz-Brown
elliptical slopes!! and other things!
492
	holeInfo.setGame(this);
1 by Jason Katz-Brown
here's kolf, read the TODO
493
	holeInfo.setAuthor(i18n("Course Author"));
494
	holeInfo.setName(i18n("Course Name"));
288 by Jason Katz-Brown
read untranslated entries in the editor so I don't always save my courses with Japanese names
495
	holeInfo.setUntranslatedName(i18n("Course Name"));
1 by Jason Katz-Brown
here's kolf, read the TODO
496
	holeInfo.setMaxStrokes(10);
30 by Jason Katz-Brown
elliptical slopes!! and other things!
497
	holeInfo.borderWallsChanged(true);
1 by Jason Katz-Brown
here's kolf, read the TODO
498
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
499
	// width and height are the width and height of the scene
220 by Jason Katz-Brown
borders
500
	// in easy storage
1 by Jason Katz-Brown
here's kolf, read the TODO
501
	width = 400;
502
	height = 400;
503
220 by Jason Katz-Brown
borders
504
	margin = 10;
505
532.1.1 by Laurent Montel
Start to remove compile error
506
	setFocusPolicy(Qt::StrongFocus);
660 by Paul Broadbent
added resizing and started fixing edit mode
507
	setMinimumSize(width, height);
508
	QSizePolicy sizePolicy = QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
509
	setSizePolicy(sizePolicy);
220 by Jason Katz-Brown
borders
510
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
511
	setContentsMargins(margin, margin, margin, margin);
512
991 by Stefan Majewsky
First use of Tagaro::Scene, Board, and SpriteObjectItem in KolfGame class.
513
	course = new Tagaro::Scene(Kolf::renderer(), "grass");
514
	course->setMainView(this); //this does this->setScene(course)
515
	courseBoard = new Tagaro::Board;
516
	courseBoard->setLogicalSize(QSizeF(400, 400));
517
	course->addItem(courseBoard);
39 by Jason Katz-Brown
cool cursors, sequential loading
518
754 by Paul Broadbent
added forground image to intro
519
	if( filename.contains( "intro" ) )
520
	{
991 by Stefan Majewsky
First use of Tagaro::Scene, Board, and SpriteObjectItem in KolfGame class.
521
		banner = new Tagaro::SpriteObjectItem(Kolf::renderer(), "intro_foreground", courseBoard);
522
		banner->setSize(400, 132);
523
		banner->setPos(0, 32);
1068 by Stefan Majewsky
Refactor Z ordering.
524
		banner->setZValue(3); //on the height of a puddle (above slopes and sands, below any objects)
754 by Paul Broadbent
added forground image to intro
525
	}
526
1 by Jason Katz-Brown
here's kolf, read the TODO
527
	adjustSize();
528
529
	for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
530
	{
531
		Ball* ball = (*it).ball();
532
		ball->setParentItem(courseBoard);
533
		m_topLevelQItems << ball;
534
		m_moveableQItems << ball;
535
	}
1 by Jason Katz-Brown
here's kolf, read the TODO
536
677 by Pino Toscano
remove unneeded usage of kapplication.h and qtooltip.h
537
	QFont font = QApplication::font();
1 by Jason Katz-Brown
here's kolf, read the TODO
538
	font.setPixelSize(12);
539
97 by Jason Katz-Brown
good stuff
540
	// create the advanced putting indicator
993 by Stefan Majewsky
Move all items on the scene into the Tagaro::Board.
541
	strokeCircle = new StrokeCircle(courseBoard);
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
542
	strokeCircle->setPos(width - 90, height - 90);
97 by Jason Katz-Brown
good stuff
543
	strokeCircle->setVisible(false);
544
	strokeCircle->setValue(0);
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
545
	strokeCircle->setMaxValue(360); 
97 by Jason Katz-Brown
good stuff
546
1 by Jason Katz-Brown
here's kolf, read the TODO
547
	// whiteBall marks the spot of the whole whilst editing
1021 by Stefan Majewsky
Create a Box2D world, and attach Box2D bodies to all CanvasItems.
548
	whiteBall = new Ball(courseBoard, g_world);
88 by Jason Katz-Brown
make independent ball moving more feasible. There might still be a few bugs in the implementation -- it's messy as hell!
549
	whiteBall->setGame(this);
532.1.1 by Laurent Montel
Start to remove compile error
550
	whiteBall->setColor(Qt::white);
1 by Jason Katz-Brown
here's kolf, read the TODO
551
	whiteBall->setVisible(false);
97 by Jason Katz-Brown
good stuff
552
	whiteBall->setDoDetect(false);
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
553
	m_topLevelQItems << whiteBall;
554
	m_moveableQItems << whiteBall;
1 by Jason Katz-Brown
here's kolf, read the TODO
555
133 by Jason Katz-Brown
556
	int highestLog = 0;
557
558
	// if players have scores from loaded game, move to last hole
88 by Jason Katz-Brown
make independent ball moving more feasible. There might still be a few bugs in the implementation -- it's messy as hell!
559
	for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
97 by Jason Katz-Brown
good stuff
560
	{
133 by Jason Katz-Brown
561
		if ((int)(*it).scores().count() > highestLog)
562
			highestLog = (*it).scores().count();
563
88 by Jason Katz-Brown
make independent ball moving more feasible. There might still be a few bugs in the implementation -- it's messy as hell!
564
		(*it).ball()->setGame(this);
97 by Jason Katz-Brown
good stuff
565
	}
88 by Jason Katz-Brown
make independent ball moving more feasible. There might still be a few bugs in the implementation -- it's messy as hell!
566
133 by Jason Katz-Brown
567
	// here only for saved games
568
	if (highestLog)
150 by Jason Katz-Brown
569
		curHole = highestLog;
133 by Jason Katz-Brown
570
1021 by Stefan Majewsky
Create a Box2D world, and attach Box2D bodies to all CanvasItems.
571
	putter = new Putter(courseBoard, g_world);
1 by Jason Katz-Brown
here's kolf, read the TODO
572
573
	// border walls:
36 by Jason Katz-Brown
bumpers! super-fun. other fixes.
574
575
	// horiz
576
	addBorderWall(QPoint(margin, margin), QPoint(width - margin, margin));
577
	addBorderWall(QPoint(margin, height - margin - 1), QPoint(width - margin, height - margin - 1));
578
579
	// vert
580
	addBorderWall(QPoint(margin, margin), QPoint(margin, height - margin));
581
	addBorderWall(QPoint(width - margin - 1, margin), QPoint(width - margin - 1, height - margin));
1 by Jason Katz-Brown
here's kolf, read the TODO
582
583
	timer = new QTimer(this);
584
	connect(timer, SIGNAL(timeout()), this, SLOT(timeout()));
97 by Jason Katz-Brown
good stuff
585
	timerMsec = 300;
1 by Jason Katz-Brown
here's kolf, read the TODO
586
587
	fastTimer = new QTimer(this);
588
	connect(fastTimer, SIGNAL(timeout()), this, SLOT(fastTimeout()));
589
	fastTimerMsec = 11;
590
591
	autoSaveTimer = new QTimer(this);
592
	connect(autoSaveTimer, SIGNAL(timeout()), this, SLOT(autoSaveTimeout()));
593
	autoSaveMsec = 5 * 1000 * 60; // 5 min autosave
594
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
595
	// setUseAdvancedPutting() sets maxStrength!
596
	setUseAdvancedPutting(false);
96 by Dirk Mueller
--enable-final fixes
597
1 by Jason Katz-Brown
here's kolf, read the TODO
598
	putting = false;
599
	putterTimer = new QTimer(this);
600
	connect(putterTimer, SIGNAL(timeout()), this, SLOT(putterTimeout()));
601
	putterTimerMsec = 20;
133 by Jason Katz-Brown
602
}
1 by Jason Katz-Brown
here's kolf, read the TODO
603
150 by Jason Katz-Brown
604
void KolfGame::startFirstHole(int hole)
133 by Jason Katz-Brown
605
{
150 by Jason Katz-Brown
606
	if (curHole > 0) // if there was saved game, sync scoreboard
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
607
		// with number of holes
150 by Jason Katz-Brown
608
	{
609
		for (; scoreboardHoles < curHole; ++scoreboardHoles)
610
		{
709 by Stephan Kulow
don't leak _that_ bad (CID 3637)
611
			cfgGroup = KConfigGroup(cfg->group(QString("%1-hole@-50,-50|0").arg(scoreboardHoles + 1)));
710 by Stephan Kulow
fixing my commit - earning dartstars like mad
612
			emit newHole(cfgGroup.readEntry("par", 3));
150 by Jason Katz-Brown
613
		}
133 by Jason Katz-Brown
614
150 by Jason Katz-Brown
615
		// lets load all of the scores from saved game if there are any
133 by Jason Katz-Brown
616
		for (int hole = 1; hole <= curHole; ++hole)
617
			for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
618
				emit scoreChanged((*it).id(), hole, (*it).score(hole));
150 by Jason Katz-Brown
619
	}
620
621
	curHole = hole - 1;
622
623
	// this increments curHole, etc
624
	recalcHighestHole = true;
192 by Jason Katz-Brown
fix bad typo
625
	startNextHole();
150 by Jason Katz-Brown
626
	paused = true;
627
	unPause();
1 by Jason Katz-Brown
here's kolf, read the TODO
628
}
629
630
void KolfGame::setFilename(const QString &filename)
631
{
632
	this->filename = filename;
633
	delete cfg;
657.1.3 by Stephan Kulow
compile some more
634
	cfg = new KConfig(filename, KConfig::NoGlobals);
1 by Jason Katz-Brown
here's kolf, read the TODO
635
}
636
637
KolfGame::~KolfGame()
638
{
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
639
	QList<QGraphicsItem*> itemsCopy(m_topLevelQItems); //this list will be modified soon, so take a copy
640
	foreach (QGraphicsItem* item, itemsCopy)
1032 by Stefan Majewsky
The shotgun approach to object cleanup: Destroy everything!
641
	{
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
642
		CanvasItem* citem = dynamic_cast<CanvasItem*>(item);
1065 by Stefan Majewsky
Remove a big bunch of unused methods from CanvasItem.
643
		delete citem;
1032 by Stefan Majewsky
The shotgun approach to object cleanup: Destroy everything!
644
	}
645
1 by Jason Katz-Brown
here's kolf, read the TODO
646
	delete cfg;
725 by Paul Broadbent
fixed reszing bug and disabled sound
647
#ifdef SOUND
611 by Dmitry Suzdalev
Use Phonon::AudioPlayer
648
	delete m_player;
725 by Paul Broadbent
fixed reszing bug and disabled sound
649
#endif
1 by Jason Katz-Brown
here's kolf, read the TODO
650
}
651
301 by Jason Katz-Brown
fix up, reenable charles's code, bugs.. etc
652
void KolfGame::setModified(bool mod)
653
{
654
	modified = mod;
655
	emit modifiedChanged(mod);
656
}
657
1 by Jason Katz-Brown
here's kolf, read the TODO
658
void KolfGame::pause()
659
{
192 by Jason Katz-Brown
fix bad typo
660
	if (paused)
1 by Jason Katz-Brown
here's kolf, read the TODO
661
	{
662
		// play along with people who call pause() again, instead of unPause()
663
		unPause();
664
		return;
665
	}
666
667
	paused = true;
668
	timer->stop();
669
	fastTimer->stop();
670
	putterTimer->stop();
671
}
672
673
void KolfGame::unPause()
674
{
675
	if (!paused)
676
		return;
677
678
	paused = false;
679
680
	timer->start(timerMsec);
681
	fastTimer->start(fastTimerMsec);
682
683
	if (putting || stroking)
684
		putterTimer->start(putterTimerMsec);
685
}
686
702 by Matt Williams
Make EBN happy with plenty of references-to-const fixes.
687
void KolfGame::addBorderWall(const QPoint &start, const QPoint &end)
1 by Jason Katz-Brown
here's kolf, read the TODO
688
{
1047 by Stefan Majewsky
Refactor Wall class: Drop WallPoint class, introduce WallOverlay.
689
	Kolf::Wall *wall = new Kolf::Wall(courseBoard, g_world);
1018 by Stefan Majewsky
Adapt Kolf::Overlay and Kolf::Shape from playground/games/kolf2/base.
690
	wall->setLine(QLineF(start, end));
5 by Jason Katz-Brown
691
	wall->setVisible(true);
1 by Jason Katz-Brown
here's kolf, read the TODO
692
	wall->setGame(this);
1079 by Stefan Majewsky
Fix Z ordering of border walls.
693
	//change Z value to something very high so that border walls
694
	//really keep the balls inside the course
695
	wall->setZBehavior(CanvasItem::FixedZValue, 10000);
1 by Jason Katz-Brown
here's kolf, read the TODO
696
	borderWalls.append(wall);
697
}
698
227 by Jason Katz-Brown
make scrollview mouse presses work right
699
void KolfGame::handleMouseDoubleClickEvent(QMouseEvent *e)
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
700
{
56 by Jason Katz-Brown
new cup graphic, better slope arrows
701
	// allow two fast single clicks
227 by Jason Katz-Brown
make scrollview mouse presses work right
702
	handleMousePressEvent(e);
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
703
}
177 by Jason Katz-Brown
add spiffy intro infinite-loop hole
704
227 by Jason Katz-Brown
make scrollview mouse presses work right
705
void KolfGame::handleMousePressEvent(QMouseEvent *e)
1 by Jason Katz-Brown
here's kolf, read the TODO
706
{
322 by Jason Katz-Brown
fix showinfo state bugs
707
	if (m_ignoreEvents)
26 by Jason Katz-Brown
kick-ass. 1) mouse support. 2) wallpoints fixed FOR GOOD. 3) random hole. 4) better save stuff still, prompt on close/quit.
708
		return;
709
322 by Jason Katz-Brown
fix showinfo state bugs
710
	if (editing)
711
	{
1070 by Stefan Majewsky
Remove obsolete code from KolfGame for selecting and moving items in the editor.
712
		//at this point, QGV::mousePressEvent and thus the interaction
713
		//with overlays has already been done; we therefore know that
714
		//the user has clicked into free space
1071 by Stefan Majewsky
Fix overlay activation and deactivation.
715
		setSelectedItem(0);
1070 by Stefan Majewsky
Remove obsolete code from KolfGame for selecting and moving items in the editor.
716
		return;
1 by Jason Katz-Brown
here's kolf, read the TODO
717
	}
322 by Jason Katz-Brown
fix showinfo state bugs
718
	else
719
	{
720
		if (m_useMouse)
721
		{
532.1.1 by Laurent Montel
Start to remove compile error
722
			if (!inPlay && e->button() == Qt::LeftButton)
322 by Jason Katz-Brown
fix showinfo state bugs
723
				puttPress();
532.1.1 by Laurent Montel
Start to remove compile error
724
			else if (e->button() == Qt::RightButton)
322 by Jason Katz-Brown
fix showinfo state bugs
725
				toggleShowInfo();
726
		}
727
	}
1 by Jason Katz-Brown
here's kolf, read the TODO
728
729
	setFocus();
730
}
731
220 by Jason Katz-Brown
borders
732
QPoint KolfGame::viewportToViewport(const QPoint &p)
733
{
993 by Stefan Majewsky
Move all items on the scene into the Tagaro::Board.
734
	//convert viewport coordinates to board coordinates
735
	return courseBoard->deviceTransform(viewportTransform()).inverted().map(p);
220 by Jason Katz-Brown
borders
736
}
737
227 by Jason Katz-Brown
make scrollview mouse presses work right
738
// the following four functions are needed to handle both
739
// border presses and regular in-course presses
740
220 by Jason Katz-Brown
borders
741
void KolfGame::mouseReleaseEvent(QMouseEvent * e)
742
{
1017 by Stefan Majewsky
Enable mouse handlers of QGraphicsItems which accept mouse interaction.
743
	e->setAccepted(false);
744
	QGraphicsView::mouseReleaseEvent(e);
745
	if (e->isAccepted())
746
		return;
747
661 by Paul Broadbent
fixed some compile time warnings and resized ball movement bugs
748
	QMouseEvent fixedEvent (QEvent::MouseButtonRelease, viewportToViewport(e->pos()), e->button(), e->buttons(), e->modifiers());
227 by Jason Katz-Brown
make scrollview mouse presses work right
749
	handleMouseReleaseEvent(&fixedEvent);
966 by Stefan Majewsky
Fix mouse event propagation in combination with Oxygen's new window dragging.
750
	e->accept();
220 by Jason Katz-Brown
borders
751
}
752
753
void KolfGame::mousePressEvent(QMouseEvent * e)
754
{
1017 by Stefan Majewsky
Enable mouse handlers of QGraphicsItems which accept mouse interaction.
755
	e->setAccepted(false);
756
	QGraphicsView::mousePressEvent(e);
757
	if (e->isAccepted())
758
		return;
759
661 by Paul Broadbent
fixed some compile time warnings and resized ball movement bugs
760
	QMouseEvent fixedEvent (QEvent::MouseButtonPress, viewportToViewport(e->pos()), e->button(), e->buttons(), e->modifiers());
227 by Jason Katz-Brown
make scrollview mouse presses work right
761
	handleMousePressEvent(&fixedEvent);
966 by Stefan Majewsky
Fix mouse event propagation in combination with Oxygen's new window dragging.
762
	e->accept();
220 by Jason Katz-Brown
borders
763
}
764
765
void KolfGame::mouseDoubleClickEvent(QMouseEvent * e)
766
{
1017 by Stefan Majewsky
Enable mouse handlers of QGraphicsItems which accept mouse interaction.
767
	e->setAccepted(false);
768
	QGraphicsView::mouseDoubleClickEvent(e);
769
	if (e->isAccepted())
770
		return;
771
661 by Paul Broadbent
fixed some compile time warnings and resized ball movement bugs
772
	QMouseEvent fixedEvent (QEvent::MouseButtonDblClick, viewportToViewport(e->pos()), e->button(), e->buttons(), e->modifiers());
227 by Jason Katz-Brown
make scrollview mouse presses work right
773
	handleMouseDoubleClickEvent(&fixedEvent);
966 by Stefan Majewsky
Fix mouse event propagation in combination with Oxygen's new window dragging.
774
	e->accept();
220 by Jason Katz-Brown
borders
775
}
776
777
void KolfGame::mouseMoveEvent(QMouseEvent * e)
778
{
1017 by Stefan Majewsky
Enable mouse handlers of QGraphicsItems which accept mouse interaction.
779
	e->setAccepted(false);
780
	QGraphicsView::mouseMoveEvent(e);
781
	if (e->isAccepted())
782
		return;
783
661 by Paul Broadbent
fixed some compile time warnings and resized ball movement bugs
784
	QMouseEvent fixedEvent (QEvent::MouseMove, viewportToViewport(e->pos()), e->button(), e->buttons(), e->modifiers());
227 by Jason Katz-Brown
make scrollview mouse presses work right
785
	handleMouseMoveEvent(&fixedEvent);
966 by Stefan Majewsky
Fix mouse event propagation in combination with Oxygen's new window dragging.
786
	e->accept();
220 by Jason Katz-Brown
borders
787
}
788
227 by Jason Katz-Brown
make scrollview mouse presses work right
789
void KolfGame::handleMouseMoveEvent(QMouseEvent *e)
1 by Jason Katz-Brown
here's kolf, read the TODO
790
{
1070 by Stefan Majewsky
Remove obsolete code from KolfGame for selecting and moving items in the editor.
791
	if (!editing && !inPlay && putter && !m_ignoreEvents)
26 by Jason Katz-Brown
kick-ass. 1) mouse support. 2) wallpoints fixed FOR GOOD. 3) random hole. 4) better save stuff still, prompt on close/quit.
792
	{
1070 by Stefan Majewsky
Remove obsolete code from KolfGame for selecting and moving items in the editor.
793
		// mouse moving of putter
28 by Jason Katz-Brown
various stuff.. fixes mostly
794
		updateMouse();
1070 by Stefan Majewsky
Remove obsolete code from KolfGame for selecting and moving items in the editor.
795
		e->accept();
796
	}
1 by Jason Katz-Brown
here's kolf, read the TODO
797
}
798
28 by Jason Katz-Brown
various stuff.. fixes mostly
799
void KolfGame::updateMouse()
800
{
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
801
	// don't move putter if in advanced putting sequence
96 by Dirk Mueller
--enable-final fixes
802
	if (!m_useMouse || ((stroking || putting) && m_useAdvancedPutting))
28 by Jason Katz-Brown
various stuff.. fixes mostly
803
		return;
804
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
805
	const QPointF cursor = viewportToViewport(mapFromGlobal(QCursor::pos()));
806
	const QPointF ball((*curPlayer).ball()->x(), (*curPlayer).ball()->y());
985 by Stefan Majewsky
Rewrite Vector class as a subclass of QPointF.
807
	putter->setAngle(-Vector(cursor - ball).direction());
28 by Jason Katz-Brown
various stuff.. fixes mostly
808
}
809
227 by Jason Katz-Brown
make scrollview mouse presses work right
810
void KolfGame::handleMouseReleaseEvent(QMouseEvent *e)
1 by Jason Katz-Brown
here's kolf, read the TODO
811
{
680 by Pino Toscano
better API for cursors
812
	setCursor(Qt::ArrowCursor);
334 by Jason Katz-Brown
add new status message while moving things
813
814
	if (editing)
815
	{
684 by Matt Williams
kblackbox, kbounce, kgoldrunner, kmahjongg, knetwalk, kolf, kpat and kshisen EBN fixes
816
		emit newStatusText(QString());
334 by Jason Katz-Brown
add new status message while moving things
817
	}
1 by Jason Katz-Brown
here's kolf, read the TODO
818
322 by Jason Katz-Brown
fix showinfo state bugs
819
	if (m_ignoreEvents)
26 by Jason Katz-Brown
kick-ass. 1) mouse support. 2) wallpoints fixed FOR GOOD. 3) random hole. 4) better save stuff still, prompt on close/quit.
820
		return;
821
322 by Jason Katz-Brown
fix showinfo state bugs
822
	if (!editing && m_useMouse)
1 by Jason Katz-Brown
here's kolf, read the TODO
823
	{
532.1.1 by Laurent Montel
Start to remove compile error
824
		if (!inPlay && e->button() == Qt::LeftButton)
322 by Jason Katz-Brown
fix showinfo state bugs
825
			puttRelease();
532.1.1 by Laurent Montel
Start to remove compile error
826
		else if (e->button() == Qt::RightButton)
322 by Jason Katz-Brown
fix showinfo state bugs
827
			toggleShowInfo();
1 by Jason Katz-Brown
here's kolf, read the TODO
828
	}
829
830
	setFocus();
831
}
832
833
void KolfGame::keyPressEvent(QKeyEvent *e)
834
{
177 by Jason Katz-Brown
add spiffy intro infinite-loop hole
835
	if (inPlay || editing || m_ignoreEvents)
836
		return;
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
837
1 by Jason Katz-Brown
here's kolf, read the TODO
838
	switch (e->key())
839
	{
532.1.1 by Laurent Montel
Start to remove compile error
840
		case Qt::Key_Up:
1 by Jason Katz-Brown
here's kolf, read the TODO
841
			if (!e->isAutoRepeat())
201 by Jason Katz-Brown
good fixes, black holes accept harder ball speeds, and most important new Show Info toggle action
842
				toggleShowInfo();
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
843
			break;
1 by Jason Katz-Brown
here's kolf, read the TODO
844
532.1.1 by Laurent Montel
Start to remove compile error
845
		case Qt::Key_Escape:
1 by Jason Katz-Brown
here's kolf, read the TODO
846
			putting = false;
847
			stroking = false;
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
848
			finishStroking = false;
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
849
			strokeCircle->setVisible(false); 
1 by Jason Katz-Brown
here's kolf, read the TODO
850
			putterTimer->stop();
851
			putter->setOrigin((*curPlayer).ball()->x(), (*curPlayer).ball()->y());
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
852
			break;
1 by Jason Katz-Brown
here's kolf, read the TODO
853
532.1.1 by Laurent Montel
Start to remove compile error
854
		case Qt::Key_Left:
855
		case Qt::Key_Right:
96 by Dirk Mueller
--enable-final fixes
856
			// don't move putter if in advanced putting sequence
56 by Jason Katz-Brown
new cup graphic, better slope arrows
857
			if ((!stroking && !putting) || !m_useAdvancedPutting)
661 by Paul Broadbent
fixed some compile time warnings and resized ball movement bugs
858
				putter->go(e->key() == Qt::Key_Left? D_Left : D_Right, e->modifiers() & Qt::ShiftModifier? Amount_More : e->modifiers() & Qt::ControlModifier? Amount_Less : Amount_Normal);
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
859
			break;
1 by Jason Katz-Brown
here's kolf, read the TODO
860
532.1.1 by Laurent Montel
Start to remove compile error
861
		case Qt::Key_Space: case Qt::Key_Down:
1 by Jason Katz-Brown
here's kolf, read the TODO
862
			puttPress();
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
863
			break;
1 by Jason Katz-Brown
here's kolf, read the TODO
864
865
		default:
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
866
			break;
1 by Jason Katz-Brown
here's kolf, read the TODO
867
	}
868
}
869
201 by Jason Katz-Brown
good fixes, black holes accept harder ball speeds, and most important new Show Info toggle action
870
void KolfGame::toggleShowInfo()
871
{
872
	setShowInfo(!m_showInfo);
873
}
874
875
void KolfGame::updateShowInfo()
876
{
877
	setShowInfo(m_showInfo);
878
}
879
880
void KolfGame::setShowInfo(bool yes)
881
{
882
	m_showInfo = yes;
1053 by Stefan Majewsky
More sophisticated handling of info items.
883
	QList<QGraphicsItem*> infoItems;
884
	foreach (QGraphicsItem* qitem, m_topLevelQItems)
885
	{
886
		CanvasItem *citem = dynamic_cast<CanvasItem *>(qitem);
887
		if (citem)
888
			infoItems << citem->infoItems();
889
	}
890
	foreach (QGraphicsItem* qitem, infoItems)
891
		qitem->setVisible(m_showInfo);
26 by Jason Katz-Brown
kick-ass. 1) mouse support. 2) wallpoints fixed FOR GOOD. 3) random hole. 4) better save stuff still, prompt on close/quit.
892
}
893
1 by Jason Katz-Brown
here's kolf, read the TODO
894
void KolfGame::puttPress()
895
{
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
896
	// Advanced putting: 1st click start putting sequence, 2nd determine strength, 3rd determine precision
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
897
1 by Jason Katz-Brown
here's kolf, read the TODO
898
	if (!putting && !stroking && !inPlay)
899
	{
900
		puttCount = 0;
96 by Dirk Mueller
--enable-final fixes
901
		puttReverse = false;
1 by Jason Katz-Brown
here's kolf, read the TODO
902
		putting = true;
903
		stroking = false;
904
		strength = 0;
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
905
		if (m_useAdvancedPutting)
906
		{
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
907
			strokeCircle->setValue(0); 
908
			int pw = (int)(putter->line().x2() - putter->line().x1());
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
909
			if (pw < 0) pw = -pw;
169 by Jason Katz-Brown
make putter use radians and not degrees
910
			int px = (int)putter->x() + pw / 2;
911
			int py = (int)putter->y();
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
912
			if (px > width / 2 && py < height / 2) 
913
				strokeCircle->setPos(px/2 - pw / 2 - 5 - strokeCircle->width()/2, py/2 + 5);
914
			else if (px > width / 2) 
915
				strokeCircle->setPos(px/2 - pw / 2 - 5 - strokeCircle->width()/2, py/2 - 5 - strokeCircle->height()/2);
916
			else if (py < height / 2) 
917
				strokeCircle->setPos(px/2 + pw / 2 + 5, py/2 + 5);
918
			else 
919
				strokeCircle->setPos(px/2 + pw / 2 + 5, py/2 - 5 - strokeCircle->height()/2);
920
			strokeCircle->setVisible(true); 
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
921
		}
1 by Jason Katz-Brown
here's kolf, read the TODO
922
		putterTimer->start(putterTimerMsec);
923
	}
96 by Dirk Mueller
--enable-final fixes
924
	else if (m_useAdvancedPutting && putting && !editing)
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
925
	{
926
		putting = false;
927
		stroking = true;
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
928
		puttReverse = false;
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
929
		finishStroking = false;
96 by Dirk Mueller
--enable-final fixes
930
	}
931
	else if (m_useAdvancedPutting && stroking)
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
932
	{
933
		finishStroking = true;
934
		putterTimeout();
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
935
	}
1 by Jason Katz-Brown
here's kolf, read the TODO
936
}
937
938
void KolfGame::keyReleaseEvent(QKeyEvent *e)
939
{
177 by Jason Katz-Brown
add spiffy intro infinite-loop hole
940
	if (e->isAutoRepeat() || m_ignoreEvents)
1 by Jason Katz-Brown
here's kolf, read the TODO
941
		return;
942
532.1.1 by Laurent Montel
Start to remove compile error
943
	if (e->key() == Qt::Key_Space || e->key() == Qt::Key_Down)
1 by Jason Katz-Brown
here's kolf, read the TODO
944
		puttRelease();
661 by Paul Broadbent
fixed some compile time warnings and resized ball movement bugs
945
	else if ((e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete) && !(e->modifiers() & Qt::ControlModifier))
1 by Jason Katz-Brown
here's kolf, read the TODO
946
	{
1070 by Stefan Majewsky
Remove obsolete code from KolfGame for selecting and moving items in the editor.
947
		if (editing && selectedItem)
1 by Jason Katz-Brown
here's kolf, read the TODO
948
		{
949
			CanvasItem *citem = dynamic_cast<CanvasItem *>(selectedItem);
122 by Jason Katz-Brown
950
			if (!citem)
951
				return;
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
952
			QGraphicsItem *item = dynamic_cast<QGraphicsItem *>(citem);
1067 by Stefan Majewsky
More CanvasItem cleanup.
953
			if (citem && !dynamic_cast<Ball*>(item))
1 by Jason Katz-Brown
here's kolf, read the TODO
954
			{
205 by Jason Katz-Brown
stuff
955
				lastDelId = citem->curId();
956
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
957
				m_topLevelQItems.removeAll(item);
958
				m_moveableQItems.removeAll(item);
149 by Jason Katz-Brown
clean up wall collisions
959
				delete citem;
1071 by Stefan Majewsky
Fix overlay activation and deactivation.
960
				setSelectedItem(0);
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
961
301 by Jason Katz-Brown
fix up, reenable charles's code, bugs.. etc
962
				setModified(true);
1 by Jason Katz-Brown
here's kolf, read the TODO
963
			}
964
		}
965
	}
532.1.1 by Laurent Montel
Start to remove compile error
966
	else if (e->key() == Qt::Key_I || e->key() == Qt::Key_Up)
201 by Jason Katz-Brown
good fixes, black holes accept harder ball speeds, and most important new Show Info toggle action
967
		toggleShowInfo();
1 by Jason Katz-Brown
here's kolf, read the TODO
968
}
969
660 by Paul Broadbent
added resizing and started fixing edit mode
970
void KolfGame::resizeEvent( QResizeEvent* ev )
971
{
972
	int newW = ev->size().width();
973
	int newH = ev->size().height();
974
	int oldW = ev->oldSize().width();
975
	int oldH = ev->oldSize().height();
976
977
	if(oldW<=0 || oldH<=0) //this is the first draw so no point wasting resources resizing yet
978
		return;
979
	else if( (oldW==newW) && (oldH==newH) )
980
		return;
981
1003 by Stefan Majewsky
Kill RectItem class and newSize() methods.
982
	int setSize = qMin(newW, newH);
983
	QGraphicsView::resize(setSize, setSize); //make sure new size is square
660 by Paul Broadbent
added resizing and started fixing edit mode
984
}
985
1 by Jason Katz-Brown
here's kolf, read the TODO
986
void KolfGame::puttRelease()
987
{
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
988
	if (!m_useAdvancedPutting && putting && !editing)
1 by Jason Katz-Brown
here's kolf, read the TODO
989
	{
990
		putting = false;
991
		stroking = true;
992
	}
993
}
994
100 by Jason Katz-Brown
make the game end if there's no competition, make it work better when putter is showing and ball goes into hole or puddle
995
void KolfGame::stoppedBall()
996
{
997
	if (!inPlay)
998
	{
999
		inPlay = true;
1000
		dontAddStroke = true;
1001
	}
1002
}
1003
1 by Jason Katz-Brown
here's kolf, read the TODO
1004
void KolfGame::timeout()
1005
{
1006
	Ball *curBall = (*curPlayer).ball();
1007
72 by Jason Katz-Brown
undo if ball leaves course
1008
	// test if the ball is gone
1009
	// in this case we want to stop the ball and
1010
	// later undo the shot
88 by Jason Katz-Brown
make independent ball moving more feasible. There might still be a few bugs in the implementation -- it's messy as hell!
1011
	for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
72 by Jason Katz-Brown
undo if ball leaves course
1012
	{
634 by Mauricio Piacentini
QGV will handle dirty rects for us
1013
                //QGV handles management of dirtied rects for us
1014
		//course->update();
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1015
993 by Stefan Majewsky
Move all items on the scene into the Tagaro::Board.
1016
		if (!QRectF(QPointF(), courseBoard->logicalSize()).contains((*it).ball()->pos()))
88 by Jason Katz-Brown
make independent ball moving more feasible. There might still be a few bugs in the implementation -- it's messy as hell!
1017
		{
1018
			(*it).ball()->setState(Stopped);
213 by Jason Katz-Brown
iwallpoint stuff
1019
1020
			// don't do it if he's past maxStrokes
328 by Jason Katz-Brown
fix max strokes stuff
1021
			if ((*it).score(curHole) < holeInfo.maxStrokes() - 1 || !holeInfo.hasMaxStrokes())
213 by Jason Katz-Brown
iwallpoint stuff
1022
			{
1023
				loadStateList();
1024
			}
429 by Albert Astals Cid
Forward port (is that the correct word?), the fix for bug 49173 to the CVS HEAD branch
1025
			shotDone();
328 by Jason Katz-Brown
fix max strokes stuff
1026
88 by Jason Katz-Brown
make independent ball moving more feasible. There might still be a few bugs in the implementation -- it's messy as hell!
1027
			return;
1028
		}
72 by Jason Katz-Brown
undo if ball leaves course
1029
	}
1030
88 by Jason Katz-Brown
make independent ball moving more feasible. There might still be a few bugs in the implementation -- it's messy as hell!
1031
	for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
1065 by Stefan Majewsky
Remove a big bunch of unused methods from CanvasItem.
1032
		if ((*it).ball()->forceStillGoing() || ((*it).ball()->curState() == Rolling && Vector((*it).ball()->velocity()).magnitude() > 0 && (*it).ball()->isVisible()))
88 by Jason Katz-Brown
make independent ball moving more feasible. There might still be a few bugs in the implementation -- it's messy as hell!
1033
			return;
1034
1 by Jason Katz-Brown
here's kolf, read the TODO
1035
	int curState = curBall->curState();
1036
	if (curState == Stopped && inPlay)
1037
	{
70 by Jason Katz-Brown
undo shot! :-)
1038
		inPlay = false;
301 by Jason Katz-Brown
fix up, reenable charles's code, bugs.. etc
1039
		QTimer::singleShot(0, this, SLOT(shotDone()));
1 by Jason Katz-Brown
here's kolf, read the TODO
1040
	}
1041
1042
	if (curState == Holed && inPlay)
1043
	{
1044
		emit inPlayEnd();
1045
175 by Jason Katz-Brown
add new Slope Practice course, clean up some code
1046
		int curScore = (*curPlayer).score(curHole);
1047
		if (!dontAddStroke)
1048
			curScore++;
1049
5 by Jason Katz-Brown
1050
		if (curScore == 1)
304 by Jason Katz-Brown
play all of the new sounds, make blackholes spit out a little after the entrance
1051
		{
286 by Jason Katz-Brown
make kolf a lean, mean, command-line-argument handling machine. Will open courses AND saved games from the command line. The mimetypes also specify kolf in an exec line.
1052
			playSound("holeinone");
304 by Jason Katz-Brown
play all of the new sounds, make blackholes spit out a little after the entrance
1053
		}
5 by Jason Katz-Brown
1054
		else if (curScore <= holeInfo.par())
304 by Jason Katz-Brown
play all of the new sounds, make blackholes spit out a little after the entrance
1055
		{
1056
			// I don't have a sound!!
1057
			// *sob*
1058
			// playSound("woohoo");
1059
		}
1 by Jason Katz-Brown
here's kolf, read the TODO
1060
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1061
		(*curPlayer).ball()->setZValue((*curPlayer).ball()->zValue() + .1 - (.1)/(curScore));
5 by Jason Katz-Brown
1062
24 by Jason Katz-Brown
1063
		if (allPlayersDone())
1 by Jason Katz-Brown
here's kolf, read the TODO
1064
		{
1065
			inPlay = false;
1066
174 by Jason Katz-Brown
fix dontAddStroke bug
1067
			if (curHole > 0 && !dontAddStroke)
1 by Jason Katz-Brown
here's kolf, read the TODO
1068
			{
1069
				(*curPlayer).addStrokeToHole(curHole);
1070
				emit scoreChanged((*curPlayer).id(), curHole, (*curPlayer).score(curHole));
1071
			}
283 by Jason Katz-Brown
play holed.wav, make hole-ending sounds get played
1072
			QTimer::singleShot(600, this, SLOT(holeDone()));
1 by Jason Katz-Brown
here's kolf, read the TODO
1073
		}
1074
		else
1075
		{
1076
			inPlay = false;
301 by Jason Katz-Brown
fix up, reenable charles's code, bugs.. etc
1077
			QTimer::singleShot(0, this, SLOT(shotDone()));
1 by Jason Katz-Brown
here's kolf, read the TODO
1078
		}
1079
	}
1080
}
1081
1082
void KolfGame::fastTimeout()
1083
{
166 by Jason Katz-Brown
get rid of one timer (consolidate into other)
1084
	// do regular advance every other time
1085
	if (regAdv)
1086
		course->advance();
1087
	regAdv = !regAdv;
1088
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1089
	if (editing)
1090
		return;
1091
1023 by Stefan Majewsky
Execute Box2D steps aside the internal advance()s.
1092
	// do Box2D advance
1093
	//Because there are so much CanvasItems out there, there is currently no
1094
	//easy and/or systematic approach to iterate over all of them, except for
1095
	//using the b2Bodies available on the world.
1096
1097
	//prepare simulation
1098
	for (b2Body* body = g_world->GetBodyList(); body; body = body->GetNext())
1099
	{
1100
		CanvasItem* citem = static_cast<CanvasItem*>(body->GetUserData());
1101
		if (citem)
1102
		{
1103
			citem->startSimulation();
1068 by Stefan Majewsky
Refactor Z ordering.
1104
			//HACK: the following should not be necessary at this point
1105
			QGraphicsItem* qitem = dynamic_cast<QGraphicsItem*>(citem);
1106
			if (qitem)
1107
				citem->updateZ(qitem);
1023 by Stefan Majewsky
Execute Box2D steps aside the internal advance()s.
1108
		}
1109
	}
1110
	//step world
1065 by Stefan Majewsky
Remove a big bunch of unused methods from CanvasItem.
1111
	//NOTE: I previously set timeStep to 1.0 so that CItem's velocity()
1112
	//corresponds to the position change per step. In this case, the
1030 by Stefan Majewsky
Milestone! The intro level works with Box2D-powered ball propagation!
1113
	//velocity would be scaled by Kolf::Box2DScaleFactor, which would result in
1114
	//very small velocities (below Box2D's internal cutoff thresholds!) for
1115
	//usual movements. Therefore, we apply the scaling to the timestep instead.
1116
	const double timeStep = 1.0 * Kolf::Box2DScaleFactor;
1023 by Stefan Majewsky
Execute Box2D steps aside the internal advance()s.
1117
	g_world->Step(timeStep, 10, 10); //parameters 2/3 = iteration counts (TODO: optimize)
1118
	//conclude simulation
1119
	for (b2Body* body = g_world->GetBodyList(); body; body = body->GetNext())
1120
	{
1121
		CanvasItem* citem = static_cast<CanvasItem*>(body->GetUserData());
1122
		if (citem)
1123
		{
1124
			citem->endSimulation();
1125
		}
1126
	}
59 by Jason Katz-Brown
a spiffy newgame dialog
1127
}
1 by Jason Katz-Brown
here's kolf, read the TODO
1128
59 by Jason Katz-Brown
a spiffy newgame dialog
1129
void KolfGame::ballMoved()
1130
{
1131
	if (putter->isVisible())
166 by Jason Katz-Brown
get rid of one timer (consolidate into other)
1132
	{
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1133
		putter->setPos((*curPlayer).ball()->x(), (*curPlayer).ball()->y());
166 by Jason Katz-Brown
get rid of one timer (consolidate into other)
1134
		updateMouse();
1135
	}
1 by Jason Katz-Brown
here's kolf, read the TODO
1136
}
1137
1138
void KolfGame::putterTimeout()
1139
{
1140
	if (inPlay || editing)
1141
		return;
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1142
1143
	if (m_useAdvancedPutting)
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
1144
	{
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1145
		if (putting)
1146
		{
631 by Stephan Kulow
fix linking under windows
1147
			const qreal base = 2.0;
57 by Jason Katz-Brown
better black holes that are color-coded, better advanced putting speeds
1148
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1149
			if (puttReverse && strength <= 0)
1150
			{
1151
				// aborted
1152
				putting = false;
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1153
				strokeCircle->setVisible(false); 
96 by Dirk Mueller
--enable-final fixes
1154
			}
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1155
			else if (strength > maxStrength || puttReverse)
1156
			{
56 by Jason Katz-Brown
new cup graphic, better slope arrows
1157
				// decreasing strength as we've reached the top
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1158
				puttReverse = true;
631 by Stephan Kulow
fix linking under windows
1159
				strength -= pow(base, qreal(strength / maxStrength)) - 1.8;
169 by Jason Katz-Brown
make putter use radians and not degrees
1160
				if ((int)strength < puttCount * 2)
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1161
				{
1162
					puttCount--;
1163
					if (puttCount >= 0)
96 by Dirk Mueller
--enable-final fixes
1164
						putter->go(Forwards);
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1165
				}
96 by Dirk Mueller
--enable-final fixes
1166
			}
1167
			else
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1168
			{
1169
				// make the increase at high strength faster
57 by Jason Katz-Brown
better black holes that are color-coded, better advanced putting speeds
1170
				strength += pow(base, strength / maxStrength) - .3;
169 by Jason Katz-Brown
make putter use radians and not degrees
1171
				if ((int)strength > puttCount * 2)
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1172
				{
1173
					putter->go(Backwards);
1174
					puttCount++;
1175
				}
1176
			}
1177
			// make the visible steps at high strength smaller
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1178
			strokeCircle->setValue(pow(strength / maxStrength, 0.8) * 360); 
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
1179
		}
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1180
		else if (stroking)
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
1181
		{
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1182
			double al = strokeCircle->value(); 
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1183
			if (al >= 45)
1184
				al -= 0.2 + strength / 50 + al / 100;
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
1185
			else
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1186
				al -= 0.2 + strength / 50;
1187
96 by Dirk Mueller
--enable-final fixes
1188
			if (puttReverse)
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1189
			{
1190
				// show the stroke
1191
				puttCount--;
1192
				if (puttCount >= 0)
1193
					putter->go(Forwards);
1194
				else
1195
				{
96 by Dirk Mueller
--enable-final fixes
1196
					strokeCircle->setVisible(false);
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1197
					finishStroking = false;
1198
					putterTimer->stop();
1199
					putting = false;
1200
					stroking = false;
96 by Dirk Mueller
--enable-final fixes
1201
					shotStart();
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1202
				}
1203
			}
1204
			else if (al < -45 || finishStroking)
1205
			{
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1206
				strokeCircle->setValue(al); 
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1207
				int deg;
1208
				// if > 45 or < -45 then bad stroke
1209
				if (al > 45)
1210
				{
1211
					deg = putter->curDeg() - 45 + rand() % 90;
169 by Jason Katz-Brown
make putter use radians and not degrees
1212
					strength -= rand() % (int)strength;
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1213
				}
1214
				else if (!finishStroking)
1215
				{
1216
					deg = putter->curDeg() - 45 + rand() % 90;
169 by Jason Katz-Brown
make putter use radians and not degrees
1217
					strength -= rand() % (int)strength;
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1218
				}
1219
				else
169 by Jason Katz-Brown
make putter use radians and not degrees
1220
					deg = putter->curDeg() + (int)(strokeCircle->value() / 3);
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1221
1222
				if (deg < 0)
1223
					deg += 360;
1224
				else if (deg > 360)
1225
					deg -= 360;
1226
1227
				putter->setDeg(deg);
1228
				puttReverse = true;
96 by Dirk Mueller
--enable-final fixes
1229
			}
1230
			else
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1231
			{
1232
				strokeCircle->setValue(al);
550 by Laurent Montel
qt3support--
1233
				putterTimer->start(putterTimerMsec/10);
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1234
			}
1235
		}
96 by Dirk Mueller
--enable-final fixes
1236
	}
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1237
	else
1238
	{
1239
		if (putting)
1240
		{
1241
			putter->go(Backwards);
1242
			puttCount++;
1243
			strength += 1.5;
1244
			if (strength > maxStrength)
1245
			{
1246
				putting = false;
1247
				stroking = true;
1248
			}
1249
		}
1250
		else if (stroking)
1251
		{
1252
			if (putter->curLen() < (*curPlayer).ball()->height() + 2)
1253
			{
1254
				stroking = false;
1255
				putterTimer->stop();
1256
				putting = false;
1257
				stroking = false;
1258
				shotStart();
1259
			}
1260
1261
			putter->go(Forwards);
550 by Laurent Montel
qt3support--
1262
			putterTimer->start(putterTimerMsec/10);
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
1263
		}
1264
	}
1 by Jason Katz-Brown
here's kolf, read the TODO
1265
}
1266
1267
void KolfGame::autoSaveTimeout()
1268
{
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1269
	// this should be a config option
1270
	// until it is i'll disable it
70 by Jason Katz-Brown
undo shot! :-)
1271
	if (editing)
1272
	{
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
1273
		//save();
70 by Jason Katz-Brown
undo shot! :-)
1274
	}
1275
}
1276
1277
void KolfGame::recreateStateList()
1278
{
1016 by Stefan Majewsky
Kill StateDB class and CanvasItem::{load,save}State.
1279
	savedState.clear();
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1280
	foreach (QGraphicsItem* item, m_topLevelQItems)
70 by Jason Katz-Brown
undo shot! :-)
1281
	{
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1282
		if (dynamic_cast<Ball*>(item)) continue; //see below
1016 by Stefan Majewsky
Kill StateDB class and CanvasItem::{load,save}State.
1283
		CanvasItem* citem = dynamic_cast<CanvasItem*>(item);
70 by Jason Katz-Brown
undo shot! :-)
1284
		if (citem)
1285
		{
1016 by Stefan Majewsky
Kill StateDB class and CanvasItem::{load,save}State.
1286
			const QString key = makeStateGroup(citem->curId(), citem->name());
1287
			savedState.insert(key, item->pos());
70 by Jason Katz-Brown
undo shot! :-)
1288
		}
1289
	}
1290
1291
	ballStateList.clear();
1292
	for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
1293
		ballStateList.append((*it).stateInfo(curHole));
384 by Laurent Montel
Fix header
1294
175 by Jason Katz-Brown
add new Slope Practice course, clean up some code
1295
	ballStateList.canUndo = true;
70 by Jason Katz-Brown
undo shot! :-)
1296
}
1297
1298
void KolfGame::undoShot()
1299
{
175 by Jason Katz-Brown
add new Slope Practice course, clean up some code
1300
	if (ballStateList.canUndo)
1301
		loadStateList();
70 by Jason Katz-Brown
undo shot! :-)
1302
}
1303
1304
void KolfGame::loadStateList()
1305
{
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1306
	foreach (QGraphicsItem* item, m_topLevelQItems)
70 by Jason Katz-Brown
undo shot! :-)
1307
	{
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1308
		if (dynamic_cast<Ball*>(item)) continue; //see below
1016 by Stefan Majewsky
Kill StateDB class and CanvasItem::{load,save}State.
1309
		CanvasItem* citem = dynamic_cast<CanvasItem*>(item);
70 by Jason Katz-Brown
undo shot! :-)
1310
		if (citem)
1311
		{
1016 by Stefan Majewsky
Kill StateDB class and CanvasItem::{load,save}State.
1312
			const QString key = makeStateGroup(citem->curId(), citem->name());
1313
			const QPointF currentPos = item->pos();
1314
			const QPointF posDiff = savedState.value(key, currentPos) - currentPos;
1315
			citem->moveBy(posDiff.x(), posDiff.y());
70 by Jason Katz-Brown
undo shot! :-)
1316
		}
1317
	}
1318
1319
	for (BallStateList::Iterator it = ballStateList.begin(); it != ballStateList.end(); ++it)
1320
	{
1321
		BallStateInfo info = (*it);
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1322
		Player &player = (*(players->begin() + (info.id - 1) ));
1323
		player.ball()->setPos(info.spot.x(), info.spot.y());
268 by Jason Katz-Brown
make kolf not totally broken
1324
		player.ball()->setBeginningOfHole(info.beginningOfHole);
70 by Jason Katz-Brown
undo shot! :-)
1325
		if ((*curPlayer).id() == info.id)
1326
			ballMoved();
97 by Jason Katz-Brown
good stuff
1327
		else
1328
			player.ball()->setVisible(!info.beginningOfHole);
70 by Jason Katz-Brown
undo shot! :-)
1329
		player.setScoreForHole(info.score, curHole);
1330
		player.ball()->setState(info.state);
1331
		emit scoreChanged(info.id, curHole, info.score);
1332
	}
1 by Jason Katz-Brown
here's kolf, read the TODO
1333
}
1334
1335
void KolfGame::shotDone()
1336
{
70 by Jason Katz-Brown
undo shot! :-)
1337
	inPlay = false;
1338
	emit inPlayEnd();
1 by Jason Katz-Brown
here's kolf, read the TODO
1339
	setFocus();
1340
1341
	Ball *ball = (*curPlayer).ball();
1342
328 by Jason Katz-Brown
fix max strokes stuff
1343
	if (!dontAddStroke && (*curPlayer).numHoles())
1344
		(*curPlayer).addStrokeToHole(curHole);
100 by Jason Katz-Brown
make the game end if there's no competition, make it work better when putter is showing and ball goes into hole or puddle
1345
1346
	dontAddStroke = false;
1 by Jason Katz-Brown
here's kolf, read the TODO
1347
1348
	// do hack stuff, shouldn't be done here
1349
5 by Jason Katz-Brown
1350
	for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
1351
	{
1352
		if ((*it).ball()->addStroke())
1353
		{
1354
			for (int i = 1; i <= (*it).ball()->addStroke(); ++i)
1355
				(*it).addStrokeToHole(curHole);
56 by Jason Katz-Brown
new cup graphic, better slope arrows
1356
5 by Jason Katz-Brown
1357
			// emit that we have a new stroke count
1358
			emit scoreChanged((*it).id(), curHole, (*it).score(curHole));
1359
		}
1360
		(*it).ball()->setAddStroke(0);
1361
	}
1362
88 by Jason Katz-Brown
make independent ball moving more feasible. There might still be a few bugs in the implementation -- it's messy as hell!
1363
	for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
1 by Jason Katz-Brown
here's kolf, read the TODO
1364
	{
192 by Jason Katz-Brown
fix bad typo
1365
		Ball *ball = (*it).ball();
1366
1367
		if (ball->curState() == Holed)
94 by Jason Katz-Brown
fix lotsa bugs in states of ball, convert more stuff to vectors
1368
			continue;
1369
1025 by Stefan Majewsky
Kill Ball::vector property.
1370
		Vector oldVelocity;
1371
		if (ball->placeOnGround(oldVelocity))
1 by Jason Katz-Brown
here's kolf, read the TODO
1372
		{
192 by Jason Katz-Brown
fix bad typo
1373
			ball->setPlaceOnGround(false);
1374
1375
			QStringList options;
344 by Stephan Binner
CVS_SILENT Style guide text fix, use "cvslastchange" or X-WebCVS header to view
1376
			const QString placeOutside = i18n("Drop Outside of Hazard");
1377
			const QString rehit = i18n("Rehit From Last Location");
192 by Jason Katz-Brown
fix bad typo
1378
			options << placeOutside << rehit;
568 by Chusslove Illich
Conversion to new i18n API (see KDE4PORTING.html->I18N->i18n calls).
1379
			const QString choice = KComboBoxDialog::getItem(i18n("What would you like to do for your next shot?"), i18n("%1 is in a Hazard", (*it).name()), options, placeOutside, "hazardOptions");
192 by Jason Katz-Brown
fix bad typo
1380
1381
			if (choice == placeOutside)
1382
			{
1383
				(*it).ball()->setDoDetect(false);
1384
1025 by Stefan Majewsky
Kill Ball::vector property.
1385
				QPointF pos = ball->pos();
1386
				//normalize old velocity
1387
				const QPointF v = oldVelocity / oldVelocity.magnitude();
192 by Jason Katz-Brown
fix bad typo
1388
1389
				while (1)
1390
				{
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1391
					QList<QGraphicsItem *> list = ball->collidingItems();
192 by Jason Katz-Brown
fix bad typo
1392
					bool keepMoving = false;
1393
					while (!list.isEmpty())
1394
					{
1025 by Stefan Majewsky
Kill Ball::vector property.
1395
						QGraphicsItem *item = list.takeFirst();
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1396
						if (item->data(0) == Rtti_DontPlaceOn)
192 by Jason Katz-Brown
fix bad typo
1397
							keepMoving = true;
1398
					}
1399
					if (!keepMoving)
1400
						break;
1401
1025 by Stefan Majewsky
Kill Ball::vector property.
1402
					const qreal movePixel = 3.0;
1403
					pos -= v * movePixel;
1404
					ball->setPos(pos);
192 by Jason Katz-Brown
fix bad typo
1405
				}
1406
			}
1407
			else if (choice == rehit)
1408
			{
1409
				for (BallStateList::Iterator it = ballStateList.begin(); it != ballStateList.end(); ++it)
1410
				{
1411
					if ((*it).id == (*curPlayer).id())
1412
					{
1413
						if ((*it).beginningOfHole)
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1414
							ball->setPos(whiteBall->x(), whiteBall->y());
192 by Jason Katz-Brown
fix bad typo
1415
						else
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1416
							ball->setPos((*it).spot.x(), (*it).spot.y());
192 by Jason Katz-Brown
fix bad typo
1417
1418
						break;
1419
					}
1420
				}
1421
			}
88 by Jason Katz-Brown
make independent ball moving more feasible. There might still be a few bugs in the implementation -- it's messy as hell!
1422
1 by Jason Katz-Brown
here's kolf, read the TODO
1423
			ball->setVisible(true);
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1424
			ball->setState(Stopped); 
97 by Jason Katz-Brown
good stuff
1425
1426
			(*it).ball()->setDoDetect(true);
1024 by Stefan Majewsky
Remove all ball-wall and ball-ball collision code.
1427
			ball->collisionDetect();
1 by Jason Katz-Brown
here's kolf, read the TODO
1428
		}
1429
	}
96 by Dirk Mueller
--enable-final fixes
1430
5 by Jason Katz-Brown
1431
	// emit again
1 by Jason Katz-Brown
here's kolf, read the TODO
1432
	emit scoreChanged((*curPlayer).id(), curHole, (*curPlayer).score(curHole));
96 by Dirk Mueller
--enable-final fixes
1433
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1434
	if(ball->curState() == Rolling) {
1435
		inPlay = true; 
1436
		return;
1437
	}
1438
987 by Stefan Majewsky
Convert all velocity getters/setters members to Vector class.
1439
	ball->setVelocity(Vector());
1 by Jason Katz-Brown
here's kolf, read the TODO
1440
91 by Jason Katz-Brown
add real ball bouncing physics.
1441
	for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
1 by Jason Katz-Brown
here's kolf, read the TODO
1442
	{
91 by Jason Katz-Brown
add real ball bouncing physics.
1443
		Ball *ball = (*it).ball();
1 by Jason Katz-Brown
here's kolf, read the TODO
1444
176 by Jason Katz-Brown
add icons to desktop files
1445
		int curStrokes = (*it).score(curHole);
103 by Jason Katz-Brown
scoreboard par changing bugfix
1446
		if (curStrokes >= holeInfo.maxStrokes() && holeInfo.hasMaxStrokes())
1 by Jason Katz-Brown
here's kolf, read the TODO
1447
		{
91 by Jason Katz-Brown
add real ball bouncing physics.
1448
			ball->setState(Holed);
1449
			ball->setVisible(false);
1450
328 by Jason Katz-Brown
fix max strokes stuff
1451
			// move to center in case he/she hit out
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1452
			ball->setPos(width / 2, height / 2);
328 by Jason Katz-Brown
fix max strokes stuff
1453
			playerWhoMaxed = (*it).name();
1454
91 by Jason Katz-Brown
add real ball bouncing physics.
1455
			if (allPlayersDone())
1456
			{
192 by Jason Katz-Brown
fix bad typo
1457
				startNextHole();
328 by Jason Katz-Brown
fix max strokes stuff
1458
				QTimer::singleShot(100, this, SLOT(emitMax()));
91 by Jason Katz-Brown
add real ball bouncing physics.
1459
				return;
1460
			}
328 by Jason Katz-Brown
fix max strokes stuff
1461
1462
			QTimer::singleShot(100, this, SLOT(emitMax()));
1 by Jason Katz-Brown
here's kolf, read the TODO
1463
		}
1464
	}
1465
1466
	// change player to next player
1467
	// skip player if he's Holed
1468
	do
1469
	{
1470
		curPlayer++;
1471
		if (curPlayer == players->end())
1472
			curPlayer = players->begin();
1473
	}
1474
	while ((*curPlayer).ball()->curState() == Holed);
1475
1476
	emit newPlayersTurn(&(*curPlayer));
1477
1478
	(*curPlayer).ball()->setVisible(true);
30 by Jason Katz-Brown
elliptical slopes!! and other things!
1479
759 by Paul Broadbent
fixed bug with game hanging when balls collide by being placed ontop of each other when dropping outside the hazard and a bug where the putter can get into the wrong place
1480
	inPlay = false;
1024 by Stefan Majewsky
Remove all ball-wall and ball-ball collision code.
1481
	(*curPlayer).ball()->collisionDetect();
759 by Paul Broadbent
fixed bug with game hanging when balls collide by being placed ontop of each other when dropping outside the hazard and a bug where the putter can get into the wrong place
1482
169 by Jason Katz-Brown
make putter use radians and not degrees
1483
	putter->setAngle((*curPlayer).ball());
1 by Jason Katz-Brown
here's kolf, read the TODO
1484
	putter->setOrigin((*curPlayer).ball()->x(), (*curPlayer).ball()->y());
30 by Jason Katz-Brown
elliptical slopes!! and other things!
1485
	updateMouse();
1 by Jason Katz-Brown
here's kolf, read the TODO
1486
}
1487
328 by Jason Katz-Brown
fix max strokes stuff
1488
void KolfGame::emitMax()
1489
{
1490
	emit maxStrokesReached(playerWhoMaxed);
1491
}
1492
1025 by Stefan Majewsky
Kill Ball::vector property.
1493
void KolfGame::startBall(const Vector &velocity)
175 by Jason Katz-Brown
add new Slope Practice course, clean up some code
1494
{
304 by Jason Katz-Brown
play all of the new sounds, make blackholes spit out a little after the entrance
1495
	playSound("hit");
1496
175 by Jason Katz-Brown
add new Slope Practice course, clean up some code
1497
	emit inPlayStart();
1498
	putter->setVisible(false);
1499
1500
	(*curPlayer).ball()->setState(Rolling);
1025 by Stefan Majewsky
Kill Ball::vector property.
1501
	(*curPlayer).ball()->setVelocity(velocity);
760 by Paul Broadbent
fixed bug where is game is resized the ball could wrongly think it is in a puddle at the start of a hole and made it so that the ball cannot bounce on bumpers forever
1502
	(*curPlayer).ball()->shotStarted();
175 by Jason Katz-Brown
add new Slope Practice course, clean up some code
1503
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1504
	foreach (QGraphicsItem* qitem, m_topLevelQItems)
175 by Jason Katz-Brown
add new Slope Practice course, clean up some code
1505
	{
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1506
		CanvasItem *citem = dynamic_cast<CanvasItem *>(qitem);
175 by Jason Katz-Brown
add new Slope Practice course, clean up some code
1507
		if (citem)
1508
			citem->shotStarted();
1509
	}
1510
1511
	inPlay = true;
1512
}
1513
1 by Jason Katz-Brown
here's kolf, read the TODO
1514
void KolfGame::shotStart()
1515
{
454 by Jason Katz-Brown
My first commit in months! Fix a few kolf bugs: slope block, winner dialog, ball api with add strokes, mouse clicking to skip holes.
1516
	// ensure we never hit the ball back into the hole which
1517
	// can cause hole skippage
1518
	if ((*curPlayer).ball()->curState() == Holed)
1519
		return;
1520
70 by Jason Katz-Brown
undo shot! :-)
1521
	// save state
1522
	recreateStateList();
1523
169 by Jason Katz-Brown
make putter use radians and not degrees
1524
	putter->saveAngle((*curPlayer).ball());
1 by Jason Katz-Brown
here's kolf, read the TODO
1525
	strength /= 8;
36 by Jason Katz-Brown
bumpers! super-fun. other fixes.
1526
	if (!strength)
1527
		strength = 1;
175 by Jason Katz-Brown
add new Slope Practice course, clean up some code
1528
775 by Paul Broadbent
minor tweaks to wall collisions, problems fixed?
1529
	//kDebug(12007) << "Start started. BallX:" << (*curPlayer).ball()->x() << ", BallY:" << (*curPlayer).ball()->y() << ", Putter Angle:" << putter->curAngle() << ", Vector Strength: " << strength;
1530
1024 by Stefan Majewsky
Remove all ball-wall and ball-ball collision code.
1531
	(*curPlayer).ball()->collisionDetect();
1532
1025 by Stefan Majewsky
Kill Ball::vector property.
1533
	startBall(Vector::fromMagnitudeDirection(strength, -(putter->curAngle() + M_PI)));
175 by Jason Katz-Brown
add new Slope Practice course, clean up some code
1534
1535
	addHoleInfo(ballStateList);
1536
}
1537
1538
void KolfGame::addHoleInfo(BallStateList &list)
1539
{
1540
	list.player = (*curPlayer).id();
1025 by Stefan Majewsky
Kill Ball::vector property.
1541
	list.vector = (*curPlayer).ball()->velocity();
175 by Jason Katz-Brown
add new Slope Practice course, clean up some code
1542
	list.hole = curHole;
1 by Jason Katz-Brown
here's kolf, read the TODO
1543
}
1544
192 by Jason Katz-Brown
fix bad typo
1545
void KolfGame::sayWhosGoing()
1546
{
1547
	if (players->count() >= 2)
1548
	{
568 by Chusslove Illich
Conversion to new i18n API (see KDE4PORTING.html->I18N->i18n calls).
1549
		KMessageBox::information(this, i18n("%1 will start off.", (*curPlayer).name()), i18n("New Hole"), "newHole");
192 by Jason Katz-Brown
fix bad typo
1550
	}
1551
}
1552
1 by Jason Katz-Brown
here's kolf, read the TODO
1553
void KolfGame::holeDone()
1554
{
283 by Jason Katz-Brown
play holed.wav, make hole-ending sounds get played
1555
	for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
1556
		(*it).ball()->setVisible(false);
192 by Jason Katz-Brown
fix bad typo
1557
	startNextHole();
1558
	sayWhosGoing();
1559
}
1560
1561
// this function is WAY too smart for it's own good
1562
// ie, bad design :-(
1563
void KolfGame::startNextHole()
1564
{
1 by Jason Katz-Brown
here's kolf, read the TODO
1565
	setFocus();
1566
24 by Jason Katz-Brown
1567
	bool reset = true;
1568
	if (askSave(true))
1569
	{
1570
		if (allPlayersDone())
1571
		{
1572
			// we'll reload this hole, but not reset
1573
			curHole--;
1574
			reset = false;
1575
		}
1576
		else
1577
			return;
1578
	}
1579
	else
301 by Jason Katz-Brown
fix up, reenable charles's code, bugs.. etc
1580
		setModified(false);
24 by Jason Katz-Brown
1581
169 by Jason Katz-Brown
make putter use radians and not degrees
1582
	pause();
1583
100 by Jason Katz-Brown
make the game end if there's no competition, make it work better when putter is showing and ball goes into hole or puddle
1584
	dontAddStroke = false;
1585
1 by Jason Katz-Brown
here's kolf, read the TODO
1586
	inPlay = false;
1587
	timer->stop();
169 by Jason Katz-Brown
make putter use radians and not degrees
1588
	putter->resetAngles();
1 by Jason Katz-Brown
here's kolf, read the TODO
1589
1590
	int oldCurHole = curHole;
1591
	curHole++;
259 by Neil Stevens
Now the newHoleAction shows the current hole
1592
	emit currentHole(curHole);
1 by Jason Katz-Brown
here's kolf, read the TODO
1593
24 by Jason Katz-Brown
1594
	if (reset)
30 by Jason Katz-Brown
elliptical slopes!! and other things!
1595
	{
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1596
		whiteBall->setPos(width/2, height/2);
30 by Jason Katz-Brown
elliptical slopes!! and other things!
1597
		holeInfo.borderWallsChanged(true);
1598
	}
56 by Jason Katz-Brown
new cup graphic, better slope arrows
1599
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
1600
	int leastScore = INT_MAX;
56 by Jason Katz-Brown
new cup graphic, better slope arrows
1601
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
1602
	// to get the first player to go first on every hole,
1603
	// don't do the score stuff below
1604
	curPlayer = players->begin();
384 by Laurent Montel
Fix header
1605
1 by Jason Katz-Brown
here's kolf, read the TODO
1606
	for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
1607
	{
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
1608
		if (curHole > 1)
1609
		{
192 by Jason Katz-Brown
fix bad typo
1610
			bool ahead = false;
1611
			if ((*it).lastScore() != 0)
1612
			{
1613
				if ((*it).lastScore() < leastScore)
1614
					ahead = true;
1615
				else if ((*it).lastScore() == leastScore)
1616
				{
1617
					for (int i = curHole - 1; i > 0; --i)
1618
					{
651 by Paul Broadbent
some minor bug fixes
1619
						while(i > (*it).scores().size())
1620
							i--;
1621
192 by Jason Katz-Brown
fix bad typo
1622
						const int thisScore = (*it).score(i);
1623
						const int thatScore = (*curPlayer).score(i);
1624
						if (thisScore < thatScore)
1625
						{
1626
							ahead = true;
1627
							break;
1628
						}
1629
						else if (thisScore > thatScore)
1630
							break;
1631
					}
1632
				}
1633
			}
1634
1635
			if (ahead)
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
1636
			{
1637
				curPlayer = it;
1638
				leastScore = (*it).lastScore();
1639
			}
1640
		}
1641
24 by Jason Katz-Brown
1642
		if (reset)
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1643
			(*it).ball()->setPos(width / 2, height / 2);
24 by Jason Katz-Brown
1644
		else
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1645
			(*it).ball()->setPos(whiteBall->x(), whiteBall->y());
24 by Jason Katz-Brown
1646
1 by Jason Katz-Brown
here's kolf, read the TODO
1647
		(*it).ball()->setState(Stopped);
173 by Jason Katz-Brown
clean up a little bit
1648
21 by Jason Katz-Brown
fix bug where editing made ball's visibility isn't right when toggling editing at start of hole
1649
		// this gets set to false when the ball starts
1650
		// to move by the Mr. Ball himself.
1651
		(*it).ball()->setBeginningOfHole(true);
150 by Jason Katz-Brown
1652
		if ((int)(*it).scores().count() < curHole)
1653
			(*it).addHole();
987 by Stefan Majewsky
Convert all velocity getters/setters members to Vector class.
1654
		(*it).ball()->setVelocity(Vector());
7 by Jason Katz-Brown
1655
		(*it).ball()->setVisible(false);
1 by Jason Katz-Brown
here's kolf, read the TODO
1656
	}
1657
1658
	emit newPlayersTurn(&(*curPlayer));
96 by Dirk Mueller
--enable-final fixes
1659
24 by Jason Katz-Brown
1660
	if (reset)
1661
		openFile();
1 by Jason Katz-Brown
here's kolf, read the TODO
1662
1663
	inPlay = false;
1664
	timer->start(timerMsec);
1665
760 by Paul Broadbent
fixed bug where is game is resized the ball could wrongly think it is in a puddle at the start of a hole and made it so that the ball cannot bounce on bumpers forever
1666
	if(size().width()!=400 || size().height()!=400) { //not default size, so resizing needed
1003 by Stefan Majewsky
Kill RectItem class and newSize() methods.
1667
		int setSize = qMin(size().width(), size().height());
1668
		//resize needs to be called for setSize+1 first because otherwise it doesn't seem to get called (not sure why)
1669
		QGraphicsView::resize(setSize+1, setSize+1);
1670
		QGraphicsView::resize(setSize, setSize);
760 by Paul Broadbent
fixed bug where is game is resized the ball could wrongly think it is in a puddle at the start of a hole and made it so that the ball cannot bounce on bumpers forever
1671
	}
1672
133 by Jason Katz-Brown
1673
	// if (false) { we're done with the round! }
1 by Jason Katz-Brown
here's kolf, read the TODO
1674
	if (oldCurHole != curHole)
1675
	{
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1676
		for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it) {
133 by Jason Katz-Brown
1677
			(*it).ball()->setPlaceOnGround(false);
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1678
			while( (*it).numHoles() < (unsigned)curHole)
1679
				(*it).addHole();
1680
		}
133 by Jason Katz-Brown
1681
1 by Jason Katz-Brown
here's kolf, read the TODO
1682
		// here we have to make sure the scoreboard shows
1683
		// all of the holes up until now;
1684
1685
		for (; scoreboardHoles < curHole; ++scoreboardHoles)
1686
		{
709 by Stephan Kulow
don't leak _that_ bad (CID 3637)
1687
			cfgGroup = KConfigGroup(cfg->group(QString("%1-hole@-50,-50|0").arg(scoreboardHoles + 1)));
710 by Stephan Kulow
fixing my commit - earning dartstars like mad
1688
			emit newHole(cfgGroup.readEntry("par", 3));
1 by Jason Katz-Brown
here's kolf, read the TODO
1689
		}
4 by Jason Katz-Brown
1690
1691
		resetHoleScores();
201 by Jason Katz-Brown
good fixes, black holes accept harder ball speeds, and most important new Show Info toggle action
1692
		updateShowInfo();
5 by Jason Katz-Brown
1693
97 by Jason Katz-Brown
good stuff
1694
		// this is from shotDone()
5 by Jason Katz-Brown
1695
		(*curPlayer).ball()->setVisible(true);
1696
		putter->setOrigin((*curPlayer).ball()->x(), (*curPlayer).ball()->y());
30 by Jason Katz-Brown
elliptical slopes!! and other things!
1697
		updateMouse();
38 by Jason Katz-Brown
1698
175 by Jason Katz-Brown
add new Slope Practice course, clean up some code
1699
		ballStateList.canUndo = false;
97 by Jason Katz-Brown
good stuff
1700
1024 by Stefan Majewsky
Remove all ball-wall and ball-ball collision code.
1701
		(*curPlayer).ball()->collisionDetect();
1 by Jason Katz-Brown
here's kolf, read the TODO
1702
	}
384 by Laurent Montel
Fix header
1703
169 by Jason Katz-Brown
make putter use radians and not degrees
1704
	unPause();
1 by Jason Katz-Brown
here's kolf, read the TODO
1705
}
1706
1707
void KolfGame::showInfoDlg(bool addDontShowAgain)
1708
{
78 by Jason Katz-Brown
KOLF HAS PLUGINS! yay :-)
1709
	KMessageBox::information(parentWidget(),
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1710
			i18n("Course name: %1", holeInfo.name()) + QString("\n")
1711
			+ i18n("Created by %1", holeInfo.author()) + QString("\n")
1712
			+ i18n("%1 holes", highestHole),
1713
			i18n("Course Information"),
684 by Matt Williams
kblackbox, kbounce, kgoldrunner, kmahjongg, knetwalk, kolf, kpat and kshisen EBN fixes
1714
			addDontShowAgain? holeInfo.name() + QString(" ") + holeInfo.author() : QString());
1 by Jason Katz-Brown
here's kolf, read the TODO
1715
}
1716
1717
void KolfGame::openFile()
1718
{
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1719
	QList<QGraphicsItem*> newTopLevelQItems;
1720
	foreach (QGraphicsItem* qitem, m_topLevelQItems)
38 by Jason Katz-Brown
1721
	{
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1722
		if (dynamic_cast<Ball*>(qitem))
1723
		{
1724
			//do not delete balls
1725
			newTopLevelQItems << qitem;
1726
			continue;
1727
		}
1728
		CanvasItem *citem = dynamic_cast<CanvasItem *>(qitem);
38 by Jason Katz-Brown
1729
		if (citem)
1730
		{
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1731
			delete citem;
38 by Jason Katz-Brown
1732
		}
1733
	}
1734
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1735
	m_moveableQItems = m_topLevelQItems = newTopLevelQItems;
36 by Jason Katz-Brown
bumpers! super-fun. other fixes.
1736
	selectedItem = 0;
1 by Jason Katz-Brown
here's kolf, read the TODO
1737
38 by Jason Katz-Brown
1738
	// will tell basic course info
1739
	// we do this here for the hell of it.
1740
	// there is no fake id, by the way,
1741
	// because it's old and when i added ids i forgot to change it.
709 by Stephan Kulow
don't leak _that_ bad (CID 3637)
1742
	cfgGroup = KConfigGroup(cfg->group(QString("0-course@-50,-50")));
710 by Stephan Kulow
fixing my commit - earning dartstars like mad
1743
	holeInfo.setAuthor(cfgGroup.readEntry("author", holeInfo.author()));
1744
	holeInfo.setName(cfgGroup.readEntry("Name", holeInfo.name()));
1745
	holeInfo.setUntranslatedName(cfgGroup.readEntryUntranslated("Name", holeInfo.untranslatedName()));
73 by Jason Katz-Brown
make puddles place your ball on the right spot again
1746
	emit titleChanged(holeInfo.name());
38 by Jason Katz-Brown
1747
709 by Stephan Kulow
don't leak _that_ bad (CID 3637)
1748
	cfgGroup = KConfigGroup(KSharedConfig::openConfig(filename), QString("%1-hole@-50,-50|0").arg(curHole));
710 by Stephan Kulow
fixing my commit - earning dartstars like mad
1749
	curPar = cfgGroup.readEntry("par", 3);
38 by Jason Katz-Brown
1750
	holeInfo.setPar(curPar);
710 by Stephan Kulow
fixing my commit - earning dartstars like mad
1751
	holeInfo.borderWallsChanged(cfgGroup.readEntry("borderWalls", holeInfo.borderWalls()));
1752
	holeInfo.setMaxStrokes(cfgGroup.readEntry("maxstrokes", 10));
1 by Jason Katz-Brown
here's kolf, read the TODO
1753
342 by Jason Katz-Brown
make the dialog for telling that plugins aren't show a list, instead of popping up multiple times
1754
	QStringList missingPlugins;
925 by Ian Wadham
Fix the regression in hole-data loading that was causing Kolf to fail miserably after hole 1 on any course.
1755
1756
	// The "for" loop depends on the list of groups being in sorted order.
1757
	QStringList groups = cfg->groupList();
1758
	groups.sort();
1 by Jason Katz-Brown
here's kolf, read the TODO
1759
1760
	int numItems = 0;
28 by Jason Katz-Brown
various stuff.. fixes mostly
1761
	int _highestHole = 0;
1 by Jason Katz-Brown
here's kolf, read the TODO
1762
927 by Laurent Montel
iterator fix
1763
	for (QStringList::const_iterator it = groups.constBegin(); it != groups.constEnd(); ++it)
1 by Jason Katz-Brown
here's kolf, read the TODO
1764
	{
925 by Ian Wadham
Fix the regression in hole-data loading that was causing Kolf to fail miserably after hole 1 on any course.
1765
		// Format of group name is [<holeNum>-<name>@<x>,<y>|<id>]
709 by Stephan Kulow
don't leak _that_ bad (CID 3637)
1766
		cfgGroup = KConfigGroup(cfg->group(*it));
1 by Jason Katz-Brown
here's kolf, read the TODO
1767
54 by Jason Katz-Brown
get rid of makgroup stuff in objects (improved design), optimize floaters
1768
		const int len = (*it).length();
571 by Dmitry Suzdalev
deprecated--
1769
		const int dashIndex = (*it).indexOf("-");
54 by Jason Katz-Brown
get rid of makgroup stuff in objects (improved design), optimize floaters
1770
		const int holeNum = (*it).left(dashIndex).toInt();
28 by Jason Katz-Brown
various stuff.. fixes mostly
1771
		if (holeNum > _highestHole)
1772
			_highestHole = holeNum;
1 by Jason Katz-Brown
here's kolf, read the TODO
1773
571 by Dmitry Suzdalev
deprecated--
1774
		const int atIndex = (*it).indexOf("@");
54 by Jason Katz-Brown
get rid of makgroup stuff in objects (improved design), optimize floaters
1775
		const QString name = (*it).mid(dashIndex + 1, atIndex - (dashIndex + 1));
96 by Dirk Mueller
--enable-final fixes
1776
1 by Jason Katz-Brown
here's kolf, read the TODO
1777
		if (holeNum != curHole)
1778
		{
925 by Ian Wadham
Fix the regression in hole-data loading that was causing Kolf to fail miserably after hole 1 on any course.
1779
			// Break before reading all groups, if the highest hole
1780
			// number is known and all items in curHole are done.
28 by Jason Katz-Brown
various stuff.. fixes mostly
1781
			if (numItems && !recalcHighestHole)
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1782
				break;
1 by Jason Katz-Brown
here's kolf, read the TODO
1783
			continue;
1784
		}
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
1785
		numItems++;
96 by Dirk Mueller
--enable-final fixes
1786
1 by Jason Katz-Brown
here's kolf, read the TODO
1787
571 by Dmitry Suzdalev
deprecated--
1788
		const int commaIndex = (*it).indexOf(",");
1789
		const int pipeIndex = (*it).indexOf("|");
54 by Jason Katz-Brown
get rid of makgroup stuff in objects (improved design), optimize floaters
1790
		const int x = (*it).mid(atIndex + 1, commaIndex - (atIndex + 1)).toInt();
1791
		const int y = (*it).mid(commaIndex + 1, pipeIndex - (commaIndex + 1)).toInt();
1 by Jason Katz-Brown
here's kolf, read the TODO
1792
1793
		// will tell where ball is
1794
		if (name == "ball")
1795
		{
1796
			for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1797
				(*it).ball()->setPos(x, y);
1798
			whiteBall->setPos(x, y);
1 by Jason Katz-Brown
here's kolf, read the TODO
1799
			continue;
1800
		}
1801
54 by Jason Katz-Brown
get rid of makgroup stuff in objects (improved design), optimize floaters
1802
		const int id = (*it).right(len - (pipeIndex + 1)).toInt();
1 by Jason Katz-Brown
here's kolf, read the TODO
1803
1021 by Stefan Majewsky
Create a Box2D world, and attach Box2D bodies to all CanvasItems.
1804
		QGraphicsItem* newItem = m_factory.createInstance(name, courseBoard, g_world);
983 by Stefan Majewsky
Replace the Object classes by the new ItemFactory.
1805
		if (newItem)
1 by Jason Katz-Brown
here's kolf, read the TODO
1806
		{
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1807
			m_topLevelQItems << newItem;
1808
			m_moveableQItems << newItem;
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1809
			CanvasItem *sceneItem = dynamic_cast<CanvasItem *>(newItem);
1 by Jason Katz-Brown
here's kolf, read the TODO
1810
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1811
			if (!sceneItem)
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
1812
				continue;
54 by Jason Katz-Brown
get rid of makgroup stuff in objects (improved design), optimize floaters
1813
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1814
			sceneItem->setId(id);
1815
			sceneItem->setGame(this);
1816
			sceneItem->editModeChanged(editing);
983 by Stefan Majewsky
Replace the Object classes by the new ItemFactory.
1817
			sceneItem->setName(name);
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1818
			m_moveableQItems.append(sceneItem->moveableItems());
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1819
1076 by Stefan Majewsky
Fix loading of windmills.
1820
			sceneItem->setPosition(QPointF(x, y));
39 by Jason Katz-Brown
cool cursors, sequential loading
1821
			newItem->setVisible(true);
1822
18 by Jason Katz-Brown
change some things, make course better, document CanvasItem sorta
1823
			// make things actually show
1065 by Stefan Majewsky
Remove a big bunch of unused methods from CanvasItem.
1824
			cfgGroup = KConfigGroup(cfg->group(makeGroup(id, curHole, sceneItem->name(), x, y)));
1825
			sceneItem->load(&cfgGroup);
1 by Jason Katz-Brown
here's kolf, read the TODO
1826
		}
983 by Stefan Majewsky
Replace the Object classes by the new ItemFactory.
1827
		else if (name != "hole" && !missingPlugins.contains(name))
342 by Jason Katz-Brown
make the dialog for telling that plugins aren't show a list, instead of popping up multiple times
1828
			missingPlugins.append(name);
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1829
342 by Jason Katz-Brown
make the dialog for telling that plugins aren't show a list, instead of popping up multiple times
1830
	}
1831
1832
	if (!missingPlugins.empty())
1833
	{
886 by Mauricio Piacentini
Fixing previous commit so that it is translatable. This is an error
1834
		KMessageBox::informationList(this, QString("<p>") + i18n("This hole uses the following plugins, which you do not have installed:") + QString("</p>"), missingPlugins, QString(), QString("%1 warning").arg(holeInfo.untranslatedName() + QString::number(curHole)));
1 by Jason Katz-Brown
here's kolf, read the TODO
1835
	}
1836
205 by Jason Katz-Brown
stuff
1837
	lastDelId = -1;
1838
1 by Jason Katz-Brown
here's kolf, read the TODO
1839
	// if it's the first hole let's not
100 by Jason Katz-Brown
make the game end if there's no competition, make it work better when putter is showing and ball goes into hole or puddle
1840
	if (!numItems && curHole > 1 && !addingNewHole && curHole >= _highestHole)
1 by Jason Katz-Brown
here's kolf, read the TODO
1841
	{
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
1842
		// we're done, let's quit
1 by Jason Katz-Brown
here's kolf, read the TODO
1843
		curHole--;
1844
		pause();
1845
		emit holesDone();
38 by Jason Katz-Brown
1846
1847
		// tidy things up
1848
		setBorderWalls(false);
1849
		clearHole();
301 by Jason Katz-Brown
fix up, reenable charles's code, bugs.. etc
1850
		setModified(false);
38 by Jason Katz-Brown
1851
		for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
1852
			(*it).ball()->setVisible(false);
1853
1 by Jason Katz-Brown
here's kolf, read the TODO
1854
		return;
1855
	}
1856
39 by Jason Katz-Brown
cool cursors, sequential loading
1857
	// do it down here; if !hasFinalLoad, do it up there!
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1858
	//QGraphicsItem *qsceneItem = 0;
1859
	QList<QGraphicsItem *>::const_iterator qsceneItem;
1860
	QList<CanvasItem *> todo;
1861
	QList<QGraphicsItem *> qtodo;
39 by Jason Katz-Brown
cool cursors, sequential loading
1862
132 by Jason Katz-Brown
1863
	if (curHole > _highestHole)
1864
		_highestHole = curHole;
1 by Jason Katz-Brown
here's kolf, read the TODO
1865
28 by Jason Katz-Brown
various stuff.. fixes mostly
1866
	if (recalcHighestHole)
1867
	{
1868
		highestHole = _highestHole;
1869
		recalcHighestHole = false;
133 by Jason Katz-Brown
1870
		emit largestHole(highestHole);
28 by Jason Katz-Brown
various stuff.. fixes mostly
1871
	}
38 by Jason Katz-Brown
1872
1873
	if (curHole == 1 && !filename.isNull() && !infoShown)
1874
	{
59 by Jason Katz-Brown
a spiffy newgame dialog
1875
		// let's not now, because they see it when they choose course
1876
		//showInfoDlg(true);
38 by Jason Katz-Brown
1877
		infoShown = true;
1878
	}
1879
301 by Jason Katz-Brown
fix up, reenable charles's code, bugs.. etc
1880
	setModified(false);
1 by Jason Katz-Brown
here's kolf, read the TODO
1881
}
1882
983 by Stefan Majewsky
Replace the Object classes by the new ItemFactory.
1883
void KolfGame::addNewObject(const QString& identifier)
1 by Jason Katz-Brown
here's kolf, read the TODO
1884
{
1021 by Stefan Majewsky
Create a Box2D world, and attach Box2D bodies to all CanvasItems.
1885
	QGraphicsItem *newItem = m_factory.createInstance(identifier, courseBoard, g_world);
636 by Paul Broadbent
first steps towards SVG graphics
1886
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1887
	m_topLevelQItems << newItem;
1888
	m_moveableQItems << newItem;
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1889
	if(!newItem->isVisible())
1890
		newItem->setVisible(true);
1 by Jason Katz-Brown
here's kolf, read the TODO
1891
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1892
	CanvasItem *sceneItem = dynamic_cast<CanvasItem *>(newItem);
1893
	if (!sceneItem)
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
1894
		return;
38 by Jason Katz-Brown
1895
205 by Jason Katz-Brown
stuff
1896
	// we need to find a number that isn't taken
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1897
	int i = lastDelId > 0? lastDelId : m_topLevelQItems.count() - 30;
205 by Jason Katz-Brown
stuff
1898
	if (i <= 0)
1899
		i = 0;
1900
1901
	for (;; ++i)
1902
	{
206 by Jason Katz-Brown
fixes in courses - impossible lookin' goood.. and it's very difficult, I just got majorly over par on not such a bad round
1903
		bool found = false;
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1904
		foreach (QGraphicsItem* qitem, m_topLevelQItems)
205 by Jason Katz-Brown
stuff
1905
		{
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1906
			CanvasItem *citem = dynamic_cast<CanvasItem *>(qitem);
205 by Jason Katz-Brown
stuff
1907
			if (citem)
206 by Jason Katz-Brown
fixes in courses - impossible lookin' goood.. and it's very difficult, I just got majorly over par on not such a bad round
1908
			{
205 by Jason Katz-Brown
stuff
1909
				if (citem->curId() == i)
206 by Jason Katz-Brown
fixes in courses - impossible lookin' goood.. and it's very difficult, I just got majorly over par on not such a bad round
1910
				{
1911
					found = true;
1912
					break;
1913
				}
1914
			}
205 by Jason Katz-Brown
stuff
1915
		}
1916
206 by Jason Katz-Brown
fixes in courses - impossible lookin' goood.. and it's very difficult, I just got majorly over par on not such a bad round
1917
1918
		if (!found)
1919
			break;
205 by Jason Katz-Brown
stuff
1920
	}
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1921
	sceneItem->setId(i);
205 by Jason Katz-Brown
stuff
1922
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1923
	sceneItem->setGame(this);
206 by Jason Katz-Brown
fixes in courses - impossible lookin' goood.. and it's very difficult, I just got majorly over par on not such a bad round
1924
1053 by Stefan Majewsky
More sophisticated handling of info items.
1925
	foreach (QGraphicsItem* qitem, sceneItem->infoItems())
1926
		qitem->setVisible(m_showInfo);
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1927
1928
	sceneItem->editModeChanged(editing);
1929
983 by Stefan Majewsky
Replace the Object classes by the new ItemFactory.
1930
	sceneItem->setName(identifier);
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
1931
	m_moveableQItems.append(sceneItem->moveableItems());
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1932
1933
	newItem->setPos(width/2 - 18, height / 2 - 18);
673 by Paul Broadbent
fixed some edit mode bugs
1934
	sceneItem->moveBy(0, 0);
1009 by Stefan Majewsky
Change signature of CanvasItem::setSize from (double, double) to (QSizeF).
1935
	sceneItem->setSize(newItem->boundingRect().size());
38 by Jason Katz-Brown
1936
301 by Jason Katz-Brown
fix up, reenable charles's code, bugs.. etc
1937
	setModified(true);
1 by Jason Katz-Brown
here's kolf, read the TODO
1938
}
1939
24 by Jason Katz-Brown
1940
bool KolfGame::askSave(bool noMoreChances)
1 by Jason Katz-Brown
here's kolf, read the TODO
1941
{
29 by Jason Katz-Brown
My mother was finding the default course one too hard (and I was thinking many people would have trouble with it, including myself sometimes :) so I've moved that to Hard.kolf and started an Easy.kolf. It'll be Kolf's second course -- I'm pretty happy with Hard.kolf.
1942
	if (!modified)
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
1943
		// not cancel, don't save
1944
		return false;
1945
679 by Thomas Friedrichsmeier
Add a buttonCancel parameter to all KMessageBox::*cancel* functions.
1946
	int result = KMessageBox::warningYesNoCancel(this, i18n("There are unsaved changes to current hole. Save them?"), i18n("Unsaved Changes"), KStandardGuiItem::save(), noMoreChances? KStandardGuiItem::discard() : KGuiItem(i18n("Save &Later")), KStandardGuiItem::cancel(), noMoreChances? "DiscardAsk" : "SaveAsk");
1 by Jason Katz-Brown
here's kolf, read the TODO
1947
	switch (result)
1948
	{
1949
		case KMessageBox::Yes:
1950
			save();
1951
			// fallthrough
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
1952
1 by Jason Katz-Brown
here's kolf, read the TODO
1953
		case KMessageBox::No:
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
1954
			return false;
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1955
			break;
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
1956
1957
		case KMessageBox::Cancel:
1958
			return true;
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1959
			break;
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
1960
1961
		default:
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
1962
			break;
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
1963
	}
1964
1965
	return false;
1966
}
1967
1968
void KolfGame::addNewHole()
1969
{
24 by Jason Katz-Brown
1970
	if (askSave(true))
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
1971
		return;
24 by Jason Katz-Brown
1972
1973
	// either it's already false
1974
	// because it was saved by askSave(),
1975
	// or the user pressed the 'discard' button
301 by Jason Katz-Brown
fix up, reenable charles's code, bugs.. etc
1976
	setModified(false);
24 by Jason Katz-Brown
1977
21 by Jason Katz-Brown
fix bug where editing made ball's visibility isn't right when toggling editing at start of hole
1978
	// find highest hole num, and create new hole
1979
	// now openFile makes highest hole for us
1980
1981
	addingNewHole = true;
1982
	curHole = highestHole;
28 by Jason Katz-Brown
various stuff.. fixes mostly
1983
	recalcHighestHole = true;
192 by Jason Katz-Brown
fix bad typo
1984
	startNextHole();
21 by Jason Katz-Brown
fix bug where editing made ball's visibility isn't right when toggling editing at start of hole
1985
	addingNewHole = false;
259 by Neil Stevens
Now the newHoleAction shows the current hole
1986
	emit currentHole(curHole);
21 by Jason Katz-Brown
fix bug where editing made ball's visibility isn't right when toggling editing at start of hole
1987
1988
	// make sure even the current player isn't showing
1989
	for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
1990
		(*it).ball()->setVisible(false);
1991
1992
	whiteBall->setVisible(editing);
1993
	putter->setVisible(!editing);
1994
	inPlay = false;
30 by Jason Katz-Brown
elliptical slopes!! and other things!
1995
132 by Jason Katz-Brown
1996
	// add default objects
983 by Stefan Majewsky
Replace the Object classes by the new ItemFactory.
1997
	foreach (const Kolf::ItemMetadata& metadata, m_factory.knownTypes())
1998
		if (metadata.addOnNewHole)
1999
			addNewObject(metadata.identifier);
132 by Jason Katz-Brown
2000
175 by Jason Katz-Brown
add new Slope Practice course, clean up some code
2001
	save();
1 by Jason Katz-Brown
here's kolf, read the TODO
2002
}
2003
2004
// kantan deshou ;-)
2005
void KolfGame::resetHole()
2006
{
26 by Jason Katz-Brown
kick-ass. 1) mouse support. 2) wallpoints fixed FOR GOOD. 3) random hole. 4) better save stuff still, prompt on close/quit.
2007
	if (askSave(true))
2008
		return;
301 by Jason Katz-Brown
fix up, reenable charles's code, bugs.. etc
2009
	setModified(false);
1 by Jason Katz-Brown
here's kolf, read the TODO
2010
	curHole--;
192 by Jason Katz-Brown
fix bad typo
2011
	startNextHole();
1 by Jason Katz-Brown
here's kolf, read the TODO
2012
	resetHoleScores();
2013
}
2014
2015
void KolfGame::resetHoleScores()
2016
{
2017
	for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
2018
	{
2019
		(*it).resetScore(curHole);
2020
		emit scoreChanged((*it).id(), curHole, 0);
2021
	}
2022
}
2023
2024
void KolfGame::clearHole()
2025
{
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
2026
	QList<QGraphicsItem*> newTopLevelQItems;
2027
	foreach (QGraphicsItem* qitem, m_topLevelQItems)
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
2028
	{
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
2029
		if (dynamic_cast<Ball*>(qitem))
2030
		{
2031
			//do not delete balls
2032
			newTopLevelQItems << qitem;
2033
			continue;
2034
		}
2035
		CanvasItem *citem = dynamic_cast<CanvasItem *>(qitem);
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
2036
		if (citem)
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
2037
		{
2038
			delete citem;
2039
		}
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
2040
	}
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
2041
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
2042
	m_moveableQItems = m_topLevelQItems = newTopLevelQItems;
1071 by Stefan Majewsky
Fix overlay activation and deactivation.
2043
	setSelectedItem(0);
30 by Jason Katz-Brown
elliptical slopes!! and other things!
2044
194 by Jason Katz-Brown
add ctrl-arrows for fine-tuned rotation
2045
	// add default objects
983 by Stefan Majewsky
Replace the Object classes by the new ItemFactory.
2046
	foreach (const Kolf::ItemMetadata& metadata, m_factory.knownTypes())
2047
		if (metadata.addOnNewHole)
2048
			addNewObject(metadata.identifier);
194 by Jason Katz-Brown
add ctrl-arrows for fine-tuned rotation
2049
301 by Jason Katz-Brown
fix up, reenable charles's code, bugs.. etc
2050
	setModified(true);
1 by Jason Katz-Brown
here's kolf, read the TODO
2051
}
2052
2053
void KolfGame::switchHole(int hole)
2054
{
117 by Jason Katz-Brown
2055
	if (inPlay)
1 by Jason Katz-Brown
here's kolf, read the TODO
2056
		return;
2057
	if (hole < 1 || hole > highestHole)
2058
		return;
384 by Laurent Montel
Fix header
2059
117 by Jason Katz-Brown
2060
	bool wasEditing = editing;
2061
	if (editing)
2062
		toggleEditMode();
2063
2064
	if (askSave(true))
2065
		return;
301 by Jason Katz-Brown
fix up, reenable charles's code, bugs.. etc
2066
	setModified(false);
1 by Jason Katz-Brown
here's kolf, read the TODO
2067
2068
	curHole = hole;
2069
	resetHole();
117 by Jason Katz-Brown
2070
2071
	if (wasEditing)
2072
		toggleEditMode();
1 by Jason Katz-Brown
here's kolf, read the TODO
2073
}
2074
2075
void KolfGame::switchHole(const QString &holestring)
2076
{
2077
	bool ok;
2078
	int hole = holestring.toInt(&ok);
2079
	if (!ok)
2080
		return;
2081
	switchHole(hole);
2082
}
2083
2084
void KolfGame::nextHole()
2085
{
2086
	switchHole(curHole + 1);
2087
}
2088
2089
void KolfGame::prevHole()
2090
{
2091
	switchHole(curHole - 1);
2092
}
2093
2094
void KolfGame::firstHole()
2095
{
2096
	switchHole(1);
2097
}
2098
2099
void KolfGame::lastHole()
2100
{
2101
	switchHole(highestHole);
2102
}
2103
26 by Jason Katz-Brown
kick-ass. 1) mouse support. 2) wallpoints fixed FOR GOOD. 3) random hole. 4) better save stuff still, prompt on close/quit.
2104
void KolfGame::randHole()
2105
{
547 by Laurent Montel
Deprecated--
2106
	int newHole = 1 + (int)((double)KRandom::random() * ((double)(highestHole - 1) / (double)RAND_MAX));
26 by Jason Katz-Brown
kick-ass. 1) mouse support. 2) wallpoints fixed FOR GOOD. 3) random hole. 4) better save stuff still, prompt on close/quit.
2107
	switchHole(newHole);
2108
}
2109
1 by Jason Katz-Brown
here's kolf, read the TODO
2110
void KolfGame::save()
2111
{
2112
	if (filename.isNull())
2113
	{
598 by Stephan Kulow
compile further
2114
		QString newfilename = KFileDialog::getSaveFileName(KUrl("kfiledialog:///kourses"), 
2115
				"application/x-kourse", this, i18n("Pick Kolf Course to Save To"));
24 by Jason Katz-Brown
2116
		if (newfilename.isNull())
2117
			return;
1 by Jason Katz-Brown
here's kolf, read the TODO
2118
37 by Jason Katz-Brown
make it so one can actually make new courses again...
2119
		setFilename(newfilename);
1 by Jason Katz-Brown
here's kolf, read the TODO
2120
	}
2121
72 by Jason Katz-Brown
undo if ball leaves course
2122
	emit parChanged(curHole, holeInfo.par());
73 by Jason Katz-Brown
make puddles place your ball on the right spot again
2123
	emit titleChanged(holeInfo.name());
72 by Jason Katz-Brown
undo if ball leaves course
2124
875 by Laurent Montel
add const where it's possible
2125
	const QStringList groups = cfg->groupList();
1 by Jason Katz-Brown
here's kolf, read the TODO
2126
2127
	// wipe out all groups from this hole
874 by Laurent Montel
const'ify
2128
	for (QStringList::const_iterator it = groups.begin(); it != groups.end(); ++it)
1 by Jason Katz-Brown
here's kolf, read the TODO
2129
	{
571 by Dmitry Suzdalev
deprecated--
2130
		int holeNum = (*it).left((*it).indexOf("-")).toInt();
1 by Jason Katz-Brown
here's kolf, read the TODO
2131
		if (holeNum == curHole)
2132
			cfg->deleteGroup(*it);
2133
	}
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
2134
	foreach (QGraphicsItem* qitem, m_topLevelQItems)
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
2135
	{
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
2136
		CanvasItem *citem = dynamic_cast<CanvasItem *>(qitem);
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
2137
		if (citem)
38 by Jason Katz-Brown
2138
		{
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
2139
			cfgGroup = KConfigGroup(cfg->group(makeGroup(citem->curId(), curHole, citem->name(), (int)qitem->x(), (int)qitem->y())));
710 by Stephan Kulow
fixing my commit - earning dartstars like mad
2140
			citem->save(&cfgGroup);
38 by Jason Katz-Brown
2141
		}
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
2142
	}
1 by Jason Katz-Brown
here's kolf, read the TODO
2143
2144
	// save where ball starts (whiteBall tells all)
709 by Stephan Kulow
don't leak _that_ bad (CID 3637)
2145
	cfgGroup = KConfigGroup(cfg->group(QString("%1-ball@%2,%3").arg(curHole).arg((int)whiteBall->x()).arg((int)whiteBall->y())));
710 by Stephan Kulow
fixing my commit - earning dartstars like mad
2146
	cfgGroup.writeEntry("dummykey", true);
1 by Jason Katz-Brown
here's kolf, read the TODO
2147
709 by Stephan Kulow
don't leak _that_ bad (CID 3637)
2148
	cfgGroup = KConfigGroup(cfg->group(QString("0-course@-50,-50")));
710 by Stephan Kulow
fixing my commit - earning dartstars like mad
2149
	cfgGroup.writeEntry("author", holeInfo.author());
2150
	cfgGroup.writeEntry("Name", holeInfo.untranslatedName());
1 by Jason Katz-Brown
here's kolf, read the TODO
2151
2152
	// save hole info
709 by Stephan Kulow
don't leak _that_ bad (CID 3637)
2153
	cfgGroup = KConfigGroup(cfg->group(QString("%1-hole@-50,-50|0").arg(curHole)));
710 by Stephan Kulow
fixing my commit - earning dartstars like mad
2154
	cfgGroup.writeEntry("par", holeInfo.par());
2155
	cfgGroup.writeEntry("maxstrokes", holeInfo.maxStrokes());
2156
	cfgGroup.writeEntry("borderWalls", holeInfo.borderWalls());
1 by Jason Katz-Brown
here's kolf, read the TODO
2157
2158
	cfg->sync();
2159
301 by Jason Katz-Brown
fix up, reenable charles's code, bugs.. etc
2160
	setModified(false);
1 by Jason Katz-Brown
here's kolf, read the TODO
2161
}
2162
2163
void KolfGame::toggleEditMode()
2164
{
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
2165
	// won't be editing anymore, and user wants to cancel, we return
117 by Jason Katz-Brown
2166
	// this is pretty useless. when the person leaves the hole,
2167
	// he gets asked again
2168
	/*
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
2169
	   if (editing && modified)
2170
	   {
2171
	   if (askSave(false))
2172
	   {
2173
	   emit checkEditing();
2174
	   return;
2175
	   }
2176
	   }
2177
	   */
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
2178
36 by Jason Katz-Brown
bumpers! super-fun. other fixes.
2179
	selectedItem = 0;
27 by Jason Katz-Brown
fix 2 critical bugs: 1) don't crash when editing and mouse moves 2) make holes not disappear off of floaters (and floater saving is all better now thank heaven :)
2180
1 by Jason Katz-Brown
here's kolf, read the TODO
2181
	editing = !editing;
2182
2183
	if (editing)
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
2184
	{
2185
		emit editingStarted();
1071 by Stefan Majewsky
Fix overlay activation and deactivation.
2186
		setSelectedItem(0);
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
2187
	}
2188
	else
39 by Jason Katz-Brown
cool cursors, sequential loading
2189
	{
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
2190
		emit editingEnded();
680 by Pino Toscano
better API for cursors
2191
		setCursor(Qt::ArrowCursor);
39 by Jason Katz-Brown
cool cursors, sequential loading
2192
	}
1 by Jason Katz-Brown
here's kolf, read the TODO
2193
2194
	// alert our items
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
2195
	foreach (QGraphicsItem* qitem, m_topLevelQItems)
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
2196
	{
1042 by Stefan Majewsky
Unbreak editor.
2197
		if (dynamic_cast<Ball*>(qitem)) continue;
1041 by Stefan Majewsky
Fix the annoying crash in KolfGame's dtor.
2198
		CanvasItem *citem = dynamic_cast<CanvasItem *>(qitem);
19 by Jason Katz-Brown
things I can think of: game knows if it's been modified, prompts if you wanna save it. no crashes, more optimized floaters (but not enough), person with best score on last hole goes first.. other things, forget, must go to bed. cheers!
2199
		if (citem)
2200
			citem->editModeChanged(editing);
2201
	}
1 by Jason Katz-Brown
here's kolf, read the TODO
2202
2203
	for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
21 by Jason Katz-Brown
fix bug where editing made ball's visibility isn't right when toggling editing at start of hole
2204
	{
2205
		// curplayer shouldn't be hidden no matter what
2206
		if ((*it).ball()->beginningOfHole() && it != curPlayer)
2207
			(*it).ball()->setVisible(false);
2208
		else
2209
			(*it).ball()->setVisible(!editing);
2210
	}
1 by Jason Katz-Brown
here's kolf, read the TODO
2211
2212
	whiteBall->setVisible(editing);
1061 by Stefan Majewsky
Enable editing of white ball.
2213
	whiteBall->editModeChanged(editing);
1 by Jason Katz-Brown
here's kolf, read the TODO
2214
2215
	// shouldn't see putter whilst editing
2216
	putter->setVisible(!editing);
2217
2218
	if (editing)
2219
		autoSaveTimer->start(autoSaveMsec);
2220
	else
2221
		autoSaveTimer->stop();
2222
2223
	inPlay = false;
2224
}
2225
1071 by Stefan Majewsky
Fix overlay activation and deactivation.
2226
void KolfGame::setSelectedItem(CanvasItem* citem)
1046 by Stefan Majewsky
Ensure that only one overlay is active at any time.
2227
{
1071 by Stefan Majewsky
Fix overlay activation and deactivation.
2228
	QGraphicsItem* qitem = dynamic_cast<QGraphicsItem*>(citem);
2229
	selectedItem = qitem;
2230
	emit newSelectedItem(qitem ? citem : &holeInfo);
2231
	//deactivate all other overlays
2232
	foreach (QGraphicsItem* otherQitem, m_topLevelQItems)
1046 by Stefan Majewsky
Ensure that only one overlay is active at any time.
2233
	{
1071 by Stefan Majewsky
Fix overlay activation and deactivation.
2234
		CanvasItem* otherCitem = dynamic_cast<CanvasItem*>(otherQitem);
2235
		if (otherCitem && otherCitem != citem)
1046 by Stefan Majewsky
Ensure that only one overlay is active at any time.
2236
		{
1071 by Stefan Majewsky
Fix overlay activation and deactivation.
2237
			//false = do not create overlay if it does not exist yet
2238
			Kolf::Overlay* otherOverlay = otherCitem->overlay(false);
2239
			if (otherOverlay)
2240
				otherOverlay->setState(Kolf::Overlay::Passive);
1046 by Stefan Majewsky
Ensure that only one overlay is active at any time.
2241
		}
2242
	}
2243
}
2244
749 by Paul Broadbent
edit mode vastly improved, now fully usable
2245
#ifdef SOUND
611 by Dmitry Suzdalev
Use Phonon::AudioPlayer
2246
void KolfGame::playSound(const QString& file, float vol)
1 by Jason Katz-Brown
here's kolf, read the TODO
2247
{
611 by Dmitry Suzdalev
Use Phonon::AudioPlayer
2248
	if (m_sound)
1 by Jason Katz-Brown
here's kolf, read the TODO
2249
	{
611 by Dmitry Suzdalev
Use Phonon::AudioPlayer
2250
		QString resFile = soundDir + file + QString::fromLatin1(".wav");
295 by Jason Katz-Brown
make sure sound files exist
2251
304 by Jason Katz-Brown
play all of the new sounds, make blackholes spit out a little after the entrance
2252
		// not needed when all of the files are in the distribution
611 by Dmitry Suzdalev
Use Phonon::AudioPlayer
2253
		//if (!QFile::exists(resFile))
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
2254
		//return;
611 by Dmitry Suzdalev
Use Phonon::AudioPlayer
2255
		if (vol > 1)
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
2256
			vol = 1;
739 by Matthias Kretz
adapt to phonon-Trolltech branch API changes
2257
		m_player->setCurrentSource(resFile);
2258
		m_player->play();
611 by Dmitry Suzdalev
Use Phonon::AudioPlayer
2259
	}
749 by Paul Broadbent
edit mode vastly improved, now fully usable
2260
}
2261
#else //SOUND
2262
void KolfGame::playSound( const QString&, float )
2263
{
2264
}
2265
#endif //SOUND
1 by Jason Katz-Brown
here's kolf, read the TODO
2266
30 by Jason Katz-Brown
elliptical slopes!! and other things!
2267
void HoleInfo::borderWallsChanged(bool yes)
2268
{
2269
	m_borderWalls = yes;
2270
	game->setBorderWalls(yes);
2271
}
2272
24 by Jason Katz-Brown
2273
bool KolfGame::allPlayersDone()
2274
{
2275
	for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
2276
		if ((*it).ball()->curState() != Holed)
328 by Jason Katz-Brown
fix max strokes stuff
2277
			return false;
24 by Jason Katz-Brown
2278
328 by Jason Katz-Brown
fix max strokes stuff
2279
	return true;
24 by Jason Katz-Brown
2280
}
2281
30 by Jason Katz-Brown
elliptical slopes!! and other things!
2282
void KolfGame::setBorderWalls(bool showing)
2283
{
1047 by Stefan Majewsky
Refactor Wall class: Drop WallPoint class, introduce WallOverlay.
2284
	foreach (Kolf::Wall* wall, borderWalls)
2285
		wall->setVisible(showing);
30 by Jason Katz-Brown
elliptical slopes!! and other things!
2286
}
2287
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
2288
void KolfGame::setUseAdvancedPutting(bool yes)
96 by Dirk Mueller
--enable-final fixes
2289
{
2290
	m_useAdvancedPutting = yes;
49 by Jason Katz-Brown
clean up indentation, add niklas to author list
2291
2292
	// increase maxStrength in advanced putting mode
2293
	if (yes)
2294
		maxStrength = 65;
2295
	else
2296
		maxStrength = 55;
96 by Dirk Mueller
--enable-final fixes
2297
}
43 by Jason Katz-Brown
AWESOME new putting style by Niklas Knutsson ...
2298
72 by Jason Katz-Brown
undo if ball leaves course
2299
void KolfGame::setShowGuideLine(bool yes)
2300
{
2301
	putter->setShowGuideLine(yes);
2302
}
2303
77 by Jason Katz-Brown
toggle sound on/off
2304
void KolfGame::setSound(bool yes)
2305
{
2306
	m_sound = yes;
2307
}
2308
59 by Jason Katz-Brown
a spiffy newgame dialog
2309
void KolfGame::courseInfo(CourseInfo &info, const QString& filename)
2310
{
664 by Paul Broadbent
KConfig ports
2311
	KConfig config(filename);
2312
	KConfigGroup configGroup (config.group(QString("0-course@-50,-50")));
2313
	info.author = configGroup.readEntry("author", info.author);
2314
	info.name = configGroup.readEntry("Name", configGroup.readEntry("name", info.name));
2315
	info.untranslatedName = configGroup.readEntryUntranslated("Name", configGroup.readEntryUntranslated("name", info.name));
59 by Jason Katz-Brown
a spiffy newgame dialog
2316
2317
	unsigned int hole = 1;
2318
	unsigned int par= 0;
2319
	while (1)
2320
	{
2321
		QString group = QString("%1-hole@-50,-50|0").arg(hole);
664 by Paul Broadbent
KConfig ports
2322
		if (!config.hasGroup(group))
59 by Jason Katz-Brown
a spiffy newgame dialog
2323
		{
2324
			hole--;
2325
			break;
2326
		}
2327
664 by Paul Broadbent
KConfig ports
2328
		configGroup = KConfigGroup(config.group(group));
2329
		par += configGroup.readEntry("par", 3);
59 by Jason Katz-Brown
a spiffy newgame dialog
2330
2331
		hole++;
2332
	}
2333
2334
	info.par = par;
2335
	info.holes = hole;
2336
}
2337
222 by Jason Katz-Brown
change to KConfig (from KSimpleConfig) so translations are kept through saves
2338
void KolfGame::scoresFromSaved(KConfig *config, PlayerList &players)
133 by Jason Katz-Brown
2339
{
708 by Stephan Kulow
nice leak (CID 3640)
2340
	KConfigGroup configGroup(config->group(QString("0 Saved Game")));
2341
	int numPlayers = configGroup.readEntry("Players", 0);
133 by Jason Katz-Brown
2342
	if (numPlayers <= 0)
2343
		return;
2344
2345
	for (int i = 1; i <= numPlayers; ++i)
2346
	{
2347
		// this is same as in kolf.cpp, but we use saved game values
708 by Stephan Kulow
nice leak (CID 3640)
2348
		configGroup = KConfigGroup(config->group(QString::number(i)));
133 by Jason Katz-Brown
2349
		players.append(Player());
710 by Stephan Kulow
fixing my commit - earning dartstars like mad
2350
		players.last().ball()->setColor(configGroup.readEntry("Color", "#ffffff"));
2351
		players.last().setName(configGroup.readEntry("Name"));
133 by Jason Katz-Brown
2352
		players.last().setId(i);
2353
875 by Laurent Montel
add const where it's possible
2354
		const QStringList scores(configGroup.readEntry("Scores",QStringList()));
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
2355
		QList<int> intscores;
874 by Laurent Montel
const'ify
2356
		for (QStringList::const_iterator it = scores.begin(); it != scores.end(); ++it)
133 by Jason Katz-Brown
2357
			intscores.append((*it).toInt());
2358
2359
		players.last().setScores(intscores);
2360
	}
2361
}
2362
222 by Jason Katz-Brown
change to KConfig (from KSimpleConfig) so translations are kept through saves
2363
void KolfGame::saveScores(KConfig *config)
133 by Jason Katz-Brown
2364
{
2365
	// wipe out old player info
875 by Laurent Montel
add const where it's possible
2366
	const QStringList groups = config->groupList();
874 by Laurent Montel
const'ify
2367
	for (QStringList::const_iterator it = groups.begin(); it != groups.end(); ++it)
133 by Jason Katz-Brown
2368
	{
2369
		// this deletes all int groups, ie, the player info groups
2370
		bool ok = false;
144 by Jason Katz-Brown
clean up
2371
		(*it).toInt(&ok);
133 by Jason Katz-Brown
2372
		if (ok)
135 by Jason Katz-Brown
fix typos in savegame code so it gets rid of old scores in file
2373
			config->deleteGroup(*it);
133 by Jason Katz-Brown
2374
	}
2375
707 by Dirk Mueller
not allocating on the heap fixes memory leaks (CID: 3638)
2376
	KConfigGroup configGroup(config->group(QString("0 Saved Game")));
2377
	configGroup.writeEntry("Players", players->count());
2378
	configGroup.writeEntry("Course", filename);
2379
	configGroup.writeEntry("Current Hole", curHole);
133 by Jason Katz-Brown
2380
2381
	for (PlayerList::Iterator it = players->begin(); it != players->end(); ++it)
2382
	{
707 by Dirk Mueller
not allocating on the heap fixes memory leaks (CID: 3638)
2383
		KConfigGroup configGroup(config->group(QString::number((*it).id())));
2384
		configGroup.writeEntry("Name", (*it).name());
2385
		configGroup.writeEntry("Color", (*it).ball()->color().name());
150 by Jason Katz-Brown
2386
133 by Jason Katz-Brown
2387
		QStringList scores;
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
2388
		QList<int> intscores = (*it).scores();
2389
		for (QList<int>::Iterator it = intscores.begin(); it != intscores.end(); ++it)
133 by Jason Katz-Brown
2390
			scores.append(QString::number(*it));
150 by Jason Katz-Brown
2391
707 by Dirk Mueller
not allocating on the heap fixes memory leaks (CID: 3638)
2392
		configGroup.writeEntry("Scores", scores);
133 by Jason Katz-Brown
2393
	}
2394
}
2395
286 by Jason Katz-Brown
make kolf a lean, mean, command-line-argument handling machine. Will open courses AND saved games from the command line. The mimetypes also specify kolf in an exec line.
2396
CourseInfo::CourseInfo()
633 by Paul Broadbent
Ported to Qt4: almost all Qt 3 compatibility classes removed and now using QGraphicsView
2397
	: name(i18n("Course Name")), author(i18n("Course Author")), holes(0), par(0)
286 by Jason Katz-Brown
make kolf a lean, mean, command-line-argument handling machine. Will open courses AND saved games from the command line. The mimetypes also specify kolf in an exec line.
2398
{
2399
}
2400
1 by Jason Katz-Brown
here's kolf, read the TODO
2401
#include "game.moc"