這個遊戲主要設計到兩點:
首先是勝負運算
由於石頭剪刀布是循環性的
石頭殺剪子
剪子殺布
布殺石頭
石頭殺剪子
。 。 。
根據以上特點找出規律,寫出算法即可。
讓電腦隨機
這點比較容易,前面我有寫過文章介紹,不明白的童鞋可以去看看。
隨機刷屏
其實這個效果不是遊戲的關鍵性,但為了看起來更加互動,好玩,我就給加上了。這裡用到了一個取模算法,根據余數去循環顯示即可達到效果。
界面截圖
最後上代碼
<!DOCTYPE html><html><head><meta charset="utf-8" /><title>JS寫的石頭剪子佈遊戲- 瓊台博客</title><style type="text/css">div{margin:20px auto;padding:10px;border:2px solid #999;width:200px;background:#ffe;}div#cu{font-weight:bold;font-size:30px;height:40px;color:red;}div#la{border:none;background:none;display:none;}span{color:red;font-weight:bold;}</style><script type="text/javascript">var se = null,time=20,you=0,arr=new Array('石頭','抹布','剪子');function p(n){you = n;document.getElementById('you').innerHTML=s(n);document.getElementById('st').disabled=true;document.getElementById('mb').disabled=true;document.getElementById('jz').disabled=true;document.getElementById('cu').innerHTML = '...';se = setInterval('t()',50);}function agin(){document.getElementById('st').disabled=false;document.getElementById('mb').disabled=false;document.getElementById('jz').disabled=false;document.getElementById('la').style.display = 'none';document.getElementById('you').innerHTML = '';document.getElementById('pc').innerHTML = '';document.getElementById('cu').innerHTML = '';document.getElementById('you').innerHTML= '請選擇';}function bt(){var pc = Math.floor(Math.random() * 3 + 1);document.getElementById('pc').innerHTML = s(pc);var str='';if(pc==you){str += '平局';}else{var b = pc-you;if(b>0){if(b==1){str += '電腦贏';}else{str += '你贏啦';}}else{b = b*-1;if(b==1){str += '你贏啦';}else{str += '電腦贏';}}}document.getElementById('la').style.display = 'block';document.getElementById('cu').innerHTML = str;}function t(){if(time>0){document.getElementById('pc').innerHTML = arr[time%3];time--;}else{clearInterval(se);se = null;time = 20;bt();}}function s(n){if(n==1){return '石頭';}else if(n==2){return '抹布';}else{return '剪子';}}</script></head><body><div><p>你出什麼? <span id="you">請選擇</span></p><p><button id="st" onclick="p(1);">石頭</button></p><p><button id="mb" onclick="p(2);">抹布</button></p><p><button id="jz" onclick="p(3);">剪子</button></p></div><div><p>電腦出? </p><span style="" id="pc"></span></div><div id="cu"></div><div id="la"><button id="agin" onclick="agin()">再來一次</button></div></body></html>