js石头剪刀布小游戏
代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> .div1{ margin-left: 40px; margin-top: 40px; } </style> </head> <body> <table border="1px" cellspacing="0px"><!-- border设置表格边线,cellspacing设置边框的边距 --> <tr> <td> <p>我方出拳</p> <img src="img/2.png" id="img2"> </td> <td>VS</td> <td> <p>敌方出拳</p> <img src="img/3.png" id="img3"> </td> </tr> <tr> <td colspan="3"> <p id="result">PLEASE CHOLCE</p> </td> </tr> <tr> <td> <p>我方选择的是</p> <img src="img/2.png" id="img1"> </td> <td>请出拳</td> <td> <div class="div1"> <select onchange="changeImg()" id="choiceSelect"> <option value="2">剪刀</option> <option value="1">石头</option> <option value="3">布</option> </select> </div> <div class="div1"> <input type="button" value="想好了出拳" onclick="getChoice()"> </div> <div class="div1"> <input type="button" value="查看结果" onclick="showresult()"> </div> </td> </tr> <tr> <td colspan="3" id="finalresult"> <p>您玩了0局,您平0次,赢0次,输0次</p></td> </tr> </table> <script type="text/javascript"> // n1代表我方数 var n1 = 2; var peace = 0; var win = 0; var lose = 0; var all = 0 function changeImg(){ var choiceSelect = document.getElementById("choiceSelect"); n1 = choiceSelect.value; document.getElementById("img1").src = "img/"+n1+".png"; } function getChoice(){ //n2代表敌方数 var n2 = parseInt(Math.random()*3)+1; // alert(n2); document.getElementById("img2").src = "img/"+n1+".png"; document.getElementById("img3").src = "img/"+n2+".png"; pk(n1,n2); } function pk(n1,n2){ var result = document.getElementById("result"); if (n1-n2 == 0) { result.innerHTML = "你和计算机平"+n1+"-------"+n2; peace++; } if (n1-n2 == -1||n1-n2 == 2) { result.innerHTML = "你赢了!!!"+n1+"-------"+n2; win++; } // if (n1-n2 == 1) { if (n1-n2 == 1||n1-n2 == -2 ) { // getChoice(); result.innerHTML = "你输了!!!"+n1+"-------"+n2; lose++; } all++; document.getElementById("finalresult").innerHTML = "<p>您玩了"+all+"局,您平"+peace+"次,赢"+win+"次,输"+lose+"次</p>"; } function showresult(){ document.getElementById("finalresult").innerHTML = "<p>您玩了"+all+"局,您平"+peace+"次,赢"+win+"次,输"+lose+"次</p>"; } </script> </body> </html>
changeImg:获取选择的结果,显示对应的图片
n1:为获取下拉框选择的结果的内容
getChoice:获取0-1的随机数(不包括1)乘以3向下取整+1,得到的数为1,2,3
pk:计算输赢(例如:当我选石头为1,电脑选剪刀为2,那么n1-n2等于-1,所以判断如果结果等于-1时为我赢。一共有九种可能)
图片: