战舰游戏-随机坐标c++

Battleships game - Random co-ordinates c++

本文关键字:坐标 c++ 随机 游戏      更新时间:2023-10-16

好了,我修复了我的代码。我可以生成5个随机坐标并将它们保存在我的数组中,但我需要确保坐标不会重复。我试图将每个坐标保存在一个单独的数组中,并使用if语句,但我不知道如何做到这一点。有人能给我一些建议吗?这是我的代码到目前为止…

#include <iostream>
#include <ctime>
#include <stdlib.h>
using namespace std;
int main() 
{
  int *x, *y;
  int a, b;
  int randNum2, randNum;
  char arr[5][5]={{0}};
  srand(time(0));

  x = &randNum;
  y = &randNum2; 

for( a = 0 ; a < 5 ; a++ ){
randNum = (rand() % 5); 
    randNum2 = (rand() % 5);
      arr[*x][*y] = 'S';
   }

   return 0;
}

你的代码不能正常工作的原因有很多!

char arr[5][5] = {{255}};

很可能会做一些你意想不到的事情:它只将arr[0][0]初始化为255,然后将所有其他值初始化为0

因此,xy的有效范围实际上是在0到4之间,但rand() % 5 + 1给你一个1到5之间的随机整数。因此,您可以不初始化二维数组的所有项,或者破坏内存。

对于剩余的代码,它不是自给自足的。H应该是什么?

#include <iostream>
#include <ctime>
#include <stdlib.h>
using namespace std;
int main() 
{
    int x, y;
    char arr[5][5]={{255}};
    srand(time(0));
    for(x = 0; x < 5; x++) 
    {
        for(y = 0; y < 5; y++) 
        {
            int randNum = (rand() % 5) + 1; 
            int randNum2 = (rand() % 5) + 1;    
            if(x==randNum && y==randNum2)
                cout<< (arr[x][y] = 'H');
            else
                cout<< (arr[x][y] = 255);
        }
        cout<<endl;
    }
    return 0;
}

给出的输出类似于

�����
�����
��H��
�����
�����
�����
��H��
���H�
����H
�����

…等等,有时没有h

现在你告诉我这应该是什么