JS 实现别踩皂块小游戏
JS 实现别踩白块小游戏
使用JS实现别踩白块功能。自己尚未完成。后序会继续完成的。
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>别踩白块</title> <style> #main { width: 400px; height: 400px; background: gray; border:2px solid green; margin: 0 auto; position: relative; overflow: hidden; } #container { width: 100%; height: 400px; position: relative; top: -100px; background: white; } .row { width: 100%; height:100px; } .cell{ width: 100px; height: 100px; float: left; } .black { background: black; } #score{ text-align: center; } </style> </head> <body> <h1 id="score">0</h1> <div id="main"> <div id="container"></div> </div> </body> <script> var colck = null; //定时器操作句柄 var state = 0; //0初始化,1进行中, 2暂停, 3失败 //初始化操作,使得有4行 function init(){ for(var i=0; i<4; i++){ crow(); } $('main').onclick = function (ev){ judge(ev); } } function judge(ev){ if (state == 3) { alert('失败!!!!!!'); return; } if (ev.target.className.indexOf('black') == -1) { clearInterval(clock); state = 3; alert('结束'); }else{ ev.target.className = 'cell'; ev.target.parentNode.pass = 1; //节点对象没有属性的时候,可以任意增加 score(); } } //定时器 function start(){ clock = window.setInterval('move()', 30); } //动画 function move(){ var con = $('container'); var top = parseInt(window.getComputedStyle(con, null)['top']); top += 5; con.style.top = top + 'px'; if(top == 0){ crow(); con.style.top = '-100px'; drow(); }else if(top == -95){ var rows = con.children; if((rows.length == 5) && (rows[rows.length-1].pass !== 1)){ alert('shu'); } } } //计分 function score(){ $('score').innerHTML = parseInt($('score').innerHTML)+1; } //创建div,row 包装四个子div function crow(){ var con = $('container'); var row = cdiv('row'); var classes = createSn(); for(var i=0; i<4; i++){ row.appendChild(cdiv(classes[i])); } if (con.firstChild == null) { con.appendChild(row); }else{ con.insertBefore(row, con.firstChild); } } //删除最后一行 function drow(){ var con = $('container'); con.removeChild(con.lastChild); } //创建div,className是类mi名 function cdiv(className){ var div = document.createElement('div'); div.className = className; return div; } //返回数组,其中一个单元为cell black 其他的位cell function createSn(){ var arr = ['cell', 'cell', 'cell', 'cell']; var i = Math.floor(Math.random()*4); arr[i] = 'cell black'; return arr; } //封装一个函数,按照ID获取对象 function $(id){ return document.getElementById(id); } init(); start(); </script> </html>
效果图: