如何随机排列数组中的位置

问题描述 投票:0回答:2

我正在尝试编写Minesweeper游戏,为此,我需要随机分配炸弹位置。有人可以帮助您更改一下功能,以便将其随机化吗?

代码:

void Createbomb(int*** bord, int size)//size+1
{
    //bomb num.1
    (*bord)[size - 5][size - 1] = 9;
    //bomb num.2
    (*bord)[size - 4][size - 4] = 9;
    //bomb num.3
    (*bord)[size - 3][size - 2] = 9;
    //bomb num.4
    (*bord)[size - 2][size - 2] = 9;
    //bomb num.5
    (*bord)[size - 1][size - 5] = 9;
}
c arrays visual-studio random minesweeper
2个回答
0
投票

假设您需要的炸弹数量为5。此外,首先让board的所有单元格默认值为1,只有在单元格中存在炸弹的情况下,默认值为9。然后,您可以执行以下操作:

void createBomb(int*** board, int size){
    int numOfBombsPlaced = 0;
    while(numOfBombsPlaced < 5){
        int x = rand()%size;
        int y = rand()%size;
        if ((*board)[x][y]==9):
             continue;
        numOfBombsPlaced++;
        (*board)[x][y] = 9;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.