使用具有可靠性的嵌套数组

Making use of a nested Array with solidity

大家好,我公司的一个客户希望使用 solidity 创建一个在线游戏。游戏中有游戏,每个游戏都有各自的玩家。它可以比作 FPS 游戏中的大逃杀,其中有各种大逃杀与各自的参与者同时在游戏中进行。我尝试在结构中使用数组来记录游戏。但是,我在尝试执行此操作时遇到错误。任何建议的建议将不胜感激。

结构:

struct Game {
        address[] participants;
        uint amountRequired;
        uint Duration;
        uint id;
        bool ended;
        uint createdTime;
    } 

创建游戏的函数:

function CreateGame(uint amountRequired, string memory timeoption) public restricted{
        setGameDuration(timeoption);
        gameid++;

        Game memory newGame = Game({
            participants: address[] participants,
            amountRequired: amountRequired,
            Duration: gametime,
            id: gameid,
            ended: false,
            createdTime: block.timestamp

        });
        
    }

您需要在单独的一行中初始化数组,然后将其传递给结构。请参阅代码段中的 _participants 变量:

pragma solidity ^0.8;

contract MyContract {
    struct Game {
        address[] participants;
        uint amountRequired;
        uint Duration;
        uint id;
        bool ended;
        uint createdTime;
    }

    // create a storage mapping of value type `Game`
    // id => Game
    mapping(uint => Game) public games;

    function CreateGame(uint amountRequired, string memory timeoption) public {
        // dummy values
        address[] memory _participants; // empty array by default
        uint gametime = 1;
        uint gameid = 1;

        Game memory newGame = Game({
            participants: _participants,
            amountRequired: amountRequired,
            Duration: gametime,
            id: gameid,
            ended: false,
            createdTime: block.timestamp
        });

        // store the `memory` value into the `storage` mapping
        games[gameid] = newGame;
    }

    function addParticipant(uint gameId, address participant) public {
        require(games[gameId].createdTime > 0, "This game does not exist");
        games[gameId].participants.push(participant);
    }
}

如果你想在代码中设置一些参与者(不是从参数传递),在内存中使用动态数组有点棘手。有关详细信息和示例,请参阅 this answer

编辑:要在单独的函数中将参与者添加到数组中,您需要先将 Game 存储在存储变量中。请参阅我的更新片段中的 games 映射。然后你可以.push()从一个单独的函数进入存储数组。