猜单词游戏(JavaScript及vue版)

let rs = require('readline-sync')

let words = 'apple banana orange'
let words_arr = words.split(' ')
// console.log(words_arr);

let r_idx = Math.floor(Math.random() * words_arr.length)
let select_word = words_arr[r_idx]
// console.log(select_word);

let true_arr = select_word.split('')
// console.log(true_arr);
let char_arr = new Array(select_word.length)
char_arr.fill('-')
console.log(char_arr);

let guess_times = 5
while(guess_times > 0){
    let guess_char = rs.question('input one char\n')
    let b_find = false
    for(let i = 0; i < true_arr.length; i++){
        if(true_arr[i] === guess_char){
            char_arr[i] = guess_char;
            b_find = true;
        }
    }
    if(!char_arr.includes('-')){
        break
    }
    if(b_find === false){
        guess_times--
        console.log(`you have ${guess_times} chance left`);
    }

    console.log(char_arr);
}

if(guess_times > 0){
    console.log('you win');
}
else{
    console.log('you lose');
}

vue版

<script setup>
import {ref} from 'vue'
let words = 'apple banana orange'
let words_arr = words.split(' ')

let r_idx = Math.floor(Math.random() * words_arr.length)
let select_word = ref('')
select_word = words_arr[r_idx]

let true_arr = select_word.split('')
let char_arr = ref([])
char_arr = new Array(select_word.length)
char_arr.fill('-')
let guess_char = ref('');
let guess_times = ref(5);


function submit(){
  let b_find = false
    for(let i = 0; i < true_arr.length; i++){
        if(true_arr[i] === guess_char.value){
            char_arr[i] = guess_char.value;
            b_find = true;
        }
    }
    guess_char.value=''
    console.log(char_arr);
    if(!char_arr.includes('-')){
        guess_times.value =100
    }
    if(b_find === false){
        guess_times.value--
    }
}

</script>

<template>
  <div>
    <h2 v-if="guess_times === 0">you lose 正确答案是{{ select_word }}</h2>
    <h2 v-else-if="guess_times <= 5">还有<span>{{ guess_times }}</span>次机会</h2>
    <h2 v-else>you win</h2>
    <ul>
      <li v-for="item in char_arr">{{ item }}</li>
    </ul>
  </div>
  请输入要猜测的字符:<input size="1" maxlength="1" v-model="guess_char" type="text" @keyup.enter="submit">
</template>

<style scoped>
ul{
  display: flex;
  list-style: none;
}
span{
  color:red;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值