c++ - 计算 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) 只是一个随机点。您的函数将需要两个点来计算它们之间的距离,并且无论点是否随机,计算距离的方式都是相同的。
您没有定义distance的含义。你可能指的是毕达哥拉斯距离,但你不需要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);
}
推荐阅读
- javascript - 无法设置未定义打字稿的属性 0
- python-3.x - 尝试为 python3 安装 pytables
- powershell - 根据 Powershell 中的列值删除 CSV 行
- javascript - 如何同时测试表单上的所有输入?
- javascript - 如果我的登录数据无效,帮助文本没有显示我的错误并且我的错误消息没有出现
- matlab - Matlab:树状图轴背景颜色
- javascript - 鼠标悬停在 Chrome 浏览器上的日期和时间选择器图标上时的光标指针
- kubernetes - MiniKube,通过 localhost:3306 访问数据库 pod?
- node.js - 使用 aws-sdk 在 Docker 容器中运行 Node 应用程序
- c# - 我可以在 C# 中将字符串附加到 Func 吗?