1
\$\begingroup\$

I've learned that magic numbers are bad in code. However, should the coordinates, and rotation angles of all the sprites be stored in variables? Is the convention in game development to leave those hard-coded values as arguments to set the coordinates or the angles of the transformable?

// Create a texture to hold a graphic on the GPU
Texture textureBackground;
// Load a graphic into the texture
textureBackground.loadFromFile("graphics/background.png");
// Create a sprite
Sprite spriteBackground;
// Attach the texture to the sprite
spriteBackground.setTexture(textureBackground);
// Set the spriteBackground to cover the screen
spriteBackground.setPosition(0, 0);
// Create a tree sprite
Texture textureTree;
textureTree.loadFromFile("graphics/tree.png");
Sprite spriteTree;
spriteTree.setTexture(textureTree);
spriteTree.setPosition(810, 0);
// Prepare the bee
Texture textureBee;
textureBee.loadFromFile("graphics/bee.png");
Sprite spriteBee;
spriteBee.setTexture(textureBee);
spriteBee.setPosition(0, 800);
\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

Yes magic numbers are bad, as well as the data like "graphics/bee.png". The problem with that data in your code is that it is hidden, and dispersed across your source code files, and you need to recompile to modify it.

Read about Data Driven Design (and do not confuse with Data Oriented Design). The idea is to separate the code and the data:

We can put the data in an ascii file (txt, csv, JSON, XML, whatever you want) or binary. You will need to parse it in the code. If you need more parameters for your sprites, just add them at the end of each line and modify the code that extracts them.

==Data.csv==
"graphics/background.png",0,0
"graphics/tree.png",810,0
"graphics/bee.png",0,800

And the code does not include any specific data. Just code to parse the elements and do the actions. Also you "don't repeat yourself" (DRY), you avoid copy/paste the same code for each new sprite.

==PseudoCode==
list<Sprite> m_sprites;

for each line in data.csv  {
    std::string fileName;
    int x,y;
    parseLine(line, &fileName, &x, &y);    // extract the components form the csv/txt/binary data file

    Texture texture;
    texture.loadFromFile(fileName);

    Sprite sprite;
    sprite.setTexture(texture);
    sprite.setPosition(x, y);
    m_sprites.push_back(sprite);
}

Now you can run the same code without compiling/linking and just changing the data file, the scene changes.

You separate the design task (decide what to draw and where) from the programming part (draw a sprite in coordinates x,y).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.