-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgame.cpp
500 lines (405 loc) · 19.9 KB
/
game.cpp
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#include "game.h"
#include <wiringPi.h>
Game::Game(int w, int h) {
wiringPiSetup ();
pinMode (TRIGGER_PIN, INPUT); // trigger
pinMode (LEFT_PIN, INPUT); // trigger
pinMode (RIGHT_PIN, INPUT); // trigger
// pinMode (1, OUTPUT);
// pinMode (1, OUTPUT);
// pinMode (1, OUTPUT);
// pinMode (1, OUTPUT);
// pinMode (1, OUTPUT);
// printf("%i music - %i \n", MIX_INIT_MP3, Mix_Init(MIX_INIT_MP3)); //http://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_frame.html
if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ){
printf( "SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError() );
}
Laser = Mix_LoadWAV( "./sound/Laser.wav" );//http://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_frame.html
if( Laser == NULL ) printf( "LOAD FAILED: Laser sound effect. Error: %s\n", Mix_GetError() );
GameOver = Mix_LoadWAV( "./sound/GameOver1.wav" );//http://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_frame.html
if( GameOver == NULL ) printf( "LOAD FAILED: GameOver sound effect. Error: %s\n", Mix_GetError() );
DeadDuck = Mix_LoadWAV( "./sound/DeadDuck.wav" );//http://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_frame.html
if( DeadDuck == NULL ) printf( "LOAD FAILED: DeadDuck sound effect. Error: %s\n", Mix_GetError() );
bg = Mix_LoadWAV( "./sound/Ghostbusters.wav" );//http://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_frame.html
if( bg == NULL ) printf( "LOAD FAILED: bg sound effect. Error: %s\n", Mix_GetError() );
this->width = w;
this->height = h;
this->radarSize = w / 7;
this->duckCounter = 0;
//if(!this->cap.isOpened()) {
//printf("FATAL ERROR: Failed to open webcam.\n");
//exit(EXIT_FAILURE); // Exit with an error code.
//}
this->window = SDL_CreateWindow("Duck Haunt", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h, SDL_WINDOW_SHOWN);
printf("Created Window\n");
this->renderer = SDL_CreateRenderer(this->window, -1, SDL_RENDERER_ACCELERATED); // draw things to screen
printf("Created Renderer\n");
IMG_Init(IMG_INIT_PNG); //allows png rendering
this->spriteTexture = IMG_LoadTexture(this->renderer, "sprites/spriteSheet.png"); // Load the spritesheet directly into a texture
this->backgroundTexture = IMG_LoadTexture(this->renderer, "sprites/background.png"); // Load background image into a texture
this->titleScreenTexture = IMG_LoadTexture(this->renderer, "sprites/title.png");
this->surface = SDL_GetWindowSurface(this->window);
this->texture = SDL_CreateTextureFromSurface(this->renderer, this->surface); // SDL_Texture - A structure that contains an efficient, driver-specific representation of pixel data.
this->crosshairTexture = IMG_LoadTexture(this->renderer, "sprites/crosshair.png");
TTF_Init();
this->eightbitwonder = TTF_OpenFont("font.ttf", 18);
this->world.addDuck(Duck(Radian(20), 20));
//this->world.addDuck(Duck(Radian(10), 30));
//this->world.addDuck(Duck(Radian(30), 20));
//this->world.addDuck(Duck(Radian(100), 40));
printf("Added all ducks\n");
this->lastTicks = SDL_GetTicks();
this->gameStartTicks = SDL_GetTicks();
}
Game::~Game() {
Mix_FreeChunk(Laser);
Mix_FreeChunk(GameOver);
Mix_FreeChunk(DeadDuck);
Mix_FreeChunk(bg);
SDL_DestroyTexture(this->spriteTexture);
SDL_DestroyTexture(this->backgroundTexture);
SDL_DestroyTexture(this->titleScreenTexture);
SDL_FreeSurface(this->surface);
SDL_DestroyTexture(this->texture);
SDL_DestroyTexture(this->radarTexture);
SDL_DestroyTexture(this->crosshairTexture);
TTF_CloseFont(this->eightbitwonder);
SDL_DestroyRenderer(this->renderer);
SDL_DestroyWindow(this->window);
}
void Game::redraw() {
//this->cap >> this->image; // get a new frame from camera
//convert it to SDL_Surface
//SDL_Texture* frame=SDL_CreateTextureFromSurface(this->renderer, convertToSDLSurface(this->image));
//SDL_RenderCopy(this->renderer, frame, NULL, NULL);
//SDL_DestroyTexture(frame); // No memory leaks here.
//render the whole thing out to 0,0 coordinate
//SDL_BlitSurface(frame,NULL,this->surface,NULL);
//avoid memory leaks
// SDL_FreeSurface(frame);
if (this->state == game) {
// Fill screen with white (eventually draw scrolling background here)
boxRGBA(this->renderer, 0, 0, this->width, this->height, 0xFF, 0xFF, 0xFF, 0xFF);
//SDL_Rect dstRect1;
//SDL_Rect dstRect2;
//dstRect1 = (SDL_Rect){this->world.getPlayer()->getAngle().toDegrees(), 0, 960, 480};
//SDL_RenderCopy(this->renderer, this->backgroundTexture, NULL, &dstRect1);
//SDL_RenderCopy(this->renderer, this->backgroundTexture, NULL, dstRect2);
//printf("Drawing Webcam\n");
drawDucks();
//printf("Ducks Drawn\n");
drawRadar();
//printf("Radar Drawn\n");
drawScore();
drawHealth();
SDL_Rect crosshairDstRect = {this->width/2 - 32, this->height / 2 - 32, 64, 64};
SDL_RenderCopy(this->renderer, this->crosshairTexture, NULL, &crosshairDstRect);
}
if (this->state == titleScreen) {
SDL_RenderCopy(this->renderer, this->titleScreenTexture, NULL, NULL);
}
if (this->state == gameOver) {
//SDL_RenderCopy(this->renderer, this->gameOverScreenTexture, NULL, NULL);
boxRGBA(this->renderer, 0, 0, this->width, this->height, 0x00, 0x00, 0x00, 0xFF);
SDL_Rect srcRect = {64 * 5, 0, 64, 64};
SDL_Rect dstRect = {this->width / 2 - 128, this->height / 2 - 128, 256, 256};
int result = SDL_RenderCopy(this->renderer, this->spriteTexture, &srcRect, &dstRect);
char buffer[50];
sprintf(buffer, "SCORE %i", this->world.getPlayer()->score);
SDL_Color color = { 0xFF, 0x00, 0x00 };
SDL_Surface* surface = TTF_RenderText_Solid(this->eightbitwonder, buffer, color);
SDL_Texture* texture = SDL_CreateTextureFromSurface(this->renderer, surface);
int w, h;
SDL_QueryTexture(texture, NULL, NULL, &w, &h);
//printf("w: %i, h: %i\n", w, h);
SDL_Rect txtDstRect = {this->width / 2 - w / 2, this->height / 2 - h / 2 + 100, w, h};
SDL_RenderCopy(this->renderer,
texture,
NULL,
&txtDstRect);
SDL_DestroyTexture(texture);
SDL_FreeSurface(surface);
}
SDL_UpdateWindowSurface(this->window);
//printf("Updated Surface\n");
SDL_RenderPresent(this->renderer);
}
void Game::drawRadar() {
Vector2 radarPos(this->width - this->radarSize, 0);
Vector2 radarOrigin(radarPos.x + (radarSize / 2), (radarSize / 2));
// Draw the radar circle
filledCircleRGBA(this->renderer, radarPos.x + (this->radarSize / 2), radarPos.y + (this->radarSize / 2), radarSize / 2, 0x00, 0x00, 0x00, 0x99);
// Draw the dot for the player at the center
filledCircleRGBA(this->renderer, radarOrigin.x, radarOrigin.y, 2, 0xFF, 0xFF, 0xFF, 0xFF);
Vector2 playerDirection = this->world.getPlayer()->getVector();
// Player angle
lineRGBA(this->renderer, radarOrigin.x, radarOrigin.y, radarOrigin.x + (radarSize / 2) * playerDirection.x, radarOrigin.y - (radarSize / 2) * playerDirection.y, 0xFF, 0xFF, 0xFF, 0xFF);
// Draw ducks on radar
for (list<Duck>::iterator i = this->world.getDuckIterator(); i != this->world.getDuckEnd(); i++) {
if (i->status != alive)
continue; // Don't display dead ducks on the radar
uint8_t red, green, blue;
if (i->isVisible(*this->world.getPlayer())) {
red = 0x00;
green = 0xFF;
blue = 0x00;
}
else {
red = 0xFF;
green = 0x00;
blue = 0x00;
}
filledCircleRGBA(this->renderer,
radarOrigin.x + i->position.toVector2().x,
radarOrigin.y - i->position.toVector2().y,
2,
red, green, blue,
0xFF);
}
}
void Game::drawHealth() {
int playerHealth = (this->world.getPlayer()->health);
SDL_Rect healthSrcRect = { playerHealth * 64, 64, 64, 64 };
SDL_Rect healthDstRect = { 0, 0, 128, 128 };
//draw
int result = SDL_RenderCopy(this->renderer, this->spriteTexture, &healthSrcRect, &healthDstRect);
}
void Game::drawScore() {
// Convert the score to a string
char buffer[50];
sprintf(buffer, "SCORE %i", this->world.getPlayer()->score);
SDL_Color color = { 0x00, 0x00, 0x00 };
SDL_Surface* surface = TTF_RenderText_Solid(this->eightbitwonder, buffer, color);
SDL_Texture* texture = SDL_CreateTextureFromSurface(this->renderer, surface);
int w, h;
SDL_QueryTexture(texture, NULL, NULL, &w, &h);
//printf("w: %i, h: %i\n", w, h);
SDL_Rect srcRect = {0, 0, w, h};
SDL_Rect dstRect = {16, 64, w, h};
SDL_RenderCopy(this->renderer,
texture,
NULL,
&dstRect);
SDL_DestroyTexture(texture);
SDL_FreeSurface(surface);
}
void Game::drawDucks() {
for (list<Duck>::iterator duck = this->world.getDuckIterator(); duck != this->world.getDuckEnd(); duck++) {
// Only worry about drawing the duck if it's visible
if (duck->isVisible(*world.getPlayer())) {
SDL_Rect duckSrcRect;
if (duck->status == killedByPlayer) {
// Draw explosion if the duck was killed by the player
duckSrcRect = (SDL_Rect){ 4 * 64, 0, 64, 64 };
}
else {
// Otherwise draw the normal sprite
duckSrcRect = (SDL_Rect){ duck->getFrame() * 64, 0, 64, 64 };
}
// a = Duck
// b = Player
//((a . b) / (b . b)) * b
// Vector representation of the position of the duck
Vector2 duckVector = duck->position.toVector2();
// vector representation of the player's angle
Vector2 playerVector = this->world.getPlayer()->getVector();
// Polar coordinate of the edge of the player's FOV at the distance of the duck
Polarcoord edgeFov = duck->position;
edgeFov.theta = this->world.getPlayer()->angle + (this->world.getPlayer()->FOV / 2);
//printf("Player FOV: %f\nPlayer FOV / 2: %f\nedgeFOV.theta: %f\nplayerAngle: %f\nDuck angle: %f\n", this->world.getPlayer()->FOV.radVal, (this->world.getPlayer()->FOV / 2).radVal, edgeFov.theta.radVal, this->world.getPlayer()->angle.radVal, duck->position.theta.radVal);
// Vector representation of the edge of the player's FOV
Vector2 edgeFovVector = edgeFov.toVector2();
// Refer to the below image for the following variables:
// Where a is the duck and b is the player:
// https://upload.wikimedia.org/wikipedia/commons/9/98/Projection_and_rejection.png
//
// Projection vector (a1 on the image) of the edge of the FOV
Vector2 edgeProjection = edgeFovVector.project(playerVector);
// Rejection vector (a2 on the image) of the edge of the FOV (the maximum size the duck rejection vector can be)
Vector2 edgeRejection = edgeFovVector - edgeProjection;
// Projection vector (a1 on the image) of the duck
Vector2 projection = duckVector.project(playerVector);
// Rejection vector (a2 on the image) of the duck
Vector2 rejection = duckVector - projection;
//printf("Rejection: [%f,%f]\n", rejection.x, rejection.y);
//printf("Magnitude of edge of fov rejection: %f\nMagnitude of duck rejection: %f\n", edgeRejection.magnitude(), rejection.magnitude());
// A ratio between the two rejection vectors to determine where on the screen the duck should go
double duckDistance = rejection.magnitude() / edgeRejection.magnitude();
// Multiply it by half the width of the screen to get an actual pixel value
duckDistance *= (this->width / 2);
// Ensures the sign is correct
duckDistance *= duckVector.rightOf(playerVector);
//printf("Duck distance: %f\n", duckDistance);
//printf("[%f, %f]\n", rejection.x, rejection.y);
//printf("Projection magnitude: %f\n Rejection magnitude: %f\n", projection.magnitude(), rejection.magnitude());
double scaleFactor = 1000 * (1.f / pow(duck->position.r, 2));
//printf("********Scale factor: %f\n", scaleFactor);
Vector2 duckSize(scaleFactor * 64.f, scaleFactor * 64.f);
SDL_Rect duckDstRect = {
((this->width / 2) + (duckDistance)) - (duckSize.x / 2),
(this->height / 2) - (duckSize.y / 2),
duckSize.x,
duckSize.y};
//now taken care of in duck->update()
//duck->setFrame((duck->getFrame()+1) % 4);
int result = SDL_RenderCopy(this->renderer, this->spriteTexture, &duckSrcRect, &duckDstRect);
//if (result < 0)
//printf("Calling RenderCopy: %s\n", SDL_GetError());
}
}
}
int Game::run() {
bool quit = false;
bool restart = false;
this->state = titleScreen;
SDL_Event e;
while (!quit) {
SDL_PumpEvents();
const Uint8 *keystate = SDL_GetKeyboardState(NULL);
SDL_Delay(10); // Wait 100ms before trying again when the stack of events becomes empty
if (keystate[SDL_SCANCODE_ESCAPE]) {
quit = true;
}
// Fritz - turn left pressed
if (keystate[SDL_SCANCODE_LEFT] || digitalRead(LEFT_PIN) ){
if (this->state == game) {
printf("Turning left.\n");
this->world.getPlayer()->turnLeft(Radian(1));
}
}
// Fritz - turn right pressed
if (keystate[SDL_SCANCODE_RIGHT] || digitalRead(RIGHT_PIN)){
if (this->state == game) {
printf("Turning right.\n");
this->world.getPlayer()->turnRight(Radian(1));
}
}
// Fritz - trigger pulled
if (keystate[SDL_SCANCODE_SPACE] || digitalRead(TRIGGER_PIN) ){
if (this->state == gameOver) {
restart = true;
quit = true;
}
}
//while (SDL_PollEvent(&e) != 0) { // Pull events from the stack until we can't anymore
////Loop through each type of event
//switch(e.type) {
//case SDL_QUIT:
//quit = true;
//break;
//case SDL_KEYDOWN:
////A key was pressed, switch for which key
//switch(e.key.keysym.sym) {
//case SDLK_ESCAPE: // Esc
//quit = true; // Quit the game
//break;
//case SDLK_LEFT:
//if (this->state == game) {
//printf("Turning left.\n");
//this->world.getPlayer()->turnLeft(Radian(4));
//}
//break;
//case SDLK_RIGHT:
//if (this->state == game) {
//printf("Turning right.\n");
//this->world.getPlayer()->turnRight(Radian(4));
//}
//break;
//case SDLK_SPACE:
//if (this->state == gameOver) {
//restart = true;
//quit = true;
//}
//break;
//}
//}
//}
if (this->state == titleScreen) {
// Fritz - trigger pulled
if (keystate[SDL_SCANCODE_SPACE]) {
this->state = game;
}
}
if (this->state == game) {
double timeBetweenTicks = SDL_GetTicks() - this->lastTicks;
//printf("FPS: %f\n", 1000 * pow(timeBetweenTicks, -1));
this->lastTicks = SDL_GetTicks();
this->duckCounter += timeBetweenTicks;
Uint32 ticksSinceStart = SDL_GetTicks() - this->gameStartTicks;
int difficulty = 5000 - (ticksSinceStart / 30);
//printf("*********difficulty: %i - duckCounter: %i\n", difficulty, this->duckCounter);
if (difficulty < 0) {
difficulty = 0;
}
if (this->duckCounter > difficulty) { // Every five seconds, spawn a new duck.
Duck d(Radian(rand() % 360), 40);
d.speed = ticksSinceStart / 7000;
this->world.addDuck(d);
this->duckCounter -= difficulty;
}
for (list<Duck>::iterator duck = this->world.getDuckIterator(); duck != this->world.getDuckEnd(); duck++) {
duck->update();
// Fritz - trigger pulled
if (keystate[SDL_SCANCODE_SPACE]) {
Mix_PlayChannel( -1, Laser, 0 );
//printf("****************SPACE IS HELD DOWN******************\n");
Vector2 rejection = duck->position.toVector2() - (duck->position.toVector2().project(this->world.getPlayer()->getVector()));
//printf("Magnitude of rejection: %f\n", rejection.magnitude());
if (rejection.magnitude() <= 2 && duck->isVisible(*this->world.getPlayer()) && duck->status != killedByPlayer && duck->status != dead) {
duck->status = killedByPlayer;
duck->frameCounter = 0;
}
}
// Logic for when ducks die
if (duck->status != alive) {
if (duck->status == attackedPlayer) {
// Lower player health
// Fritz - Player hurt
this->world.getPlayer()->loseHealth();
if (this->world.getPlayer()->getHealth() <= 0) {
// Player has died.
// Fritz - player died
this->state = gameOver;
Mix_PlayChannel( -1, GameOver, 0 );
}
}
else if (duck->status == killedByPlayer && !duck->scoreAdded) {
// Raise player score
// Fritz - Duck died
Mix_PlayChannel( -1, DeadDuck, 0 );
this->world.getPlayer()->addScore(duck->speed * 100);
duck->scoreAdded = true;
}else if (duck->status == dead){
// Remove duck from list
duck = this->world.ducks.erase(duck);
}
}
}
// Ensure that the closer ducks are first in the list
this->world.ducks.sort(Duck::compare_distance);
this->world.ducks.reverse();
}
if (this->state == titleScreen) {
}
this->redraw();
}
if (restart) {
return EXIT_RESTART;
}
return EXIT_QUIT;
}
/*
SDL_Surface* Game::convertToSDLSurface(const Mat& img){
//"convert" it to older format, because I found conversation for that, and it's too late for me to rewrite it to the newer Mat
IplImage opencvimg2=(IplImage)img;
IplImage* opencvimg=&opencvimg2;
//do the actual conversation to the good ol' SDL_Surface
SDL_Surface *surface = SDL_CreateRGBSurfaceFrom((void*)opencvimg->imageData,
opencvimg->width,
opencvimg->height,
opencvimg->depth*opencvimg->nChannels,
opencvimg->widthStep,
0xff0000, 0x00ff00, 0x0000ff, 0);
return surface;
}
*/