猜数字游戏
// 猜数字游戏
// 游戏规则:4个0-9之间的随机数由系统生成,每一位各不相同
// 数字猜对并且位数也对,A++
// 只猜对数字,B++
const readline = require('readline-sync');
// 判断数字是否重复函数 如果重复 则为真 返回true 如果不重复 则为假 返回false
const isRepeat = function(arr){
for(let i=0;i<arr.length - 1;i++){
for(let j=i+1;j<arr.length;j++){
if(arr[i] === arr[j]){
// 如果能够进入到此if 说明这个数组里面存在重复的元素
return true;
}
}
}
return false
}
// 生成随机数函数
const randomNum = function(){
let num; // 用于存放0-9之间的随机数
let comNum = []; // 该数组用于存放最终生成的 4 位数
while(true){
comNum.length = 0; // 这一点很重要 要将comNum数组清空 否则里面的数字会越来越多
for(let i=0;i<4;i++){
num = Math.floor(Math.random()*10);
comNum.push(num);
}
if(!isRepeat(comNum)){
return comNum;
}
}
}
// 程序的主入口
const main = function(){
// guessNum 用于接收用户输入的数字 a 和 b 分别代表 A 和 B的个数 chance代表游戏机会
let guessNum,a = 0,b = 0,chance = 10;
// comNum 用于存放电脑生成的随机数
let comNum = randomNum();
// 鼓励语句
let arr = ['加油!','还差一点了','你马上就要猜中了','很简单的,再想想','也许你需要冷静一下'];
while(chance){
console.log('请输入你要猜测的数字');
guessNum = readline.question('');
if(guessNum.length != 4){
console.log('你输入的数字的位数不正确,请重新输入!');
} else if(isNaN(Number(guessNum))){
console.log('你输入的数字有问题!请重新输入!');
} else {
// 判断是否重复 需要将字符串转换为数组
guessNum = [...guessNum];
if(!isRepeat(guessNum)){
// 如果能够进入到此 if 说明玩家输入的数字是OK的 可以开始进行判断
for(let i=0;i<guessNum.length;i++){
for(let j=0;j<comNum.length;j++){
if(guessNum[i] == comNum[j]){
// 如果能够进入到此 if 说明数字相同
if(i === j){
// 如果进入此 if 说明 位置也相同
a++;
} else {
b++;
}
}
}
}
if(a === 4){
// 如果进入此 if 说明玩家全部猜对了 跳出while
break;
} else {
console.log(`${a}A${b}B`);
chance--;
if(chance !== 0){
let index = Math.floor(Math.random()*arr.length);
console.log(`你还剩下${chance}次机会,${arr[index]}`);
}
a = b = 0; // 清空 a 和 b 的值
}
} else {
console.log('你输入的数字重复了, 请重新输入!')
}
}
}
// 如果跳出了上面的while 说明游戏结束了 但是 分为 2 种情况
// 1. 提前猜对了 2. 机会用完了
if(chance === 0){
// 进入此 if 说明是机会用完了
console.log('很遗憾,你已经没有机会了!');
console.log(`电脑生成的随机数为${comNum}`);
} else {
console.log('恭喜你,猜测正确,游戏结束');
console.log('Thank you for playing');
}
}
main();

浙公网安备 33010602011771号