zoukankan      html  css  js  c++  java
  • 猜数字游戏

    //猜数字游戏
    //游戏规则:4个0-9之间的随机数由系统生成,每一位各不相同
    //数字猜对并且位数也对,A++
    //只猜对数字,B++
    let readline = require("readline-sync");
    //判断数组是否有重复值,有重复返回1,没有重复返回0
    let isRepeat = function (arr) {
    for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
    if (arr[i] == arr[j]) {
    return 1;
    }
    }
    }
    return 0;
    }
    //电脑生成4位不重复的数字
    let randomNum = function () {
    let num;//用于生成0-9之间的随机数
    let comNum = [];//用于装4个随机数
    while (1) {
    comNum = [];//重要!必须重新初始化数组,否则会造成死循环
    for (let i = 0; i < 4; i++) {
    num = Math.floor(Math.random() * 10);
    comNum.push(num);
    }
    //在不重复的情况下才返回该数组
    if (!isRepeat(comNum)) {
    return comNum;
    }
    }
    }
    let main = function () {
    let guessNum;//用于接收用户输入的数字
    let a = 0, b = 0, chance = 10;//a和b代表A和B的次数,chance是游戏次数,默认为10次
    let comNum = randomNum();//电脑生成4位随机数字
    let saySth = ["加油", "还差一点了", "加油少年", "就快猜中了", "下一次你绝对能猜中", "不要灰心", "继续努力", "你能行的", "整理下思路", "仔细思考一下"];
    //只要chance不为0,就一直循环
    while (chance) {
    console.log("请输入您猜测的数字:");
    guessNum = readline.question("");//guessNum存储用户输入的数字
    //判断输入数字的位数
    if (guessNum.length != 4)
    {
    console.log("您输入的数字的位数不正确");
    }
    else if (isNaN(Number(guessNum)))//判断是否为数字
    {
    console.log("您输入的数字不正确");
    }
    else {
    guessNum = guessNum.split("");//将字符串转为数组
    let repeat = isRepeat(guessNum);//判断数字是否重复
    //如果数字不重复,开始进入判断
    if (repeat == 0) {
    //进行玩家数字和电脑随机数的比较判断
    for (let i = 0; i < guessNum.length; i++) {
    for (let j = 0; j < comNum.length; j++) {
    if (guessNum[i] == comNum[j]) {
    //i和j相同代表位数也相同
    if (i == j) {
    a++;
    }
    else {
    b++;
    }
    }
    }
    }
    //如果a=4代表全对
    if (a == 4) {
    console.log("恭喜你,猜测正确!");
    break;
    }
    else {
    //console.log(comNum);//测试时可以打开,直接看到电脑生成的随机数
    console.log(a + "A" + b + "B");
    chance--;//游戏次数自减
    //chance不为0的时候显示还剩下多少次机会
    if (chance != 0) {
    let index = Math.floor(Math.random() * 10);
    console.log("你还剩下" + chance + "次机会," + saySth[index]);
    }
    //必须重置a和b的值,否则会累加
    a = 0;
    b = 0;
    }
    }
    else {
    console.log("您输入的数字重复了,请重新输入");
    }
    }
    }
    if (chance == 0) {
    console.log("很遗憾,你已经没有机会了");
    console.log("电脑出的数字为:", comNum);
    }
    else {
    console.log("游戏结束,Thank you for playing!");
    }
    }
    main();


  • 相关阅读:
    swift 获取iphone设备型号
    如何判断静态库是否支持64位
    MAC登录界面多了一个其他账户
    swift4 UIScrollView滑动手势与UIPageViewController冲突解决办法
    swift 保留两位小数以及前面不0
    本地通知
    swift3 UIColor扩展
    swift3 控件创建
    数据库--数据库事务
    数据库---触发器trigger
  • 原文地址:https://www.cnblogs.com/dbda/p/11407325.html
Copyright © 2011-2022 走看看