3

I have this code. My question pretains to struct variables weapons, armour, & stats

enum Armour {Chest, Helm, Boots, Leggings, Gloves, Shield} 
enum Weapon {Sword, Axe, Wand, Gun, Hammer, Fist}

struct Statistics { uint16 testing; }

struct Character {string name;
                  uint dna;
                  mapping (uint => Statistics) stats; 
                  mapping (uint => Weapon[10]) weapons; 
                  Armour[10] armour;                  
    }

Character[] public characters;
Armour[10] armourTest;
Weapon[10] weaponsTest;

I do not see much in http://solidity.readthedocs.io/en/v0.4.21/types.html#enums about enum arrays and mappings of enums as array values.

How can I use struct variables weapons, armour, & stats after I have pushed a character to the public variable characters?

1 Answer 1

6

This is a really abbreviated snippet to give you some ideas. You may be after a more feature-complete relational model like is described here: https://medium.com/@robhitchens/enforcing-referential-integrity-in-ethereum-smart-contracts-a9ab1427ff42

pragma solidity ^0.4.19;

contract RPG {
    enum Armor {Chest, Helm, Boots, Leggings, Gloves, Shield} 
    enum Weapon {Sword, Axe, Wand, Gun, Hammer, Fist}

    struct CharacterStruct {string name;
                      bool isCharacter;
                      uint dna;
                      Armor[] armors; 
                      Weapon[] weapons;                  
        }

    mapping(address => CharacterStruct) public characterStructs;
    address[] public characters;

    modifier onlyIfRegistered() {
        require(characterStructs[msg.sender].isCharacter);
        _;
    }

    function register() public returns(bool success) {
        require(!characterStructs[msg.sender].isCharacter);
        characters.push(msg.sender);
        characterStructs[msg.sender].isCharacter = true;
        return true;
    }

    function addArmor(Armor a) public onlyIfRegistered returns(bool success) {
        characterStructs[msg.sender].armors.push(a);
        return true;
    }

    function getArmor(address player, uint row) public view returns(Armor armor) {
        return characterStructs[player].armors[row];
    }

}

Hope it helps.

3
  • How do you call addArmor() function? Like: addArmor('Chest') or addArmor(0) @Rob Hitchens - B9lab
    – alper
    Commented Jul 8, 2019 at 15:11
  • 1
    The example uses enum for Armor so the input would be a uint8 (0 for 'Chest', 1 for Helm, 2 for Boots, etc.. Syntax depends on your front end. In JS with Truffle, myRPGInstance.addArmor(0)};` Commented Jul 8, 2019 at 15:19
  • Got it so addArmor(<uint8>) will be the correct way to call it
    – alper
    Commented Jul 8, 2019 at 15:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.