javascript 網頁遊戲:猜拳

來源:互聯網
上載者:User

//網頁遊戲:猜拳

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
        <title>Insert title here</title>
  <style type="text/css">
   input{
    width:150px;
   }
  </style>
  <script type="text/javascript">
   window.onload = function(){
    //擷取4個按鈕和兩個輸入框
    var stone = document.getElementById("stone");
    var cut = document.getElementById("cut");
    var cloth = document.getElementById("cloth");
    var mine = document.getElementById("mine");
    var guess = document.getElementById("guess");
    var computer = document.getElementById("computer");
   
    //當點擊按鈕時,把按鈕的value賦值給mine的value
    function click(){
     mine.value = this.value;
    }
   
    stone.onclick = click;
    cut.onclick = click;
    cloth.onclick = click;
   
    //產生一個隨機數, 1代表石頭, 2 代表剪刀 3布
    guess.onclick = function(){
     var num = Math.floor(Math.random()* 3 + 1);
     if(num == 1)
        computer.value = "石頭";
     else if(num == 2)
         computer.value = "剪刀";
     else if(num == 3)
         computer.value = "布";
    
     var mineValue = mine.value;
     var computerValue = computer.value;
    
     if(mineValue == computerValue)
        alert("平局");
      else if(mineValue == "石頭")
        alert(computerValue == "剪刀" ? "贏了" : "輸了");
      else if(mineValue == "剪刀")
        alert(computerValue == "布" ? "贏了" : "輸了");
      else if(mineValue == "布")
        alert(computerValue == "石頭" ? "贏了" : "輸了");
     
      mine.value ="";
      computer.value ="";
    }
   }
  </script>
    </head>
    <body>
     <input type="button" value="石頭" id="stone">
  <input type="button" value="剪刀" id="cut">
  <input type="button" value="布" id="cloth"> <br><br>
  您出的拳是:<input id="mine"><br><br>
  <input type="button" value="猜猜猜" id="guess"><br><br>
  電腦出的拳是:<input id="computer">
    </body>
</html> 


摘自  代俊建的專欄 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.