2013-12-18 51 views
0

我有一個任務來創建一個像Frogger的遊戲(你知道 - 青蛙必須穿過街道的遊戲)。到目前爲止,我已經創建了青蛙和汽車運動背後的邏輯,但我似乎無法同時運行這些流程。我知道多線程是這樣做的正確方法,但是我在通過_beginthread傳遞參數時遇到了一些麻煩。將參數傳遞給多線程時的功能

這是我到目前爲止有:

void moveCarsLeft(int x, int y) { 
    if (y < 0) { 
     field[x][y + 4] = '_'; 
     Sleep(600); 
     refreshField(); 
     showField(); 
     if (y == -4) { 
      moveCarsLeft(x, WIDTH-1); 
     } 
     moveCarsLeft(x, y - 1); 
    } 
    else { 
     if (y > WIDTH-4) { 
      field[x][y] = '-'; 
      Sleep(600); 
      refreshField(); 
      showField(); 
      moveCarsLeft(x, y - 1); 
     } 
     else { 
      field[x][y + 4] = '_'; 
      field[x][y] = '-'; 
      Sleep(600); // this is what's messing up the whole thing 
         // it stops the whole program 
         // and that's why I think I need multithreading 
      refreshField(); 
      showField(); 
      moveCarsLeft(x, y - 1); 
     } 
    } 
} 

void moveCarsRight(int x, int y) { 
... // the opposite of moveCarsLeft() 
} 

... 
int main() { 
... 
    _beginthread(moveCarsLeft, 0, what do I put here?); 
... 
} 

所以,我會非常感激,如果有人能告訴我正確的方式來實現這一功能。在此先感謝:]

+0

「我在這裏放什麼?」 - 這很大程度上取決於你想要運行什麼。 –

+0

你不清楚「爲什麼」這必須在多線程。即使它做了你想在每個部分做什麼。 –

+0

我添加了更多代碼供您查看,但實際上我只想知道如何使用_beginthread將參數傳遞給我的函數。 我並不是要求更有效的方式來編寫我的程序。 –

回答

4

你並不真的需要多線程...一個典型的舊式遊戲引擎將是:

while(1) 
{ 
    userInput = ReadUserInput(); 
    currentGameStatus = UpdateGameStatus(oldGameStatus, userInput); 
    DrawScreen(currentGameStatus); 
    oldGameStatus = currentGameStatus; 
} 
當然

這僅僅是僞代碼,掌握基本的想法。但是如果你想使用多線程,你可以使用一個共享的遊戲狀態容器,運行線程可以訪問和/或修改(你需要用一些互斥鎖來保護關鍵部分)。

如果你使用多線程,那麼會期望一些小的併發問題(例如,青蛙在它實際發生在屏幕上之前被汽車運行,或者相反),因爲你失去了由單個循環給出的完美狀態順序,遊戲一步一步完成

+0

好的,你說服了我; d我會嘗試這種方法:] –

0

「我在這裏放什麼?」

你把一個指針指向一個結構。您可以定義結構以包含您想要傳遞的所有參數。