Source

asteroids / src / Game.cpp

Full commit
  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
// Game.cpp
// Copyright (c) 2011 James O'Doherty
// All Rights Reserved.

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <algorithm>

#include <boost/shared_ptr.hpp>
#include <boost/pointer_cast.hpp>
#include <boost/bind.hpp>
#include <boost/functional.hpp>

#include "Common.h"

#include <SDL.h>

static SDL_Surface *screen = NULL;

#include "Ship.h"
#include "Bullet.h"
#include "Asteroid.h"
#include "Game.h"

using namespace std;

Game::Game()
{
    int width, height;
    // Initialize SDL subsystems
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) < 0) {
        cerr << "Error, couldn't initialize SDL: " 
             << SDL_GetError() << endl;
        exit(EXIT_FAILURE);
    }
    atexit(SDL_Quit);

    // Initialize SDL screen
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    screen = SDL_SetVideoMode(800, 600, 0, 
                              SDL_OPENGL | SDL_HWSURFACE | SDL_RESIZABLE);

    if (!screen) {
        cerr << "Error, video initialization failed: " 
             << SDL_GetError() << endl;
        exit(EXIT_FAILURE);
    }

    width = screen->w;
    height = screen->h;

    // Initialize GLEW 
    GLenum err = glewInit();
    if (GLEW_OK != err) {
        cerr << "Error, glewInit failed: " 
             << glewGetErrorString(err) << endl;
        exit(EXIT_FAILURE);
    }

    // Set up the screen
    reshape(width, height);

    // Set up our audio service
    audio = GetAudioServiceInstance();

    // Initialize sprites and scene data list
    boost::shared_ptr<Ship> splayer(new Ship());
    player = splayer;
    sprites.push_back(splayer);
}

Game::~Game()
{
    audio->release();
}

void Game::run()
{
    srand(static_cast<unsigned int>(time(NULL)));

    // Start playing background music
    audio->playTrack(r_bg_music_track);

    // Prepare game loop
    bool quit = false;
    Uint32 ticks = SDL_GetTicks();
    const Uint32 delta = 20;

    // Run game loop
    while (!quit) {
        quit = poll();
        // Update game physics if the correct time delta has passed
        while (SDL_GetTicks() > ticks + delta) {
            update();
            ticks += delta;
        }
        // Render screen and sprites
        draw();
        // Detect and report OpenGL error conditions
        while (GLenum error = glGetError() != GL_NO_ERROR) {
            cerr << gluErrorString(error) << endl;
        }
    }
}

void Game::toggleFullScreen()
{
    // *todo*
}

void Game::reshape(int w, int h)
{
    if (h == 0)
        h = 1;
    GLfloat aspectRatio = (GLfloat)w/(GLfloat)h;

    // Set up the OpenGL project screen
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    // Fill the entire window
    glViewport(0,0,w,h);
    // Center the projection on 0,0 and ensure an x,y
    // range of at least 100 in all 4 directions is visible.
    if (w <= h) {
        left = 0;
        bottom = (h-w)/2;
        width = w;
        height = w;
        glOrtho(-100.0,100.0,-100.0/aspectRatio,100.0/aspectRatio,0,1);
    } else {
        bottom = 0;
        left = (w-h)/2;
        width = h;
        height = h;
        glOrtho(-100.0*aspectRatio,100.0*aspectRatio,-100.0, 100,0,1);
    }

    glMatrixMode(GL_MODELVIEW);
    glDisable(GL_DEPTH_TEST);
    glLoadIdentity();

    glClearColor(0.0f,0.0f,0.0f,0.0f);
    glClear(GL_COLOR_BUFFER_BIT);
}

void Game::update()
{
    static int step = 3;

    vector< boost::shared_ptr<Sprite> >::iterator it;
    vector< boost::shared_ptr<Sprite> >::iterator it2;

    vector< boost::shared_ptr<Sprite> >::iterator list_it;
    vector< boost::shared_ptr<Sprite> > add_list;

    if (sprites.size() < 2) {
        for (int i=0; i<step; i++) {
            boost::shared_ptr<Sprite> a(new Asteroid(rand()%16+12.0f+step));
            sprites.push_back(a);
        }
        step++;
    }
    for_each(sprites.begin(), sprites.end(), 
            boost::bind(&Sprite::preUpdateHandler,_1));
    for_each(sprites.begin(), sprites.end(), boost::bind(&Sprite::update,_1));
    for_each(sprites.begin(), sprites.end(), 
            boost::bind(&Sprite::postUpdateHandler,_1));
    sprites.erase(remove_if(sprites.begin(), sprites.end(),
                    boost::bind(&Sprite::isOutOfBounds, _1)), sprites.end());
    for (it = sprites.begin(); it != sprites.end();) {
        if ((*it)->isOutOfBounds())
            it = sprites.erase(it);
        else
            it++;
    }

    it = sprites.begin();
    while (it != sprites.end()) {
        it2 = it;
        it2++;
        while (it2 != sprites.end()) {
            if ((*it)->detectCollision(**it2)) {
                // Use runtime type information to determine the appropriate
                // course of action for the sprites.

                // A more flexible method would be to create a SpriteManager
                // class that all sprites have a delegate to and require
                // Sprite class descendents implement a collision event
                // handler. Then every class would have everything it
                // needs to handle events.

                // I haven't gotten around to doing that yet.
               
                // Do we have an asteroid hitting an asteroid?
                Asteroid *a1 = dynamic_cast<Asteroid *>(it->get());
                Asteroid *a2 = dynamic_cast<Asteroid *>(it2->get());

                if (a1 && a2) {
                    // Back up the asteroids so they don't overlap
                    while ((*it)->detectCollision(**it2)) {
                        a1->reverse();
                        a2->reverse();
                    }
                    // Now bounce the asteroids off of each other
                    a1->collide(*a2);
                    #ifdef DEBUG
                    cout << "a and a" << endl;
                    #endif
                    continue;
                } 

                // Now check to see if we have a bullet hitting a bullet
                boost::shared_ptr<Bullet> b1 =
                    boost::dynamic_pointer_cast<Bullet>(*it);
                boost::shared_ptr<Bullet> b2 =
                    boost::dynamic_pointer_cast<Bullet>(*it2);

                if (b1 && b2) {
                    it = sprites.erase(it);
                    sprites.erase(it2);
                    #ifdef DEBUG
                    cout << "b and b" << endl;
                    #endif
                    goto next_iteration;
                }

                // Now check to see if we have a bullet hitting an asteroid
                Asteroid *a = NULL;
                boost::shared_ptr<Bullet> b;
                if (a1)
                    a = a1;
                else if (a2)
                    a = a2;
                if (b1)
                    b = b1;
                else if (b2)
                    b = b2;
                if (a && b) {
                    // Spawn baby asteroids if the asteroid is 
                    // big enough and hasn't been disabled
                    Asteroid *children[4];
                    if (a->createChildren(children)) {
                        // Children created successfully
                        for (int i=0; i<4; i++) {
                            boost::shared_ptr<Sprite> child(children[i]);
                            add_list.push_back(child);
                        }
                        audio->playSample(r_explosion_sample);
                    } else {
                        audio->playSample(r_smallexplosion_sample);
                    }
                    Point position = a->getLocation();
                    add_list.push_back(boost::shared_ptr<Sprite>(new
                                        Explosion(position.x, position.y)));
                    a->disable();
                    sprites.erase(it2);
                    it = sprites.erase(it);
                    #ifdef DEBUG
                    cout << "a and b" << endl;
                    #endif
                    goto next_iteration;
                }

                // Did something hit the player then?
                if ((*it == player || *it2 == player) && player->isAlive()) {
                    // Just kill the player. 
                    audio->playSample(r_explosion_sample);
                    player->kill();
                } 
            }
            it2++;
        } 
        {
            boost::shared_ptr<Explosion> e =
                                boost::dynamic_pointer_cast<Explosion>(*it);
            if (e && e->isFinished()) {
                it = sprites.erase(it);
                goto next_iteration;
            }
        }
        it++;
        next_iteration:;
    }

    // Prune new objects added on top of existing ones.
    list_it = add_list.begin();
    while (list_it != add_list.end()) {
        bool erase = false;
        for (it=sprites.begin(); it != sprites.end(); it++) {
            if ((*list_it)->detectCollision(**it)) {
                erase = true;
                break;
            }
        }
        if (erase)
            list_it = add_list.erase(list_it);
        else
            list_it++;
    }
    // Now add all the objects we created in this update step
    for (list_it = add_list.begin(); list_it != add_list.end(); list_it++) {
        sprites.push_back(*list_it);
    } 
}

void Game::draw()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0f, 1.0f, 1.0f);
    
    glEnable(GL_SCISSOR_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glScissor(left, bottom, width, height);
    for_each(sprites.begin(), sprites.end(), boost::bind(&Sprite::draw,_1));
    glDisable(GL_BLEND);
    glDisable(GL_SCISSOR_TEST);

    glPushAttrib(GL_CURRENT_BIT);
    // Draw border of field area
    glColor3f(1.0f, 1.0f, 1.0f);
    glLineWidth(2.0f);
    glBegin(GL_LINES);
        glVertex2i(-100, -100);
        glVertex2i(100, -100);
        glVertex2i(100, -100);
        glVertex2i(100, 100);
        glVertex2i(100, 100);
        glVertex2i(-100, 100);
        glVertex2i(-100, 100);
        glVertex2i(-100, -100);
    glEnd();
    glPopAttrib();
    SDL_GL_SwapBuffers();
}

bool Game::poll()
{
    bool quit = false;
    static AudioHandle thrustSample = -1;

    // Poll Events
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
        switch (event.type) {
            case SDL_KEYDOWN:
                switch (event.key.keysym.sym) {
                    case SDLK_UP:
                    case SDLK_w:
                        player->setAccelerate();
                        if (player->isAlive())
                            thrustSample = audio->playSample(r_thrust_sample, -1);
                        break;
                    case SDLK_LEFT:
                    case SDLK_a:
                        player->setLeft();
                        break;
                    case SDLK_RIGHT:
                    case SDLK_d:
                        player->setRight();
                        break;
                    case SDLK_ESCAPE:
                        quit = true;
                        break;
                    default:
                        break;
                }
                break;
            case SDL_KEYUP:
                switch (event.key.keysym.sym) {
                    case SDLK_UP:
                    case SDLK_w:
                        player->clearAccelerate();
                        if (thrustSample != -1)
                            audio->stopSample(thrustSample);
                        thrustSample = -1;
                        break;
                    case SDLK_LEFT:
                    case SDLK_a:
                        player->clearLeft();
                        break;
                    case SDLK_RIGHT:
                    case SDLK_d:
                        player->clearRight();
                        break;
                    case SDLK_SPACE:
                        if (player->isAlive()) {
                            sprites.push_back(boost::shared_ptr<Sprite>(player->fire()));
                            audio->playSample(r_fire_sample);
                        }
                        else
                            player->revive();
                        break;
                    case SDLK_F11:
                        toggleFullScreen();
                        break;
                    default:
                        break;
                }
                break;
            case SDL_VIDEORESIZE:
                screen = SDL_SetVideoMode(event.resize.w,
                                          event.resize.h,
                                          0,
                                          screen->flags);
                reshape(event.resize.w, event.resize.h);
                break;
            case SDL_QUIT:
                quit = true;
                break;
            default:
                break;
        }
    }
    return quit;
}