2017-04-19 73 views
-1

我正在嘗試製作一個簡單的文本遊戲,但遇到了一個奇怪的問題。我有一個課程設置爲使用SDL_KEYDOWN從用戶鍵盤輸入內容。當調用函數check_event()時,它會運行一個循環,輪詢鍵盤輸入並返回按鈕的字符串。奇怪的是,按下按鍵沒有效果。該代碼停止我的while循環,但它似乎像我的功能根本沒有任何作用。SDL鍵盤輸入不觸發

這裏是我的主要代碼:

#include <iostream> 
#include <fstream> 
#include <SDL.h> 
#include "SDL_ttf.h" 
#include "input.h" 


using namespace std; 

Input input; 

int main(int argc, char* argv[]) { 
    if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0) { 
      SDL_Log("Unable to initialize SDL: %s", SDL_GetError()); 
      return 1; 
     } 

    cout << "Welcome to Hero V1.0!" << endl; //intro stuff 
    cout << "Written By: Jojo" << endl; 
    cout << endl; 

    cout << "1) New Game" << endl; 
    cout << "2) Continue Game" << endl; 


    while (true) { 
     string event = input.check_event(); 
     if(event == "1"){ 
      cout << "Test" << flush; 
     } 
    } 

    SDL_Quit(); 
    return 0; 
} 

這裏是我的輸入類的.cpp

#include <iostream> 
#include <SDL.h> 
#include "Input.h" 
using namespace std; 
string Input::check_event() { 
    while (SDL_PollEvent(&event)) { 
      if(event.type == SDL_KEYDOWN){ 
       switch(event.key.keysym.sym){ 
       case SDLK_1: 
        return "1"; 
       } 
      } 
     } 
     return "null"; 
    } 

任何幫助是極大的讚賞。

+1

你似乎並沒有已經創建了一個窗口。 SDL沒有buitin全系統輸入抓取功能(出於許多原因,這可能是有問題的或者不可能實現的)。對於文本遊戲按鍵,您需要從標準輸入讀取(read,getch,...)。 – keltar

回答

0

有多個紅旗。

首先,std::cout不適用於。圖書館使用窗口,而不是控制檯/終端。如果您想呈現文字,請閱讀適當的教程。

其次,如果您尚未初始化事件處理程序,則無法檢查事件。您應該在循環之前添加SDL_Event event;

第三,使用處理輸入是不必要的,這是更適合:

bool quit = false; 
SDL_Event event; 

while (!quit) 
{ 
    while (SDL_PollEvent(&event) != 0) 
    { 
     if (event.type == SDL_QUIT) 
     { 
      quit = true; 
     } 

     // Add if blocks, switch statements, and what have you 
    } 
}