js實(shí)現(xiàn)石頭剪刀布游戲
前言
用戶選擇出石頭剪刀布,電腦系統(tǒng)隨機(jī)生成石頭剪刀布,然后判斷結(jié)果并顯示給用戶
一、實(shí)現(xiàn)效果
二、使用步驟
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.gepszalag.com/img/shitou.png' alt=''> <img src='http://www.gepszalag.com/img/jiandao.png' alt=''> <img src='http://www.gepszalag.com/img/bu.png' alt=''> </div> <div class='text'> <span>您選擇了</span> <span>系統(tǒng)選擇了</span> </div> <div class='box2'> <img src='http://www.gepszalag.com/img/undefined.png' alt=''> <h1>pk</h1> <img src='http://www.gepszalag.com/img/undefined.png' alt=''> </div> <p>結(jié)果顯示中。。。</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//系統(tǒng) 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 //結(jié)果 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='平局,請?jiān)賮硪淮伟? }else{rs.innerHTML='不好意思,游戲失敗' } },200) } </script>
總結(jié)
利用數(shù)組,將石頭剪刀布src地址保存,利用隨機(jī)數(shù)將生成0-2的任意數(shù)字,電腦延時(shí)0.2秒生成。用戶利用for循環(huán)將照片綁定onclick(),點(diǎn)擊圖片,用戶選擇圖片修改為當(dāng)前圖片。創(chuàng)建參數(shù)函數(shù),傳入數(shù)組標(biāo),以及this對象。通過this.src改變用戶選擇的顯示圖片,將數(shù)組下標(biāo) 與隨機(jī)數(shù)進(jìn)行條件判斷。0代表石頭,1代表剪刀,2代表布。生成結(jié)果操作dom’進(jìn)行顯示
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. javascript xml xsl取值及數(shù)據(jù)修改第1/2頁2. 利用CSS3新特性創(chuàng)建透明邊框三角3. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條4. .NET使用StackTrace獲取方法調(diào)用信息的代碼演示5. IDEA創(chuàng)建Java項(xiàng)目導(dǎo)出Jar包運(yùn)行6. Python 輸出詳細(xì)的異常信息(traceback)方式7. 如何在Notepad++中配置python執(zhí)行命令8. 原生js生成圖片驗(yàn)證碼9. Vue中nvm-windows的安裝與使用教程(親測)10. Vue 自適應(yīng)高度表格的實(shí)現(xiàn)方法
