vue.jsを最近学び始めたので、じゃんけんアプリを作ってみた。
htmlのbodyタグ内
janken.html
<body>
<div id="app">
<!-- 結果 -->
<div>
<p>結果 : {{ result }}</p>
<p>勝ち数 : {{ winCount }}</p>
<p>負け数 : {{ loseCount}}</p>
</div>
<!-- 敵 -->
<div>
<p>敵の手は : {{ enemyHand }}</p>
</div>
<!-- 自分 -->
<button v-on:click="fight('ぐー')">ぐー</button>
<button v-on:click="fight('ちょき')">ちょき</button>
<button v-on:click="fight('ぱー')">ぱー</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="main.js"></script>
</body>
続いて、js
main.js
new Vue({
el: '#app',
data: {
handArr: ['ぐー','ちょき','ぱー'],
enemyHand: '',
result: '',
winCount: 0,
loseCount: 0
},
methods:{
fight: function(myHand){
var index = Math.floor(Math.random()*Math.floor(3));
this.enemyHand = this.handArr[index];
//引き分け
if(myHand === this.enemyHand){
this.result = '引き分け';
}
//勝ち
if(this.enemyHand === 'ぐー' && myHand ==='ぱー'){
this.result = '勝ち';
this.winCount++;
}
if(this.enemyHand === 'ちょき' && myHand ==='ぐー'){
this.result = '勝ち';
this.winCount++;
}
if(this.enemyHand === 'ぱー' && myHand ==='ちょき'){
this.result = '勝ち';
this.winCount++;
}
//負け
if(this.enemyHand === 'ぐー' && myHand ==='ちょき'){
this.result = '負け';
this.loseCount ++;
}
if(this.enemyHand === 'ちょき' && myHand ==='ぱー'){
this.result = '負け';
this.loseCount ++;
}
if(this.enemyHand === 'ぱー' && myHand ==='ぐー'){
this.result = '負け';
this.loseCount ++;
}
}
}
})
完成形
追記
上記if文の処理ですが、インデックスの差と剰余を使い、書くと短く書けるとのアドバイスをいただきましたので、以下に追記させていただきます。ありがとうございました。
main.js
fight: function(myHand){
var index = Math.floor(Math.random() * 3);
this.enemyHand = this.handArr[index];
switch ((index - this.handArr.indexOf(myHand) + 3) % 3) {
case 1:
this.result = '勝ち';
this.winCount++;
break;
case 2:
this.result = '負け';
this.loseCount++;
break;
default:
this.result = '引き分け';
break;
}
}