Solidity

幫助使用和閱讀數組和映射

  • January 22, 2018

我正在嘗試做一些非常簡單的事情。我想製作一個保存玩家數據的結構。

在這些數據中,我想要一個數組來儲存它的庫存,以及它目前的雞蛋/怪物。

但是我根本無法與數組互動,我經常遇到問題。有人能告訴我我做錯了什麼以及為什麼它不允許我讀取和返回數組嗎?

contract EtherMon{ 
   uint public starterEgg;
   address public owner;



   struct player{
       uint256 goldAmount;
     uint[10] listOfEggs;
       bool eggCoolDown;
       uint eggTime;
       uint eggID;
       bool battleCoolDown;
       bool breedingCoolDown;
       uint[] ownedEthermon;
   }

     mapping (address => player) public listOfPlayers;

   function EtherMon(){
       owner = msg.sender;

   }

   function createAccount(){


    starterEgg = block.timestamp % 10;

    listOfPlayers[msg.sender].goldAmount  = 100;
    listOfPlayers[msg.sender].listOfEggs[0] = starterEgg;


       }



 function getCurrentEggs() returns (uint[]) {
uint length =  listOfPlayers[msg.sender].listOfEggs.length;
uint[] eggArray;
           for(uint i = 0; i < length; i++){
              eggArray[i] =  listOfPlayers[msg.sender].listOfEggs[i];
           }
           return eggArray;
       }

   }

基本上我只是想能夠…

  1. 呼叫 CreateAccount 並將隨機 uint 儲存到儲存玩家持有的雞蛋的數組中
  2. 從映射中提取雞蛋數據並查看/更改它

有人可以給我一個包含數組的結構範例(和映射,因為我似乎可以在結構中使用映射,但動態數組有問題)並且具有 getter 和 setter 函式?

以下是一些可能對您有所幫助的模式。

pragma solidity ^0.4.15;

contract Storage {

   struct PlayerStruct {
       uint meaningless;
       uint[] dynamicList;
       uint[10] fixedList;
       mapping(bytes32 => uint) keyToUintMap;
   }

   mapping(address => PlayerStruct) public playerStructs;

   function getPlayerDynListLength(address player) public constant returns(uint count) {
       return playerStructs[player].dynamicList.length;
   }

   function appendPlayerDynList(address player, uint value) public returns(uint length) {
       return playerStructs[player].dynamicList.push(value);
   }

   function setPlayerDynFixedList(address player, uint index, uint value) public returns(bool success) {
       require(index <= 9);
       playerStructs[player].fixedList[index] = value;
       return true;
   }

   function getPlayerDynamicListElement(address player, uint index) public constant returns(uint value) {
       return playerStructs[player].dynamicList[index];
   }

   function setPlayerMappedElement(address player, bytes32 key, uint value) public returns(bool success) {
       playerStructs[player].keyToUintMap[key] = value;
       return true;
   }

   function getPlayerMappedElement(address player, bytes32 key) public constant returns(uint value) {
       return playerStructs[player].keyToUintMap[key];
   }

}

更新:

這是在 Remix 中顯示它的工作:

在此處輸入圖像描述

希望能幫助到你。

引用自:https://ethereum.stackexchange.com/questions/28680