0

学校の課題のために、ランダムな長さ 4 の戦艦 (水平または垂直) が 8x8 ゲームボードに生成される戦艦ゲームを作成する必要があります。プレイヤーは、船を沈めようとする 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 row1 = rand() % 8;
    int col1 = rand() % 8;
    do 
    {
        int row2 = rand() % 3 + (row1 - 1);
        int col2 = rand() % 3 + (col1 - 1);
    } while (row2 != row1 && col2)
    int col3 = rand()
    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;
    }
}

おそらくご覧のとおり、私は「生成」機能に苦労しています。私の目標は、8x8 2D ベクトル内に完全に収まる 4x1 の船 (水平または垂直) をランダムに 1 つ生成することです。アドバイス/ヘルプ/コメントをいただければ幸いです。

4

1 に答える 1

1

方向と位置の 2 つのランダムな選択肢があります。

方向によって有効な位置が決まるため、まず方向 (水平または垂直) をランダムに選択することをお勧めします。

次に、船の左上の位置をランダムに選択します。方向が水平の場合、x 位置は 0 から 7-3 の間、y は 0 から 7 の間である必要があります。方向が垂直の場合、y 位置は 0 から 7-3 の間であり、x は 0 から 7 の間である必要があります。

ところで、これらの番号をハードコーディングしないようにしてください。後でボードと船のサイズを簡単に変更できるように、定数を使用することをお勧めします。

于 2016-01-03T21:32:54.237 に答える