-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrincipalDatabase.sol
105 lines (93 loc) · 2.92 KB
/
PrincipalDatabase.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
pragma solidity ^0.4.24;
import "./ThirdParty/Ownable.sol";
import "./ThirdParty/ERC721/ERC721Token.sol";
/*
Database of principals. Supports basic data manipulating functions.
*/
contract PrincipalDatabase is Ownable, ERC721Token
{
struct Principal
{
uint id;
string name;
uint dna;
uint reputation;
uint power;
uint readyTime;
}
/*
Supported types of DNA fragment. Each DNA fragment has 8 bits and
stores information regarding to its representing type. A Celebrity's
DNA has 256 bits, so in theory 32 kinds of DNA fragment can exist
at the same time.
*/
enum EDnaFragment
{
ELEMENTAL,
GENDER,
HEIGHT,
FACE,
HAIR_COLOR,
EYE_COLOR
}
event PrincipalCreated(uint id, string name, uint dna);
Principal[] public principals;
mapping (uint => address) public principalToOwner;
mapping (address => uint) ownerPrincipalsCount;
constructor()
Ownable()
ERC721Token("CryptoPrincipal", "CP")
internal
{}
function _createPrincipal(string _name, uint _dna) internal returns (uint _id)
{
_id = principals.length;
_mint(msg.sender, _id);
principalToOwner[_id] = msg.sender;
ownerPrincipalsCount[msg.sender]++;
principals.push(Principal(_id, _name, _dna, 0, 0, now));
emit PrincipalCreated(_id, _name, _dna);
}
/*
Given a DNA and the type of the DNA fragment, extracts and returns the
DNA fragment.
*/
function getDnaFragment(uint _dna, EDnaFragment _type) public pure returns (uint8)
{
uint shiftedDna = _dna / (2 ** (uint(_type) * 8));
return uint8(shiftedDna & 0xFF);
}
/*
Injects a 8-bit sized DNA fragment into a given DNA. An enum is also
needed in order to specify the type of the DNA fragment.
*/
function getInjectedDna(uint _dna, uint8 _dnaFragment, EDnaFragment _type) public pure returns (uint _injectedDna)
{
uint multiplier = 2 ** (uint(_type) * 8);
uint clearedDna = _dna & ~(0xFF * multiplier);
_injectedDna = clearedDna | (_dnaFragment * multiplier);
}
/*
Get principals by owner address
*/
function getPrincipalsByOwner(address _owner) external view returns(uint[]) {
uint[] memory result = new uint[](ownerPrincipalsCount[_owner]);
uint counter = 0;
for (uint i = 0; i < principals.length; i++) {
if (principalToOwner[i] == _owner) {
result[counter] = i;
counter++;
}
}
return result;
}
/*
Generates a random DNA given a string. The string served as a seed for
the random number generator.
*/
function generateRandomDna(string _string) internal pure returns (uint)
{
uint rand = uint(keccak256(abi.encodePacked(_string)));
return rand;
}
}