计算C++战舰游戏中两个随机点之间的距离



所以,我的问题是如何计算两个随机点(x,y(之间的距离,这样我就可以使用abs方法(就像我在Function bool CheckColpo中开始做的那样(,并告诉玩家他的射击是否真的在敌舰位置的范围内。你怎么能计算出两个随机事物之间的距离?我应该如何处理?我知道在我找到两点之间的距离后,我需要使用abs函数。我有一个朋友试图向我解释,但我想我头脑太笨了。我是编程新手,C++是我学习的第一门语言,我希望有人能为我指明方向。

这是我的代码:

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
const int RIGHE = 10;
const int COLONNE = 10;
const char NAVE = 'N';
const char MARE = '~';
int x = -1;
int y = -1;
int choice1;
int choice2;
char board[RIGHE][COLONNE];
//Funzione per stampare la griglia 10x10 con il For//
void StampaGriglia() {
cout << "Here's the board : n";
for (int i = 0; i < RIGHE; ++i)
{
for (int k = 0; k < COLONNE; ++k)
{
cout << board[i][k];
}
cout << endl;
}
}
void TurnoPlayer() {
do {
cout << "Enter the ship to sink :";
cin >> choice1;
cout << endl;
cout << "Enter your second ship :";
cin >> choice2;
if (choice1 == x && choice2 == y)     // IN CASO AVESSI VOLUTO FARE CON IL CHAR NAVE : board[choice1][choice2] == nave;//
{
cout << "Boom, you sank it! ";
}
else
{
cout << "Retry! ";
}
cout << endl;

} while (choice1 < 0 || choice1 >  RIGHE || choice2 < 0 || choice2 > COLONNE);
}

bool PlayAgain(string question)
{
char again;
cout << question;
cin >> again;
return again == 'y';
}
bool CheckColpo() {
x = abs
}

int main()
{
do {
//INSERISCI IN TUTTE LE CELLE UN VALORE BASE (MARE)//
for (int i = 0; i < RIGHE; ++i)
{
for (int k = 0; k < COLONNE; ++k)
{
board[i][k] = MARE;
}
}
srand(static_cast<unsigned int>(time(0)));
x = rand() % 10;
y = rand() % 10;
board[x][y] = NAVE;
cout << "x :" << x << "y: " << y;
do
{
StampaGriglia();
TurnoPlayer();
} while (choice1 != x || choice2 != y);
} while (PlayAgain("Vuoi Giocare Ancora? (y/n)"));
return 0;
}

非常感谢,如果我写这篇文章的方式不对,我会立即采取行动纠正。

首先(x,y(只是一个随机点。你的函数需要两个点来计算它们之间的距离,无论点是否随机,计算距离的方法都是一样的。

您无法定义距离的含义。你可以指勾股距离,但你不需要abs。也许你的意思只是垂直和水平距离差的总和,这被称为曼哈顿距离,你需要abs,但在计算了距离之后就不需要了。

由于不清楚,这里有几个距离计算函数,选择你认为最好的

#include <cstdlib>
#include <cmath>
double pythagorean_distance(int x1, int y1, int x2, int y2)
{
return sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
}
int manhatten_distance(int x1, int y1, int x2, int y2)
{
return abs(x2 - x1) + abs(y2 - y1);
}

最新更新