0

我制作了这个方法,它为坐标创建了一个二维数组,并将对象(物品、宝藏、敌人)放置在随机位置。我想创建一个新方法来接收当前的 Player 对象(这样我就可以保留当前的 ​​hp、stats、points)并在随机位置生成一组坐标和对象。

void Game::newGame() {
    srand(time(0));

    int count = 0;
    int row = 0;
    int col = 0;

    Room* newRoom = new Room;
    room = newRoom;
    m_alive = true;

    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            room->aRoom[i][j] = NULL;
        }
    }

    //spawn player at 0,0
    room->aRoom[0][0] = new Player("Lemmiwinks", rand()%9+11, rand()%6+7, rand()%6+7);
    m_player = room->aRoom[0][0];
    room->currentRow = 0;
    room->currentCol = 0;
    printMoves();

    //spawn boss
    room->aRoom[rand()%rows][cols-1] = new Boss("Demon Lord", rand()%9 + 10, rand()%7 + 8, rand()%7 + 8);

    //spawn meat cleaver
    count = 0;
    while(count < 1) {
        row = rand()%rows;
        col = rand()%cols;
        if (room->aRoom[row][col] == NULL) {
            room->aRoom[row][col] = new Item("Rusty Shank", 0, 3, 1);
            count++;
        }
    }

    //spawn barrel lid
    count = 0;
    while(count < 1) {
        row = rand()%rows;
        col = rand()%cols;
        if (room->aRoom[row][col] == NULL) {
            room->aRoom[row][col] = new Item("Barrel Lid", 0, 1, 3);
            count++;
        }
    }

    //place potion at random loc
    count = 0;
    while(count < 2) {
        row = rand()%rows;
        col = rand()%cols;
        if (room->aRoom[row][col] == NULL) {
            room->aRoom[row][col] = new Item("Potion", 10, 0, 0);
            count++;
        }
    }   

    //place 5 enemies at random loc
    count = 0;
    while(count < 5) {
        row = rand()%rows;
        col = rand()%cols;
        if (room->aRoom[row][col] == NULL) {
            room->aRoom[row][col] = new Enemy("Demon", rand()%5 + 5, rand()%4 + 4, rand()%4 + 4);
            count++;
        }
    }

    //place 5 treasures at random loc
    count = 0;
    while(count < 5) {
        row = rand()%rows;
        col = rand()%cols;
        if (room->aRoom[row][col] == NULL) {
            room->aRoom[row][col] = new Treasure("Artifact", rand()%5 + 5);
            count++;
        }
    }

    cout << "\n---Stats---" << endl;
    m_player->printEntity();

}

有什么办法可以欺骗这个方法并传入一个玩家对象,这样我就可以在新地图上重用同一个玩家?

4

1 回答 1

1

不确定这是否是您所追求的,但应该这样做:

void Game::newGame() {

...
    if (!m_player) {
        m_player = new Player("Lemmiwinks", rand()%9+11, rand()%6+7, rand()%6+7);
    }
    room->aRoom[0][0] = m_player; 
...
}

void Room::clear(Item* player) {
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            if (room->aRoom[i][j] != player) {
                delete room->aRoom[i][j];
            }
            room->aRoom[i][j] = NULL;
        }
    }
}

我会考虑为您的游戏对象使用智能指针。也许您已经是,但我无法从您的示例代码中看出。

您总是可以重新构建您的程序并简单地拥有一个游戏对象列表,每个对象都包含其坐标。这将避免在游戏逻辑的其余部分中对可能较大的二维数组进行迭代。还可能避免您将遇到的许多双重派遣。

于 2012-05-25T08:13:41.837 回答