美文网首页
Chapter 2 Writing Real Code

Chapter 2 Writing Real Code

作者: Smnag | 来源:发表于2019-04-01 22:52 被阅读0次
    var randomLoc = Math.floor(Math.random()*5);//Math.floor向下取整,Math.random取0-1之间任意数
    var location1 = randomLoc;
    var location2 = randomLoc + 1;
    var location3 = randomLoc + 2;
    var guess;
    var hits = 0;
    var guesses = 0;
    var isSunk = false;
    
    while (isSunk == false) {
        guess = prompt("Ready, aim, fire! (enter a number from 0-6):"); //prompt获取用户输入
        if (guess < 0 || guess > 6) {   //排除法,先排除错误的范围
            alert("Please enter a valid cell number!");
        }else {
            guesses = guesses + 1;
            
            if (guess == location1 || guess == location2 || guess == location3){   // ||或,&&且,!非
               alert("HIT!");
               hits = hits + 1;
               if (hits == 3){
                   isSunk = true;
                   alert("You sank my battleship!");
               }
         }else {
             alert("MISS");
         }
       }
    }
    var stats = "You took " + guesses + " guesses to sink the battleship," + " which means your shooting accuracy was " + (3/guesses);
    alert(stats);
    

    相关文章

      网友评论

          本文标题:Chapter 2 Writing Real Code

          本文链接:https://www.haomeiwen.com/subject/jhlibqtx.html