SDL小屏幕

时间:2012-01-28 19:49:23

标签: c++ sdl

当我运行此代码试图开始编程俄罗斯方块克隆时它将屏幕打印到一个小矩形(< 30 * 30),屏幕的所有其他部分都是黑色(它应该是绿色)

我知道我不应该只提供所有代码,但我真的不知道错误在哪里

#include <string>
#include <vector>
#include "SDL/SDL.h"

using namespace std;

const unsigned short SCREEN_WIDTH  = 640;
const unsigned short SCREEN_HEIGHT = 480;
const unsigned short SCREEN_BPP    = 32;

const unsigned char Block_Length   = 20;

enum Color {
    Blue = 0,
    Cyan,
    White,
    Red,
    Yellow,
    Magenta,
    Green
};

struct Point {
    int x, y;
};

struct Block {
    public:
        Point l;
        Color c;
};

vector<Block> blocks;

SDL_Surface *Screen = NULL;

void apply_surface(SDL_Surface *Source, SDL_Surface *Target, int x, int y, SDL_Rect *clip = NULL);
bool init();
bool clean_up();
void show_blocks ();

int main(int argc, char** argv) {
    init();

    SDL_FillRect(Screen, NULL, 0x00FF00);

    for (int i = 0; i < 4; i++) {
        Block b;
        b.c = Red;
        b.l.x = i;
        b.l.y = i;
        blocks.push_back(b);
    }

    show_blocks();

    if (SDL_Flip(Screen) == -1)
        return 1;

    SDL_Delay(5000);

    clean_up();

    return 0;
}

void apply_surface(SDL_Surface *Source, SDL_Surface *Target, int x, int y, SDL_Rect *clip) {
    SDL_Rect o;

    o.x = x;
    o.y = y;

    SDL_BlitSurface(Source, clip, Target, &o);
}

bool init() {
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
        return false;

    if (!(Screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE)))
        return false;

    SDL_WM_SetCaption("Hey Tetris!", NULL);

    return true;
}

bool clean_up() {
    SDL_Quit();
}

void show_blocks () {
    SDL_Surface *s = SDL_CreateRGBSurface(SDL_SWSURFACE, Block_Length, Block_Length, 32, 0x0, 0x0, 0x0, 0x0);
    for (int i = 0; i < blocks.size(); i++) {
        Uint64 bColor;
        switch (blocks[i].c) {
            case Blue    : bColor = 0x0000FF; break;
            case Cyan    : bColor = 0x00FFFF; break;
            case White   : bColor = 0xFFFFFF; break;
            case Yellow  : bColor = 0xFFFF00; break;
            case Red     : bColor = 0xFF0000; break;
            case Magenta : bColor = 0xFF00FF; break;
            case Green   : bColor = 0x00FF00; break;
        }
        SDL_FillRect(s, NULL, bColor);
        apply_surface(s, Screen, blocks[i].l.x * Block_Length, blocks[i].l.y * Block_Length);
    }
    SDL_FreeSurface(s);
}

1 个答案:

答案 0 :(得分:1)

乍一看,我来到了这个问题: apply_surface()中的SDL_Rect是否设置正确?在没有宽度和高度的情况下设置x和y会给出一个由于堆栈垃圾而未定义大小的矩形,因为默认构造函数afai不会将rect归零。我将这些成员设置为Source,就像这样:

o.x = x;
o.y = y;
o.w = Source->w;
o.h = Source->h;