let rs = require('readline-sync')
let words = 'apple banana orange'
let words_arr = words.split(' ')
let r_idx = Math.floor(Math.random() * words_arr.length)
let select_word = words_arr[r_idx]
let true_arr = select_word.split('')
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>