File: CTetrisGame.cpp

package info (click to toggle)
blocks-of-the-undead 1.0-7
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 4,084 kB
  • sloc: cpp: 6,224; sh: 3,356; makefile: 171
file content (472 lines) | stat: -rw-r--r-- 11,067 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
#include <unistd.h>
#include "tetris.h"

CTetrisGame::CTetrisGame(int screenX, int screenY, int bitDepth, bool fullscreen, CTetrisTheme *theme, const list<CVector> &fieldOffsets)
                         : CSDLGame(screenX, screenY, bitDepth, fullscreen), theme(theme), state(Splash), done(false)
						 , mouseloc(0,0)//, sound()
{
	if (theme)
	{
		for (list<CVector>::const_iterator i = fieldOffsets.begin(); i != fieldOffsets.end(); ++i)
		{
			fields.push_back(new CPlayingField((*i), *(theme->getBlockSet()), theme, 100) );
		}
	}
	else
	{
		_THROWEX(ex_illegalArguments, "NULL theme", "CTetrisGame", "CTetrisGame",
			        "[ screenX=" << screenX << ", screenY=" << screenY << ", bitDepth=" << bitDepth <<
					", fullscreen=" << fullscreen << ", theme={" << theme << "}, fieldOffsets={" << &fieldOffsets << "}]");
	}
	splash = CImgLoader::loadImage("splash640x480.png");
}

CTetrisGame::CTetrisGame(int screenX, int screenY, int bitDepth, bool fullscreen, const string &title)
                         : CSDLGame(screenX, screenY, bitDepth, fullscreen, title), theme(NULL), state(Splash), done(false)
						  , mouseloc(0,0)

{	
	splash = CImgLoader::loadImage("splash640x480.png");
}

CTetrisGame::~CTetrisGame()
{

    string file;
#if defined(WIN32) || defined(_WIN32)
	file = CImgLoader::getPath() + "/progress.txt";
#else
        char *homedir = getenv("HOME");
        if (homedir != NULL)
        {
            file = string(homedir) + "/.blocks-progress";
        }
        else
        {
            file = "blocks-progress";
        }
#endif

	ofstream prog ( file.c_str() , ios::trunc );
	if (prog && fields[0]->getStage() != 0 && fields[0]->getLvl() != 0)
	{
		if (state == Win)
		{
			prog << "1" << endl << "1" << endl;
		}
		else
		{
			prog << fields[0]->getStage() << endl;
			prog << fields[0]->getLvl() << endl;
		}
	}
	prog.close();

	delete splash;
#ifndef __GNUC__
	deleteContainer(fields);
	deleteContainer(sprites);
#else
        for (vector<CPlayingField*>::iterator i = fields.begin(); i != fields.end(); ++i)
        {
                delete (*i);
        }

        for (list<CSprite*>::iterator i = sprites.begin(); i != sprites.end(); ++i)
        {
                delete (*i);
        }
#endif

	delete theme;
}

void CTetrisGame::setTheme(CTetrisTheme* t, const list<CVector> &fieldOffsets)
{
	delete theme;
	theme = t;
#ifndef __GNUC__
	deleteContainer(fields);
#else
        for (vector<CPlayingField*>::iterator i = fields.begin(); i != fields.end(); ++i)
        {
                delete (*i);
        }
#endif
	for (list<CVector>::const_iterator i = fieldOffsets.begin(); i != fieldOffsets.end(); ++i)
	{
		fields.push_back(new CPlayingField((*i), *(theme->getBlockSet()), theme, 100) );
	}

	theme = t;
}

CSprite* CTetrisGame::addSprite(CVector velocity, CVector pos, const string &filename, CImgLoader::GraphicFileType fileType)
{
	CSprite *s = new CSprite(velocity, pos, filename, "static", CBounds(0,0,640,480) );
	sprites.push_front( s );
	return s;
}

CSprite* CTetrisGame::addSprite(CSprite* sprite)
{
	sprites.push_back( sprite );
	return sprite;
}

void CTetrisGame::animateSprites()
{
	for (list<CSprite*>::iterator i = sprites.begin(); i != sprites.end(); ++i)
	{
		CSprite *s = (*i);
		int w = (s->getWidth());
		int h = (s->getHeight());
		CRect r(0,0,640,480);
		if ( ! (s->getX() > -w && 
			s->getY()  > -h &&
			s->getY() < 480 &&
			s->getX() < 640))
		{
			list<CSprite*>::iterator tmp = i;

			if (tmp != sprites.end())
				tmp++;

			delete (*i);
			sprites.erase(i);
			i = tmp;
		}
		else
		{
			(*i)->update();
			(*i)->draw(*screen);
		}
	}
}

bool CTetrisGame::gameLoop(bool infinite)
{
	Uint32 t1 = 0;
		int ct = 26;
	SDL_ShowCursor(false);
	SDL_EnableKeyRepeat(25, 150);
	CTimer t;
	double fps = 0;
	bool b = false;
	while( !done )
	{
		t1 = SDL_GetTicks();
		SDL_Event event;
		while (!done && SDL_PollEvent(&event))
		{
			handleEvent(event);
			usleep(200);
		}
		
		switch(state)
		{
			case SinglePlayerPuzzle:
			{
				if (theme->getFloater() )
				{
					int w = theme->getFloater()->getWidth();
					if (fields[0]->getStage() == 1 && t.getElapsed() > 5000 && rand() % 50 > 48)
					{
						t.reset();
						CSprite *floater = theme->getFloater();
						CSprite *s = floater->getClone(CVector(-50, 0), CVector(639, rand() % 480) );
						addSprite( s );
					}

					if (fields[0]->getStage() == 2 && t.getElapsed() > 2000 && rand() % 50 > 48)
					{
						t.reset();
						CSprite *floater = theme->getFloater();
						CVector v[] = { CVector(123,352) , CVector(276,361), CVector(103,449) };
						CVector v1 = v[rand()%3];
						CSprite *s = floater->getClone(CVector(0, -50), v1);
						s->setScale(0.6);
						//s->setRot(PI/2);
						s->setRot(0);
						s->appendEvent( new CResizeEvent(*s, 0, .6, 5000, true) );
						//s->appendEvent( new CRotateEffect(1, 6000, *s, true) );
						s->appendEvent( new CRandomVelEvent( *s, .5, 1, 5, 0, true) );
						addSprite( s );
					}
				}
				screen->blit(*(theme->getBackground()), 0, 0);
				int stage = fields[0]->getStage();
				fields[0]->draw(*screen);
				animateSprites();
				theme->getCharacter()->draw(*screen);

				if (stage != fields[0]->getStage())
				{
					int newStage = fields[0]->getStage();
#ifndef __GNUC__
					deleteContainer(sprites);
#else
					for (list<CSprite*>::iterator i = sprites.begin(); i != sprites.end(); ++i)
					{
						delete (*i);
					}
#endif
					sprites.clear();
					delete theme;

					CTetrisTheme* tmptheme = new CTetrisTheme( stringify(fields[0]->getStage()) );
					CVector pos = fields[0]->getPos();
					delete fields[0];
					fields.clear();
					fields.push_back(new CPlayingField(pos, *(tmptheme->getBlockSet()), tmptheme, 100) );
					theme = tmptheme;
					fields[0]->load(newStage,1);
					state = Loading;
				}
				screen->doneDrawing();

				if (fields[0]->isGameWon())
				{
					state = Win;
				}
			} break;
			case Splash:
			{
				CText anykey("Press any key to start the game", CColor(255,255,255), CTextManager::getDefaultFont(), CTextManager::getPtSize(1.5));
				anykey.setPos(640-anykey.getWidth()-5, 0);
				screen->blit(*splash,0,0);
				anykey.draw(*screen);
				screen->doneDrawing();
			//	fields[0]->load(1,1);
			} break;
			case Loading:
			{
				CText t("Stage " + stringify(fields[0]->getStage()), CColor(255,255,255), CTextManager::getDefaultFont(), CTextManager::getPtSize(4), CText::BOLD);
				t.setPos(640/2-t.getWidth()/2,480/2-t.getHeight()/2);
				CText t2("Press any key to begin", CColor(255,255,255), CTextManager::getDefaultFont(), CTextManager::getPtSize(2));
				t2.setPos(640/2-t2.getWidth()/2, t.getPos().getY() + t.getHeight() + 6);
				screen->fill(CColor());
				t.draw(*screen);
				t2.draw(*screen);
				screen->doneDrawing();
			} break;
			case Win:
			{
				if (!b)
				{
					b = true;
					CText *t = new CText("WINNER!", CColor(255), CTextManager::getDefaultFont(), CTextManager::getPtSize(3), CText::BOLD);
					t->setRect(CRect(0,0,640,480));
					t->setVelocity(CVector(100,200));
					t->setPos(CVector(rand()%640, rand()%480));
					sprites.clear();
					addSprite(t);
				}
				else
				{
					screen->fill(CColor());
					animateSprites();
					screen->doneDrawing();
				}
			} break;

		}

		/*if (( (SDL_GetTicks() - t1)/1000. ) > 0)       // calculate FPS (used for sprite's framerate-independent movement)
			fps = 1 / ( (SDL_GetTicks() - t1)/1000. );
		
		ostringstream ss;
		ss << "FPS: " << (int)fps;
		ct++;
		if ( ct > 25 )
		{
			ct = 0;
			(static_cast<CText*> (*(sprites.begin())))->setText(ss.str());
		}*/
		usleep(3000);
	}

	return true;
}

void CTetrisGame::handleEvent(const SDL_Event &e)
{
	switch (e.type)
	{
		case SDL_KEYDOWN:
			handleKeypress(e.key);
			break;
		case SDL_MOUSEMOTION:
			handleMouseMotion(e.motion);
			break;
		case SDL_MOUSEBUTTONDOWN:
			handleMouseButton(e.button);
			break;

		case SDL_QUIT:
			done = true;
			break;
	}
}

void CTetrisGame::handleKeypress(const SDL_KeyboardEvent &e)
{
	switch(state)
	{
		case SinglePlayerPuzzle:
		case SinglePlayer:
		{
			if (fields[0]->isGameOver())
			{
				fields[0]->reLoadLevel();
				break;
			}

			switch(e.keysym.sym)
			{
				case SDLK_ESCAPE:
					done = true;
					break;
				case SDLK_w:
					fields[0]->moveCursor(0, -1, 0);
					break;
				case SDLK_a:
					fields[0]->moveCursor(-1, 0, 0);
					break;
				case SDLK_s:
					fields[0]->moveCursor(0, 1, 0);
					break;
				case SDLK_d:
					fields[0]->moveCursor(1, 0, 0);
					break;
				case SDLK_r:
					fields[0]->reLoadLevel();
					break;
			        case SDLK_SPACE:
					fields[0]->swap();
					break;
			/*	case SDLK_RETURN:
					CTetrisTheme* tmptheme = new CTetrisTheme( stringify(3) );
					CVector pos = fields[0]->getPos();
					delete fields[0];
					fields.clear();
					fields.push_back(new CPlayingField(pos, *(tmptheme->getBlockSet()), tmptheme, 100) );
					theme = tmptheme;
					fields[0]->load(2,1);
					break;*/
			}
		} break;
		case Loading:
		{
			state = SinglePlayerPuzzle;
		} break;
		
		case Splash:
		{
			startGame();
		}break;

		default:
		{
			switch(e.keysym.sym)
			{
				case SDLK_ESCAPE:
				{
					done = true;
					break;
				}
			}
			break;
		}
	}
}

void CTetrisGame::handleMouseMotion(const SDL_MouseMotionEvent &e)
{
	switch(state)
	{
		case SinglePlayerPuzzle:
		case SinglePlayer:
			mouseloc.setX(e.x);
			mouseloc.setY(e.y);
			int x, y;
			if ( (fields[0]->boardCords(mouseloc, x, y)))
			{
				fields[0]->moveCursorAbs(x, y, 0);
			}
			break;
	}
}

void CTetrisGame::handleMouseButton(const SDL_MouseButtonEvent &e)
{
	switch(state)
	{
		case SinglePlayerPuzzle:
		case SinglePlayer:
		{
			if (fields[0]->isGameOver())
			{
				fields[0]->reLoadLevel();
				break;
			}

			int x, y;
			bool cords;
			/*if ( (cords = fields[0]->boardCords(mouseloc, x, y)) && (fields[0]->blockExists(x, y) || fields[0]->blockExists(x+1, y)))
			{*/
				fields[0]->swap();
			//}
		} break;

		case Loading:
		{
			state = SinglePlayerPuzzle;
		} break;

		case Splash:
		{
			startGame();
		}break;
	}
}

void CTetrisGame::startGame()
{
			state = SinglePlayerPuzzle;
			int a = 1, b = 1;

                        string file;
#if defined(WIN32) || defined(_WIN32)
                        file = CImgLoader::getPath() + "/progress.txt";
#else
                        char *homedir = getenv("HOME");
                        if (homedir != NULL)
                        {
                            file = string(homedir) + "/.blocks-progress";
                        }
                        else
                        {
                            file = "blocks-progress";
                        }
#endif

			ifstream data( file.c_str() );
			if (data)
			{
				data >> a;
				data >> b;
			}

			if (a != 1)
			{
				CTetrisTheme* tmptheme = new CTetrisTheme( stringify(a) );
				CVector pos = fields[0]->getPos();
				delete fields[0];
				fields.clear();
				fields.push_back(new CPlayingField(pos, *(tmptheme->getBlockSet()), tmptheme, 100) );
				delete theme;
				theme = tmptheme;
			}
			fields[0]->load(a,b);
}