Necesito crear un juego en línea usando solidez. Los juegos tienen juegos dentro de ellos y cada juego tiene sus respectivos jugadores. se puede comparar con una batalla real en un juego FPS donde hay varias batallas reales que se desarrollan simultáneamente dentro del juego con sus respectivos participantes. Intenté usar una matriz dentro de una estructura para llevar un registro de los juegos. Sin embargo, me he enfrentado a un error tras otro al intentar hacer esto.
La estructura:
struct Game { address[] participants; uint amountRequired; uint Duration; uint id; bool ended; uint createdTime; }La función para crear el juego:
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 }); }Debe inicializar la matriz en una línea separada y luego pasarla a la estructura. Vea la variable _participants en el fragmento:
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); } }Si desea establecer algunos participantes en el código (no pasados desde un argumento), trabajar con una matriz dinámica en la memoria es un poco complicado. Consulte esta respuesta para obtener más información y un ejemplo.
Editar: para agregar participantes a la matriz en una función separada, primero debe almacenar el Game en una variable de almacenamiento. Vea el mapeo de games en mi fragmento de actualización. Luego puede .push() en la matriz de almacenamiento desde una función separada.