Projects

# Project 01 ```html <section class="container" v-if="winner"> <h2>Game Over</h2> <h3 v-if="winner === 'monster'">You lost!</h3> <h3 v-else-if="winner === 'player'">You won!</h3> <h3 v-else>It's a draw</h3> <button @click="startGame">Start a new game!</button> </section> <section id="controls" v-else> <button @click="attackMonster">ATTACK</button> <button :disabled="useSpecialAttack" @click="specialAttackMonster">SPECIAL ATTACK</button> <button @click="healPlayer">HEAL</button> <button @click="surrender">SURRENDER</button> </section> <section id="log" class="container"> <h2>Battle Log</h2> <ul> <li v-for="logMessage in logMessages"> <span></span> {{logMessage.actionBy}} - {{logMessage.actionType}} - {{logMessage.actionValue}} </li> </ul> </section> ``` ```javascript function getRandomValue(min, max){ return Math.floor(Math.random() * (max - min)) + min; } const app = Vue.createApp({ data() { return { playerHealth: 100, monsterHealth: 100, currentRound: 0, winner: null, logMessages: [] } }, watch:{ playerHealth(value){ if(value == 0 && this.monsterHealth == 0){ this.winner = "draw"; } if(value == 0 && this.monsterHealth > 0){ this.winner = "monster"; } if(value > 0 && this.monsterHealth == 0){ this.winner = "player"; } } }, computed: { monsterBarStyle(){ return {width: this.monsterHealth + '%'} }, playerBarStyle(){ return {width: this.playerHealth + '%'} }, useSpecialAttack(){ return this.currentRound % 3 != 0 } }, methods: { startGame(){ this.playerHealth = 100; this.monsterHealth = 100; this.currentRound = 0; this.winner = null; this.logMessages = []; }, attackMonster(){ const attackValue = getRandomValue(5, 12); if(this.monsterHealth - attackValue <= 0){ this.monsterHealth = 0; }else { this.monsterHealth -= attackValue; } this.currentRound++; this.addLogMessage('player', 'attack', attackValue); this.attackPlayer(); }, attackPlayer(){ const attackValue = getRandomValue(8, 15); if(this.playerHealth - attackValue <= 0){ this.playerHealth = 0; }else { this.playerHealth -= attackValue; } this.addLogMessage('monster', 'attack', attackValue); }, specialAttackMonster(){ const attackValue = getRandomValue(10, 25); if(this.monsterHealth - attackValue <= 0){ this.monsterHealth = 0; }else { this.playerHealth -= attackValue; } this.currentRound++; this.addLogMessage('player', 'special-attack', attackValue); this.attackPlayer(); }, healPlayer(){ const healValue = getRandomValue(8, 20); if(this.playerHealth + healValue > 100){ this.playerHealth = 100; }else { this.playerHealth += healValue; } this.addLogMessage('player', 'heal', healValue); }, surrender(){ this.winner = "monster"; }, addLogMessage(who, what, value){ this.logMessages.unshift({ actionBy: who, actionType: what, actionValue: value }); } }, }); app.mount('#game') ```