此代码适用于用户输入网格大小的游戏,该网格填充0,除了第一行中的1。然后,用户一次输入一个坐标(与大小相同的量)。如果坐标或围绕它的8个空间中有1,则1变为0.如果没有命中,则1向下移动一行。尝试了其他坐标,依此类推。如果在比赛结束时,没有1,那就是“冲锋队”获胜。但是,如果至少1到达最后一排,“redshirts”获胜。基本上,如果所有的坐标都被摄入,并且任何1个仍然存在,那么红衫军就会进入。我的问题在于确定谁获胜。我的最后陈述不正确;我的计划总是说冲锋队赢了,我尝试了很多东西,我不知道如何让它上班(第107-119行)。可能不需要for语句,我只是试着看看是否会修复它。
#include <iostream>
using namespace std;
int ** createField(int N);
int playGame(int ** arr, int N);
int main()
{
int N;
cout << "Enter the number of Redshirts: " << endl;
cin >> N;
int ** arr = createField(N);
**createField(N);
playGame(arr, N);
}
int ** createField(int N)
{
int ** arr = new int *[N];
for (int i = 0; i<N; i++)
arr[i] = new int[N]; //creating array of user size
for (int i = 0; i < N; i++) // fills array with 0's except for first row
{
for (int j = 0; j < N; j++)
{
arr[i][j] = 0;
arr[1][j] = 1;
}
}
return arr;
}
int playGame(int ** arr, int N)
{
int x, y;
cout << "Enter the coordinates of the " << N << " shots: " << endl;
for (int i = 0; i < N; i++)
{
cin >> x >> y;
x = x - 1; // starts grid at 1 vs 0
y = y - 1;
if (x >= N || y >= N)
{
cout << "The coordinate is out of bounds." << endl;
return 0;
}
else
{
if (arr[x][y] == 1) // searches each position for a redshirt (1)
arr[x][y] = 0;
if ((x + 1) != N) // these if statements check that surrounding spaces are not out of bounds
{
if (arr[x + 1][y] == 1)
arr[x + 1][y] = 0;
}
if ((x - 1) >= 0)
{
if (arr[x - 1][y] == 1)
arr[x - 1][y] = 0;
}
if ((y + 1) != N)
{
if (arr[x][y + 1] == 1)
arr[x][y + 1] = 0;
}
if ((y - 1) >= 0)
{
if (arr[x][y - 1] == 1)
arr[x][y - 1] = 0;
}
if ((x - 1) >= 0 && (y - 1) >= 0)
{
if (arr[x - 1][y - 1] == 1)
arr[x - 1][y - 1] = 0;
}
if ((x - 1) >= 0 && (y + 1) != N)
{
if (arr[x - 1][y + 1] == 1)
arr[x - 1][y + 1] = 0;
}
if ((x + 1) != N && (y + 1) != N)
{
if (arr[x + 1][y + 1] == 1)
arr[x + 1][y + 1] = 0;
}
if ((y - 1) >= 0 && (x + 1) != N)
{
if (arr[x + 1][y - 1] == 1)
arr[x + 1][y - 1] = 0;
}
}
for (int y = 0; y < N; y++)
{
if (arr[x][y] == 1) // searches for any redshirts left
{
arr[x + 1][y] = 1; // moves remaining reshirts down one space
arr[x][y] = 0;
}
}
}
for (int x = 0; x < N; x++)
{
for (int y = 0; y < N; y++)
{
if (arr[x][y] == 1) // if redshirts reached end, they win
{
cout << "Redshirts win. " << endl;
return 1;
}
else
{
cout << "Stormtroopers win." << endl;
return 2;
}
}
}
}
答案 0 :(得分:0)
在PlayGame功能的最后,发生的事情是在arr [0] [0],如果是1,则表示Redshirts获胜,否则Stormtroopers获胜,你的代码没有机会检查其他网格。您应该只在嵌套for循环之外移动Stormtrooper获胜消息。
for (int x = 0; x < N; x++)
{
for (int y = 0; y < N; y++)
{
if (arr[x][y] == 1) // if redshirts reached end, they win
{
cout << "Redshirts win. " << endl;
return 1;
}
}
}
cout << "Stormtroopers win." << endl;
return 2;