使用两个数组,以建立一个地图的方向迈出第一步:
// orientation
//
// 7 8 9
// \|/
// 4- -6
// /|\
// 1 2 3
// 0 1 2 3 4 5 6 7 8 9
const int dir_x[] = { 0, -1, 0, 1, -1, 0, 1, -1, 0, 1 };
const int dir_y[] = { 0, 1, 1, 1, 0, 0, 0, -1, -1, -1 };
之前将新的船,如果这个地方是empty
首先你应该测试。
#define BOAT 'B'
#define BOARD_SIZE 10
bool userboat(char boatArray[][BOARD_SIZE], int x, int y, int orientation, int boat_length)
{
if (orientation < 1 || orientation > 9 || orientation == 5 || boat_length < 1)
return false;
int dx = dir_x[orientation];
if (x < 0 || x >= BOARD_SIZE ||
x + dx * boat_length < 0 || x + dx * boat_length > BOARD_SIZE) // test if x is in bounds
return false;
int dy = dir_y[orientation];
if (y < 0 || y >= BOARD_SIZE ||
y + dy * boat_length < 0 || y + dy * boat_length > BOARD_SIZE) // test if y is in bounds
return false;
// test if the boat can be placed
for (int i = 0; i < boat_length; ++ i)
if (boatArray[x+dx*i][y+dy*i] == BOAT) // test if a boat is already there
return false;
// the boat can be placed
for (int i = 0; i < boat_length; ++ i)
boatArray[x+dx*i][y+dy*i] = BOAT;
return true;
}
注意,一个C++解决方案可能是这样的:
const char BOAT = 'B';
const int BOARD_SIZE = 10;
using TBoard = std::array<std::array<char, BOARD_SIZE>, BOARD_SIZE>;
bool userboat(TBoard &boatArray, int x, int y, int orientation, int boat_length)
{
static const std::array<int, 10> dir_x{ 0, -1, 0, 1, -1, 0, 1, -1, 0, 1 };
static const std::array<int, 10> dir_y{ 0, 1, 1, 1, 0, 0, 0, -1, -1, -1 };
try
{
int dx = dir_x.at(orientation);
int dy = dir_y.at(orientation);
// test if the boat can be placed
for (int i = 0; i < boat_length; ++ i)
if (boatArray.at(x+dx*i).at(y+dy*i) == BOAT) // test if a boat is already there
return false;
// the boat can be placed
for (int i = 0; i < boat_length; ++ i)
boatArray[x+dx*i][y+dy*i] = BOAT;
}
catch (...)
{
return false;
}
return true;
}
那么,什么是您的实际问题?什么部分不工作或者你不知道如何检查这些条件? – NathanOliver
整个代码工作不正常,它没有返回正确的值。这是我对解决方案的尝试,但我想不出其他任何东西 – noobprogger
这听起来像您可能需要学习如何使用调试器来逐步执行代码。使用一个好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏离的位置。如果你打算做任何编程,这是一个重要的工具。进一步阅读:** [如何调试小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver