js實現石頭剪刀布游戲
前言
用戶選擇出石頭剪刀布,電腦系統隨機生成石頭剪刀布,然后判斷結果并顯示給用戶
一、實現效果
二、使用步驟
1.HTML和CSS
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>石頭剪刀布</title> <style> #bigbox{ width: 600px; height: 600px; background: slateblue; margin: 0 auto; } #bigbox>h1{ width: 100%; text-align: center; color: #ffffff; } .box1{ height: 200px; } .box2{ height: 220px; } .box1 img{ float: left; margin: 25px; } .box2 img{ float: left; margin:20px 63px; width: 150px; height: 150px; } .box2 h1{ display: block; color: #000; float: left; line-height: 150px; } img{ width: 150px; height: 150px; } p{ text-align: center; color: red; font-size: 20px; font-weight: bold; } .text{ height: 20px; } .text span{ font-size: 20px; color: #ffffff; margin: 0 100px; line-height: 20px; } </style></head><body> <div id=’bigbox’> <h1>請選擇</h1> <div class='box1'> <img src='http://www.aoyou183.cn/img/shitou.png' alt=''> <img src='http://www.aoyou183.cn/img/jiandao.png' alt=''> <img src='http://www.aoyou183.cn/img/bu.png' alt=''> </div> <div class='text'> <span>您選擇了</span> <span>系統選擇了</span> </div> <div class='box2'> <img src='http://www.aoyou183.cn/img/undefined.png' alt=''> <h1>pk</h1> <img src='http://www.aoyou183.cn/img/undefined.png' alt=''> </div> <p>結果顯示中。。。</p> </div></body>
2.JavaScript
<script> let imgs=document.getElementsByTagName(’img’) // console.log(imgs.length) for(let i=0;i<3;i++){ imgs[i].onclick=function(){ game(this,i) } } function game(src,i){ // console.log(i) //用戶 let str=src.src; let user=document.getElementsByTagName(’img’)[3] user.src=str//系統 setTimeout(function (){ let user=document.getElementsByTagName(’img’)[4] let imgSrc=[’../img/shitou.png’,’../img/jiandao.png’,’../img/bu.png’] let num = Math.floor(Math.random() * imgSrc.length) console.log(num) user.src=imgSrc[num] i=i*1 //結果 let rs=document.getElementsByTagName(’p’)[0] if(i==0&&num==1 || i==1&&num==2 || i==2&&num==0){rs.innerHTML='恭喜你獲得勝利!' }else if(i==num){rs.innerHTML='平局,請再來一次吧' }else{rs.innerHTML='不好意思,游戲失敗' } },200) } </script>
總結
利用數組,將石頭剪刀布src地址保存,利用隨機數將生成0-2的任意數字,電腦延時0.2秒生成。用戶利用for循環將照片綁定onclick(),點擊圖片,用戶選擇圖片修改為當前圖片。創建參數函數,傳入數組標,以及this對象。通過this.src改變用戶選擇的顯示圖片,將數組下標 與隨機數進行條件判斷。0代表石頭,1代表剪刀,2代表布。生成結果操作dom’進行顯示
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
