【CryptZombies】レッスン4チャプター10:ゾンビの勝利
チャプター4では、0から100の乱数を計算しました。今度はその乱数を使って、誰が闘いに勝つかを決めて、それに従って成績を更新してみます。
テストの実行
①ifステートメントを作成し、rand変数がattackVictoryProbability変数 より少ないか同等 であるかチェックするようにせよ。
ifの後にスペースをつけるのを忘れずに…!
function attack(uint _zombieId, uint _targetId) external ownerOf(_zombieId) { Zombie storage myZombie = zombies[_zombieId]; Zombie storage enemyZombie = zombies[_targetId]; uint rand = randMod(100); if (rand <= attackVictoryProbability) }
②もしこの条件が真であれば、我らがゾンビの勝利だ!従って、
a. myZombieのwinCountを増やせ。
attack()関数ですでに定義しましたが、myZombieはstorage内のzombies[_zombieId]を示すポインタなので、次のようになります。
function attack(uint _zombieId, uint _targetId) external ownerOf(_zombieId) { Zombie storage myZombie = zombies[_zombieId]; Zombie storage enemyZombie = zombies[_targetId]; uint rand = randMod(100); if (rand <= attackVictoryProbability) { myZombie.winCount++; } }
b. myZombieのlevelを増やせ。 (レベルアップだ!!!!!!!)
aと同様に、myZombieはstorage内のzombies[_zombieId]を示すポインタなので、次のようになります。
function attack(uint _zombieId, uint _targetId) external ownerOf(_zombieId) { Zombie storage myZombie = zombies[_zombieId]; Zombie storage enemyZombie = zombies[_targetId]; uint rand = randMod(100); if (rand <= attackVictoryProbability) { myZombie.winCount++; myZombie.level++; } }
c. enemyZombieのlossCountを増やせ。 (敗者だ!!!!!! )
enemyZombieはstorage内のzombies[_targetId]を示すポインタなので、次のようになります。
function attack(uint _zombieId, uint _targetId) external ownerOf(_zombieId) { Zombie storage myZombie = zombies[_zombieId]; Zombie storage enemyZombie = zombies[_targetId]; uint rand = randMod(100); if (rand <= attackVictoryProbability) { myZombie.winCount++; myZombie.level++; enemyZombie.lossCount++; } }
d. feedAndMultiply関数を動かすのだ。関数を呼び出す構文を見るには、zombiefeeding.solをチェックせよ。三番目の引数(_species)に、"zombie"の文字列を渡せ。(今はまだ何も起こらないのだが、後でゾンビをベースとして新たなゾンビを生みだす機能を追加できるからな。)
feedAndMultiply関数の構文は次のとおり。
function feedAndMultiply(uint _zombieId, uint _targetDna, string _species) internal ownerOf(_zombieId) { 中略 }
関数を呼び出すために、(uint _zombieId, uint _targetDna, string _species)が必要です。
_zombieIdは、attack関数内で使用しているので、そのまま使います。
_targetDnaについては、enemyZombieはstorage内のzombies[_targetId]を示すポインタなので、enemyZombie.dnaになります。
回答は次のようになります。
function attack(uint _zombieId, uint _targetId) external ownerOf(_zombieId) { Zombie storage myZombie = zombies[_zombieId]; Zombie storage enemyZombie = zombies[_targetId]; uint rand = randMod(100); if (rand <= attackVictoryProbability) { myZombie.winCount++; myZombie.level++; enemyZombie.lossCount++; feedAndMultiply(_zombieId, enemyZombie.dna, "zombie"); } }
お疲れさまでした!
<参考>
CryptoZombies - イーサリアム上でゲームを開発する方法を学習。Powered by Loom Network