2012-06-11 43 views
1

通過網絡搜索後,我沒有找到答案來幫助我。 我的程序是在C.如何在地圖上隨機放置物品?

我有一個項目列表(例如:37 a,22 b,29 c,13 d,19 e,2 f和0 g),我必須隨機將所有這些地圖上的項目(在我的例子中,int [height] [lenght] [7])。 我以爲使用rand來放置物品並循環,直到整個物品被放置,但它使用太多時間和資源。

有沒有一種方法可以輕鬆正確地放置它們?

這裏是我的代碼:

/* allocates the tab in order to place the ressources/items */ 
void   create_map(t_world *world) 
{ 
    unsigned int x; 
    unsigned int y; 

    x = 0; 
    world->map = xmalloc(world->height * sizeof(int**)); 
    while (x < world->height) 
    { 
     y = 0; 
     world->map[x] = xmalloc(world->lenght * sizeof(int*)); 
     while (y < world->lenght) 
     { 
      world->map[x][y] = xmalloc(7 * sizeof(int)); 
      bzero(world->map[x][y], 7); 
      ++y; 
     } 
    ++x; 
    } 
} 

/* base defining the number of required item */ 
t_elevation elevation_tab[] = 
{ 
    {1, {0, 1, 0, 0, 0, 0, 0} }, 
    {2, {0, 1, 1, 1, 0, 0, 0} }, 
    {2, {0, 2, 0, 1, 0, 2, 0} }, 
    {4, {0, 1, 1, 2, 0, 1, 0} }, 
    {4, {0, 1, 2, 1, 3, 0, 0} }, 
    {6, {0, 1, 2, 3, 0, 1, 0} }, 
    {6, {0, 2, 2, 2, 2, 2, 1} } 
}; 

/* calculates the number of item required */ 
unsigned int *calc_elevation(t_world *world) 
{ 
    unsigned int i; 
    unsigned int pos; 
    unsigned int *tab; 

    i = 0; 
    tab = xmalloc(7 * sizeof(int)); 
    bzero(tab, 7); 
    while (i < 7) 
    { 
    pos = 0; 
    while (pos < 7) 
    { 
     tab[pos] += (world->population/
       elevation_tab[i].required_players + 
       world->population % 
       elevation_tab[i].required_players) * 
     (elevation_tab[i].required_ressources[pos]); 
     ++pos; 
    } 
    ++i; 
    } 
    return (tab); 
} 
void   place_ressources(t_world *world, unsigned int *ressources) 
{ 
//here is my missing code 
} 

/*First called function*/ 
void   create_world(t_param *params, t_world *world) 
{ 
    unsigned int *ressources_needed; 

    world->lenght = params->lenght; 
    world->height = params->height; 
    world->population = params->team_size * 2; 
    create_map(world); 
    ressources_needed = calc_elevation(world); 
    place_ressources(world, ressources_needed); 
    show_map(world); 
    world->players = NULL; 
    free(ressources_needed); 
} 

世界是用heigth和lenght用戶決定一定規模的網格。網格中的每個案例都有一個int [7]來提供每個項目的數量。所以我可以將多個項目放在同一個案例中。

+0

你到目前爲止有什麼代碼? – Eregrith

+1

什麼是身高和體長?爲什麼這需要很長時間?你是否必須避免將物品放置在已佔用的方格中?如果是這樣,你如何去做呢? –

+0

已編輯。謝謝 – ss814

回答

0

我可以想出2種可能的方法來解決這個問題,但它將取決於需要處理的項目數量。

我首先想到的是一種類似於如何在計算機程序中洗牌的解決方案。取第一個元素,並隨機生成x,y座標。取下一個元素並生成x,y座標。如果那裏沒有物品,將物品置於該位置,否則生成新的x,y座標。繼續爲所有要放置的元素。

我能想到的另一件事是,如果你能以某種方式跟蹤哪些世界瓷磚已被使用,所以隨機生成的座標不會被重複。

事實上,你的世界對象是一個3d數組是什麼是指數增加的計算。這是絕對必要的嗎?當然,我真的不知道你的程序正在設計什麼上下文

+0

謝謝你的想法,我正在做一點修改。我會回來發佈最終的代碼。我想我可以考慮回答這個問題。感謝大家。 – ss814