SDL Small Screen

SDL Small Screen

本文关键字:Screen Small SDL      更新时间:2023-10-16

当我运行此代码尝试开始编程俄罗斯方块克隆时,它将屏幕打印成一个小矩形(<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);
}

我第一眼就想到了这个问题:是否正确设置了apply_surface()中的SDL_Rect?由于堆栈垃圾,只设置x和y而不设置宽度和高度,会产生一个大小未定义的rect,因为默认构造函数afaik没有将该rect归零。我会将这些成员设置为Source,就像这样:

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