2011-09-12 48 views
0

我正在C++中創建一個名爲Simon Says的遊戲,並希望能夠點擊空格鍵並顯示5個隨機圖像,這些圖像已加載到我的遊戲中。每當我點擊空格鍵時,我都希望圖像的排列順序與之前的不同,因此我需要能夠在命中空格鍵時隨機顯示5個不同的圖像。 下面是代碼我有一組以顯示圖片:在C++中以隨機順序顯示5個圖像

 if(key_down(VK_SPACE)) 
    { 
     clear_screen(); 
     a(); 
     refresh_screen(); 
     delay(1000); 
     clear_screen(); 
     b(); 
     refresh_screen(); 
     delay(1000); 
     clear_screen(); 
     e(); 
     refresh_screen(); 
     delay(1000); 
     clear_screen(); 
     d(); 
     refresh_screen(); 
     delay(1000); 
     clear_screen(); 
     g(); 
     refresh_screen(); 
     delay(1000); 
     clear_screen(); 
     c(); 
     refresh_screen(); 
     delay(1000); 
     clear_screen(); 
     refresh_screen(); 

    } 
+6

究竟是什麼問題? –

+0

相關問題[http://stackoverflow.com/questions/4800534/methods-call-in-random-order-c](http://stackoverflow.com/questions/4800534/methods-call-in-random-order -c) – Bob2Chiv

回答

0

您可以像下面這樣的函數:

//returns random number between 0 and 4, inclusive 
int getRandomInt() { 
    return rand() % 5; 
} 

但是,您必須首先將其用於之前調用srand(someNumber)第一次。系統時間是someNumber的一個很好的候選人,以確保每次運行程序時都不會使用相同的編號。

+0

首選:'返回rand()/(RAND_MAX/6)'(看我的回答和評論) – sehe

0

srand(http://www.cplusplus.com/reference/clibrary/cstdlib/srand/)和rand(http://www.cplusplus.com/reference/clibrary/cstdlib/rand/)可以幫助您生成隨機數字。我會將所有圖像存儲在數組中並繪製隨機索引。但不要兩次繪製任何索引。由於生成隨機數字與顯示圖像相比是一種便宜的操作,因此您可以重複該過程直到找到有效的索引。 WaelJ *的答案將幫助您在數組邊界內生成數字。

1

標準算法std::random_shuffle將把數組(或向量等)放入隨機順序。

它從你的代碼中看出你有不同的函數來繪製每個圖像,所以在這種情況下,你洗牌的東西應該是函數指針。然後,循環(直接或通過std::for_each)在你的混洗陣列(或向量等)上依次調用每個循環並進行清除/刷新/延遲。

+0

好點。是random_shuffle'new'或者什麼的 - 我在 – sehe

+0

之前沒有看到它。自98年以來它一直在每個C++版本中。你需要'#include ' – MSalters

+0

@sehe:不是。許多算法都在[''](http://cplusplus.com/reference/algorithm/random_shuffle/) –

2

這裏是管道(沒有(SDL)庫的細節):使用random_shuffle


編輯是好了很多:

#include <iostream> 
#include <algorithm> 

void a() { std::cout<<"a"<<std::endl; } 
void b() { std::cout<<"b"<<std::endl; } 
void c() { std::cout<<"c"<<std::endl; } 
void d() { std::cout<<"d"<<std::endl; } 
void e() { std::cout<<"e"<<std::endl; } 

int main() 
{ 
    typedef void(*flashfunc)(); 
    static flashfunc flashes[] = {a,b,c,d,e}; 

    std::random_shuffle(flashes, flashes+5); 

    for (flashfunc *flash=flashes; flash!=flashes+5; ++flash) 
     (*flash)(); 

    return 0; 
} 

我最初遺忘關於random_shuffel,並提出了這種做換位洗牌的方式:

#include <ctime> 

template <typename T> 
    bool shuffled(const T&, const T&) 
{ 
int r = rand()/(RAND_MAX/2); 
return 0 != r; 
} 

// ... 
    srand(time(NULL)); 
    std::stable_sort(flashes, flashes+5, shuffled<flashfunc>); 

注意,使用這種方式進行排序,你需要穩定的排序,因爲排序謂語不確定性。

+0

固定rand()邏輯根據[「使用'rand()'」文章](http://eternallyconfuzzled.com/arts/jsw_art_rand。 aspx):** [這個評論很重要的原因是有很多算法似乎一看就是實現序列的隨機混洗,但實際上並不會在N上產生均勻的分佈!可能的順序。也就是說,隨機洗牌很容易出錯。](http://www.sgi.com/tech/stl/random_shuffle.html)**。修復播種現在已經超出了範圍:) – sehe