只需要将样式表和js脚本引入到html就可以玩游戏啦
可以自行修改样式及行列长度哦!
html代码段
<head>
<title>俄罗斯方块</title>
</head>
<body>
<div id="box"></div>
</body>
css代码段
#box {
margin: 0px auto;
text-align: center;
width: 252px;
font: 25px/25px '宋体';
background: #333;
color: #ccc;
}
javascript代码段
- 定义一些需要的变量等
var shape, currShapeInfo, bak, run
var map = eval("[" + Array(23).join("0x801,") + "0xfff]")
var shapes =
[[0x6600],
[0x2222,0xf00],
[0xc600,0x2640],
[0x6c00,0x4620],
[0x4460,0x2e0,0x6220,0x740],
[0x2260,0xe20,0x6440,0x4700],
[0x2620,0x720,0x2320,0x2700]]
var keycode = {
"38": "rotate(1)",
"40": "down()",
"37": "move(2, 1)",
"39": "move(0.5, -1)"
}
- 启动程序
function start(){
shape = shapes[~~(Math.random() * 7)];
bak = currShapeInfo = {
fk: [],
y: 0,
x: 4,
s: ~~(Math.random() * 4)
}
rotate(0)
}
- 结束程序
function over(){
document.onkeydown = null
clearInterval(run)
alert("GAME OVER")
}
- 显示程序
function update(t){
bak = {
fk: currShapeInfo.fk.slice(0),
y: currShapeInfo.y,
x: currShapeInfo.x,
s: currShapeInfo.s
}
if(t)
return
debugger
for(var i = 0, a2 = ""; i < 22; i++)
a2 += map[i].toString(2).slice(1, -1) + "<br/>"
for(var i = 0, n; i < 4; i++)
if(/([^0]+)/.test(bak.fk[i].toString(2).replace(/1/g, "\u25a1")))
a2 = a2.substr(0, n = (bak.y + i + 1) * 15 - RegExp.$_.length - 4) + RegExp.$1 + a2.slice(n + RegExp.$1.length)
document.getElementById("box").innerHTML = a2.replace(/1/g, "\u25a0").replace(/0/g, "\u3000")
}
- 判断
function is(){
for(var i = 0; i < 4; i++)
if((currShapeInfo.fk[i] & map[currShapeInfo.y + i]) != 0) return currShapeInfo = bak
}
- 翻转操作
function rotate(num){
var flip = shape[currShapeInfo.s = (currShapeInfo.s + num) % shape.length] // 翻转后的形状
for(var i = 0; i < 4; i++)
currShapeInfo.fk[i] = (flip >> (12 - i * 4) & 15) << currShapeInfo.x
update(is())
}
- 下移操作
function down(){
++currShapeInfo.y
if (is()) {
for(var i = 0; i < 4 && currShapeInfo.y + i < 22; i++)
if((map[currShapeInfo.y+i] |= currShapeInfo.fk[i]) == 0xfff)
map.splice(currShapeInfo.y + i, 1), map.unshift(0x801)
if(map[1] != 0x801) return over()
start()
}
update()
}
- 移动操作
function move(t, k){
currShapeInfo.x += k
for(var i = 0; i < 4; i++)
currShapeInfo.fk[i] *= t
update(is())
}
- 绑定按键事件
document.onkeydown = function(e) {
eval(keycode[(e ? e : event).keyCode])
}
- 开始游戏
start()
- 下移延时
run = setInterval("down()", 400)