What's new? | Help | Directory | Sign in
Google
gosu
Cross-platform 2D game development library
  
  
  
  
    
Search
for
Updated Sep 28, 2007 by julianraschke
CppTutorial  
Tutorial for a small game using Gosu and C++.

Source code

The code for the complete game, together with the required media files, can be found in the Gosu distribution of your choice ('examples/Tutorial.cpp'). To run the game, setup a new project as seen in GettingStartedOnOsx, GettingStartedOnWindows or GettingStartedOnLinux, respectively, and use Tutorial.cpp as the only source file.

1. Overriding Window's callbacks

The easiest way to create a complete Gosu application is to write a new class that derives from Gosu::Window (see the reference for a complete description of its interface). Here's how a minimal GameWindow class might look like:

#include <Gosu/Gosu.hpp>
#include <Gosu/AutoLink.hpp> // Makes life easier for Windows users compiling this.

#include <boost/scoped_ptr.hpp> // Used throughout Gosu and this tutorial.
#include <boost/shared_ptr.hpp> // Learn them, they're moving into standard C++!
#include <boost/lexical_cast.hpp> // Could also use <sstream>, just for int <-> string conversion

#include <cmath>
#include <cstdlib>
#include <list>
#include <vector>

class GameWindow : public Gosu::Window
{
public:
    GameWindow()
    : Window(640, 480, false)
    {
        setCaption(L"Gosu Tutorial Game");
    }

    void update()
    {
    }

    void draw()
    {
    }
};

int main(int argc, char* argv[])
{
    GameWindow window;
    window.show();
}

The constructor initializes the Gosu::Window base class. The parameters shown here create a 640x480 pixels large, non-fullscreen (that's what the "false" stands for). Then it changes the window's caption, which is empty until then. Note that Gosu uses std::wstring almost everywhere.

update() and draw() are overrides of Gosu::Window's member functions. update() is (by default) called 60 times per second and should contain the main game logic (move objects etc.).

draw() is called afterwards, whenever the window needs redrawing for other reasons and can be skipped every other time if the FPS go too low. It should contain code to redraw the whole scene—no logic whatsoever!

Then follows the main program. A window is created and its show() member function is called, which does not return until the window has been closed by the user or its own code. Tada - now you have a small black window with a title of your choice!

2. Using Images

class GameWindow : public Gosu::Window
{
    boost::scoped_ptr<Gosu::Image> backgroundImage;

public:
    GameWindow()
    : Window(640, 480, false)
    {
        setCaption(L"Gosu Tutorial Game");
        std::wstring filename = Gosu::sharedResourcePrefix() + L"media/Space.png";
        backgroundImage.reset(new Gosu::Image(graphics(), filename, false));
    }

    void update()
    {
    }

    void draw()
    {
        backgroundImage->draw(0, 0, 0);
    }
};

Note: A scoped_ptr is used here so we can delay creation of the image, and because using smart pointers to handle Gosu resources is something one should get used to. ;)

Gosu::Image's constructor takes three arguments. First, it is tied to a Graphics instance ("graphics()" gives the Window's embedded Graphics object). Second, the file name of the image file is given. Note the sharedResourcePrefix function, which returns The Right Thing; see the reference for more information. The third argument specifies whether the image is to be created with hard borders. See BasicConcepts for an explanation.

As mentioned in the last lesson, the Window's draw() member function is the place to draw everything, so this is the place for us to draw our background image. The arguments are almost obvious. The image is drawn at (0;0) - the third image is the Z position; again, see BasicConcepts.

Player & movement

Here comes a simple player class:

class Player
{
    boost::scoped_ptr<Gosu::Image> image;
    double posX, posY, velX, velY, angle;

public:
    explicit Player(Gosu::Graphics& graphics)
    {
        std::wstring filename = Gosu::sharedResourcePrefix() + L"media/Starfighter.bmp";
        image.reset(new Gosu::Image(graphics, filename));
        posX = posY = velX = velY = angle = 0;
    }

    void warp(double x, double y)
    {
        posX = x;
        posY = y;
    }

    void turnLeft()
    {
        angle -= 4.5;
    }

    void turnRight()
    {
        angle += 4.5;
    }

    void accelerate()
    {
        velX += Gosu::offsetX(angle, 0.5);
        velY += Gosu::offsetY(angle, 0.5);
    }

    void move()
    {
        posX += velX;
        while (posX < 0)
            posX += 640;
        while (posX > 640)
            posX -= 640;

        posY += velY;
        while (posY < 0)
            posY += 480;
        while (posY > 480)
            posY -= 480;

        velX *= 0.95;
        velY *= 0.95;
    }

    void draw() const
    {
        image->drawRot(posX, posY, 1, angle);
    }
};

There are a couple of things to say about this:

Integrating Player with the Window

class GameWindow : public Gosu::Window
{
    boost::scoped_ptr<Gosu::Image> backgroundImage;
    Player player;

public:
    GameWindow()
    : Window(640, 480, false), player(graphics())
    {
        setCaption(L"Gosu Tutorial Game");
        std::wstring filename = Gosu::sharedResourcePrefix() + L"media/Space.png";
        backgroundImage.reset(new Gosu::Image(graphics(), filename, false));

        player.warp(320, 240);
    }

    void update()
    {
        if (input().down(Gosu::kbLeft) || input().down(Gosu::gpLeft))
            player.turnLeft();
        if (input().down(Gosu::kbRight) || input().down(Gosu::gpRight))
            player.turnRight();
        if (input().down(Gosu::kbUp) || input().down(Gosu::gpButton0))
              player.accelerate();
        player.move();
    }

    void draw()
    {
        player.draw();
        backgroundImage->draw(0, 0, 0);
    }
	
    void buttonDown(Gosu::Button btn)
    {
        if (btn == Gosu::kbEscape)
           close();
    }
};

As you can see, we have introduced keyboard and gamepad input! Similar to update() and draw(), Gosu::Window provides two virtual member functions buttonDown(id) and buttonUp(id) which can be overriden, and do nothing by default. We do this here to close the window when the user presses ESC. (For a list of predefined button constants, see the reference). While getting feedback on pushed buttons is suitable for one-time events such as UI interaction, jumping or typing, it is rather useless for actions that span several frames - for example, moving by holding buttons down. This is where the update() member function comes into play, which only calls the player's movement methods. If you run this lesson's code, you should be able to fly around!

3, Simple animations

First, we are going to get rid of the magic numbers for Z positions from now on by replacing them with the following enumeration:

enum ZOrder
{
    zBackground,
    zStars,
    zPlayer,
    zUI
};

What is an animation? A sequence of images. So a naive Animation type might look like this:

typedef std::vector<Gosu::Image> Animation;

However, std::vector expects a type that can be copied, which is not possible for Gosu::Images. Even if they could, it would be a very expensive operation. The easiest solution is to use boost::shared_ptr:

typedef std::vector<boost::shared_ptr<Gosu::Image> > Animation;

And this is exactly what we'll use.

For a real game, there is no way around writing some classes that fit the game's individual needs, but we'll get away with this simple solution for now.

Let's introduce the stars which are the central object of this lesson. Stars appear out of nowhere at a random place on the screen and live their animated lives until the player collects them. The definition of the Star class is rather simple:

class Star
{
    Animation* animation;
    Gosu::Color color;
    double posX, posY;

public:
    explicit Star(Animation& anim)
    {
        animation = &anim;
	
        color.setAlpha(255);
        double red = Gosu::random(40, 255);
        color.setRed(static_cast<Gosu::Color::Channel>(red));
        double green = Gosu::random(40, 255);
        color.setGreen(static_cast<Gosu::Color::Channel>(green));
        double blue = Gosu::random(40, 255);
        color.setBlue(static_cast<Gosu::Color::Channel>(blue));

        posX = Gosu::random(0, 640);
        posY = Gosu::random(0, 480);
    }

    double x() const { return posX; }
    double y() const { return posY; }

    void draw() const
    {
        Gosu::Image& image = 
            *animation->at(Gosu::milliseconds() / 100 % animation->size());

        image.draw(posX - image.width() / 2.0, posY - image.height() / 2.0,
            zStars, 1, 1, color, Gosu::amAdditive);
    }
};

Since we don't want each and every star to load the animation again, we can't do that in its constructor, but rather pass it in from somewhere else. (The Window will load the animation in about three paragraphs.)

To show a different frame of the stars' animation every 100 milliseconds, the time returned by Gosu::milliseconds is divided by 100 and then modulo-ed down to the number of frames. This very image is then additively drawn, centered at the star's position and modulated by a random colour we generated in the constructor.

Now let's add easy code to the player to collect away stars from a list:

class Player
{
    …

    void collectStars(std::list<Star>& stars)
    {
        std::list<Star>::iterator cur = stars.begin();
        while (cur != stars.end())
        {
            if (Gosu::distance(posX, posY, cur->x(), cur->y()) < 35)
                cur = stars.erase(cur);
            else
                ++cur;
        }
    }
};

Now let's extend Window to load the animation, spawn new stars, have the player collect them and draw the remaining ones:

class GameWindow : public Gosu::Window
{
    boost::scoped_ptr<Gosu::Image> backgroundImage;
	Animation starAnim;
	
    Player player;
    std::list<Star> stars;

public:
    GameWindow()
    : Window(640, 480, false), player(graphics())
    {
        setCaption(L"Gosu Tutorial Game");

        std::wstring filename = Gosu::sharedResourcePrefix() + L"media/Space.png";
        backgroundImage.reset(new Gosu::Image(graphics(), filename, false));

        filename = Gosu::sharedResourcePrefix() + L"media/Star.png";
        Gosu::imagesFromTiledBitmap(graphics(), filename, 25, 25, false, starAnim);

        player.warp(320, 240);
    }

    void update()
    {
        …
        player.move();
        player.collectStars(stars);

        if (std::rand() % 25 == 0 && stars.size() < 25)
            stars.push_back(Star(starAnim));
    }

    void draw()
    {
        player.draw();
        backgroundImage->draw(0, 0, 0); 
        for (std::list<Star>::const_iterator i = stars.begin(); i != stars.end(); ++i)
        {
            i->draw();
        }

    }

    …
};

Done! You can now collect stars.

4. Text and sound

Finally, we want to draw the current score using a bitmap font and play a 'beep' sound every time the player collects a star. The Window will handle the text part, loading a font 20 pixels high:

class GameWindow : public Gosu::Window
{
    boost::scoped_ptr<Gosu::Image> backgroundImage;
    Animation starAnim;
    Gosu::Font font;

    Player player;
    std::list<Star> stars;

public:
    ...

    GameWindow()
    : Window(640, 480, false),
        font(graphics(), Gosu::defaultFontName(), 20),
        player(graphics(), audio())
    {
        …
    }

    …

    void draw()
    {
        player.draw();
        backgroundImage->draw(0, 0, zBackground);

        for (std::list<Star>::const_iterator i = stars.begin();
            i != stars.end(); ++i)
        {
            i->draw();
        }

        font.draw(L"Score: " + boost::lexical_cast<std::wstring>(player.getScore()),
            10, 10, zUI, 1, 1, Gosu::Colors::yellow);
    }
};

What's left for the player? Right: A counter for the score, loading the sound and playing it.

class Player
{
    boost::scoped_ptr<Gosu::Image> image;
    boost::scoped_ptr<Gosu::Sample> beep;
    double posX, posY, velX, velY, angle;
    unsigned score;

public:
    Player(Gosu::Graphics& graphics, Gosu::Audio& audio)
    {
        std::wstring filename = Gosu::sharedResourcePrefix() + L"media/Starfighter.bmp";
        image.reset(new Gosu::Image(graphics, filename));

        filename = Gosu::sharedResourcePrefix() + L"media/Beep.wav";
        beep.reset(new Gosu::Sample(audio, filename));

        posX = posY = velX = velY = angle = 0;
        score = 0;
    }

    unsigned getScore() const
    {
        return score;
    }

    …

    void collectStars(std::list<Star>& stars, unsigned& score)
    {
        ...
            if (…)
            {
                cur = stars.erase(cur);
                score += 10;
                beep->play();
            }
            else
        ...
    }

As you can see, loading and playing sound effects couldn't be easier! See the reference for more powerful ways of playing back sounds - fiddle around with volume, position and pitch.

That's it! Everything else is up to your imagination. If you can't imagine how this is enough to create games, see if you can find useful source code from the GosuUsers page.


Sign in to add a comment