首页 > 解决方案 > 键盘事件未在 sdl 的 cpp 中加载

问题描述

hello当我点击键时,我试图让它成为我的屏幕打印a......当我按下2键时切换图像......但是当我这样做时,没有任何反应,我不知道为什么......它没有给我由于某些奇怪的原因而出现错误...如果您有任何想法,请在下面的评论中告诉我。我已经列出了那里的代码!

#include <SDL.h>
#include <iostream>

int main(int argc, char* argv[])
{
    SDL_Window* window = nullptr;
    SDL_Surface* WindowSurface = nullptr;
    SDL_Surface* image1 = nullptr;
    SDL_Surface* image2 = nullptr;
    SDL_Surface* currentImage = nullptr;
    SDL_Init(SDL_INIT_VIDEO);
    window = SDL_CreateWindow("sdl Window",
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, 
        SDL_WINDOW_SHOWN);
    WindowSurface = SDL_GetWindowSurface(window);
    image1 = SDL_LoadBMP("Red_sheet_full_2.bmp");
    image2 = SDL_LoadBMP("Red_sheet_fullA.bmp");
    currentImage = image2;
    bool isRunning = true;
    SDL_Event ev;
    while (isRunning)
    {
        while (SDL_PollEvent(&ev) != 0);
        {
            if (ev.type == SDL_QUIT)
                isRunning = false;
            else if (ev.type == SDL_KEYDOWN)
            {
                switch (ev.key.keysym.sym)
                    case SDLK_a:                         
                        printf("hello");
                break;
                switch (ev.key.keysym.sym)
                    case SDLK_2:
                        currentImage = image1;
                break;
            }
        }
     
        SDL_BlitSurface(currentImage, NULL, WindowSurface, NULL);
        SDL_UpdateWindowSurface(window);
    }
    
    SDL_FreeSurface(image1);
    SDL_FreeSurface(image2);
    SDL_DestroyWindow(window);
   
    currentImage = image1 = image2 = nullptr;
    window = nullptr;
    
    SDL_Quit();

    return 0;
}

标签: c++

解决方案


问题出在switch声明中。thebreakswitchso 之外,如果您收到的第一个事件不是SDLK_a,它将while在打印之前跳出循环hello并退出。

这是正在发生的事情的简化版本:https ://godbolt.org/z/9eEcEYGhj

#include <iostream>

int main(int argc, char* argv[])
{
    while (true)
    {
        char c{'p'};
        switch (c)
            case 'a':
                std::cout << "a\n";
        break;  // exits without printing anything
        switch (c)
            case 'b':
                std::cout << "b\n";
        break;
        std::cout << c;
    }
}

你有不同的方法来修复它。

一种是以适当的方式编写switch声明:https ://godbolt.org/z/99MohaTMx

#include <iostream>

int main(int argc, char* argv[])
{
    while (true)
    {
        char c{'a'};
        switch (c)
        {
            case 'a':
                std::cout << "a\n";  // forever prints "a\n"
                break;
            case 'b':
                std::cout << "b\n";
                break;
            default:
                break;
        }
    }                     
}

另一个,仅用于您当前的实现,将使用 anif-else if而不是 a switch


推荐阅读