开发者

C++ and SDL problem

I want to blit surfaces that I've created in two classes. One is called Map, that holds the relevant map vector as well as some other stuff. The other is a Tile class. There is a problem when I run the program.

开发者_JAVA技巧

I get no errors, and the program runs as it should. Any ideas? It's probably a stupid mistake somewhere.

Map populate

    void map::Populate(map M)
    for(int x=0;x<=19;x++)
    {
        for(int y=0;y<=15;y++)
        {
            int y2 = (y*32);
            int x2 = (y*32);
            Tile T(x2,y2);
            M.AddToMap(&T);
            printf("Added Tile");

Render

    void map::Render(SDL_Surface* screen)
    {
    for(int x=0;x<grid.size();x++)
    {
            printf("test");
            Tile* T = grid[x];
            SDL_Surface* k = T->GetIcon();
            SDL_Rect dstrect;
            dstrect.x = (screen->w - k->w) / 2;
            dstrect.y = (screen->h - k->h) / 2;
            SDL_BlitSurface(k, 0, screen, &dstrect);


You're not stating what the problem actually is, just that the program "runs as it should".

Problems in your code:

int x2 = (y*32); should likely be x*32.

void map::Populate(map M) takes a map by value - this copies the map you pass, and any changes will not be visible in the passed map. map & M passes a reference, so changes will be seen in the map you pass.

M.AddToMap(&T) adds a pointer to the local Tile variable, which gets invalidated each iteration of the inner loop. More likely you want new Tile(T) there, or better yet a smart pointer such as boost's shared_ptr. Remember that you also need to delete those Tiles if you don't use a smart pointer.

New code:

void map::Populate(map & M)
for(int x=0; x<20; x++)
{
    for(int y=0; y<16; y++)
    {
        int y2 = (y*32);
        int x2 = (x*32);
        M.AddToMap(new Tile(x2,y2));
        printf("Added Tile");


You are adding a reference to a local variable to your map in Populate. If the method doesn't make a copy of the input, this is most likely wrong. Make a copy (pass by value) or store a smart pointer to your Tile. Of course you can store a plain old pointer, but make sure to delete those Tiles in the end!


Assuming your problem is that the image doesn't show up you may need to post the setup code for the screen and surfaces so we can see if that is the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜