对于学校作业,我必须创建一个战舰游戏,在8x8游戏板中生成一个随机4长度战列舰(水平或垂直)。玩家有15枚鱼雷试图沉没船只。我使用了2D矢量,并且完成了以下代码:
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;
void generateship(vector<vector<int> >&field);
void fire(vector<vector<int> >&field);
void display(const vector<vector<int> >field);
int main()
{
srand(time(0));
vector<vector<int> >field(8);
for (int x = 0; x < field.size(); x++)
field[x].resize(8);
for (int x = 0; x < field.size(); x++)
for (int y = 0; y < field[y].size(); y++)
field[x][y] = 0;
generateship(field);
fire(field);
system("pause");
return 0;
}
void generateship(vector<vector<int> >&field)
{
int row, col;
int direction = rand() % 4;
switch (direction)
{
case 0: row = rand() % 5 + 3;
col = rand() % 8;
field[row][col] = 1;
field[row - 1][col] = 1;
field[row - 2][col] = 1;
field[row - 3][col] = 1;
break;
case 1: row = rand() % 8;
col = rand() % 5;
field[row][col] = 1;
field[row][col + 1] = 1;
field[row][col + 2] = 1;
field[row][col + 3] = 1;
break;
case 2: row = rand() % 5;
col = rand() % 8;
field[row][col] = 1;
field[row + 1][col] = 1;
field[row + 2][col] = 1;
field[row + 3][col] = 1;
break;
case 3: row = rand() % 8;
col = rand() % 5 + 3;
field[row][col] = 1;
field[row][col - 1] = 1;
field[row][col - 2] = 1;
field[row][col - 3] = 1;
break;
}
display(field);
}
void fire(vector<vector<int> >&field)
{
int row, col;
int torps = 15;
int hitcounter = 0;
while (hitcounter != 4 || torps != 0)
{
cout << torps << " torpedoes remain. Fire where? ";
cin >> row >> col;
switch (field[row][col])
{
case 0: cout << "Miss!" << endl << endl;
field[row][col] = 2;
break;
case 1: cout << "Hit!" << endl << endl;
field[row][col] = 3;
hitcounter = hitcounter + 1;
break;
case 2: cout << "Missed again!" << endl << endl;
break;
case 3: cout << "Hit again!" << endl << endl;
break;
}
torps = torps - 1;
display(field);
}
if (hitcounter == 4)
cout << "You win!";
else if (torps == 0)
cout << "You are out of torpedoes! Game over.";
}
void display(const vector<vector<int> >field)
{
for (int row = 0; row < 8; row++)
{
for (int col = 0; col < 8; col++)
{
switch (field[row][col])
{
case 0: cout << ". ";
break;
case 1: cout << ". ";
break;
case 2: cout << "X ";
break;
case 3: cout << "O ";
break;
}
}
cout << endl;
}
}
但是当我运行代码时,会出现一个大的对话框,上面写着“致命错误”之类的内容,并询问我是否要中止或重试。在我的编译器中,它说代码没有任何问题。我滥用双向量吗? (这是我第一次实施它们。)
感谢任何帮助!
答案 0 :(得分:3)
问题1(根本原因):
在初始化过程中,内循环使用了错误的大小。 编辑: 当y达到8时,您因此尝试在循环条件下访问字段[8],并且您已经超出界限:
double[] res =
DoubleStream.of(arr).map(d -> Math.pow(Math.tan(d + 3.4), 2.3)).toArray();
请注意,您可以通过针对以下初始化交换3 for循环来简化初始化:
for (int x = 0; x < field.size(); x++)
for (int y = 0; y < field[x].size(); y++) // not field[y] !!
field[x][y] = 0;
问题2(高风险):
然后在vector<vector<int> >field(8, vector<int>(8,0) );
中,您要求用户fire()
和row
:
col
但是你没有检查输入是否无效。如果用户无意中使用范围1..8插入0..7,你将超出范围。