战舰游戏的随机数生成

时间:2017-11-21 10:17:07

标签: c

我需要为我的任务创建一个战舰游戏,但我不知道如何初始化一个阵列来定位一个大小为5的字符长度的船,我应该如何将它们随机放入20个棋盘中行x 60列。各种帮助真的很感激,谢谢。这是原始数组

void startShips(int ships[][60]) {
    srand(time(NULL));
    int ship, last;

    for (ship = 0; ship < 3; ship++) {
        ships[ship][0] = rand() % 5;
        ships[ship][1] = rand() % 5;

        //let's check if this shot was not tried
        //if it was, just get out of the 'do while' loop when draws a pair that was not tried 
        for (last = 0; last < ship; last++) {
            if ((ships[ship][0] == ships[last][0]) && (ships[ship][1] == ships[last][1]))
                do {
                    ships[ship][0] = rand() % 5;
                    ships[ship][1] = rand() % 5;
                } while ((ships[ship][0] == ships[last][0]) && (ships[ship][1] == ships[last][1]));
        }

    }
}

1 个答案:

答案 0 :(得分:0)

首先,您决定是否水平或垂直显示船舶,以及船上可以采取的最大位置,H和V,而不会离开船上

#define ROWS 20
#define COLS 60

#define SIZE 5

int horiz = rand() % 2; // 1 is horizontal, 0 vertical
int rowmax = horiz ? ROWS - 1 : ROWS - SIZE;
int colmax = horiz ? COLS - SIZE : COLS - 1;

  • rowmax是船舶可能开始显示的最后一行
  • colmax是船舶可能开始展示的最后一栏

然后你随机决定位置

int rowstart = rand() % ( rowmax + 1 );
int colstart = rand() % ( colmax + 1 );

你填满了董事会

int i;
for(i=0 ; i<SIZE ; i++) {
    ships[rowstart + (horiz ? 0 : i)][colstart + (horiz ? i : 0)] = SHIPCHARACTER;
}

说明:数组ships[ROWS][COLS];如果船舶是水平的,则船舶从rowstart开始并停留在同一行,而列从colstart开始,下一个单元格为ships[rowstart][colstart+1],然后ships[rowstart][colstart+2]直到ships[rowstart][colstart+4]。 (反过来,如果它是垂直的)