HTML+5連連看代碼示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML+5連連看</title>
<style>
/*游戲區域樣式*/
#gameArea{
width: 600px;
height: 600px;
margin: 0 auto;
border: 1px solid #ccc;
background-color: #eee;
position: relative;
}
/*矩形塊樣式*/
.rect{
width: 50px;
height: 50px;
margin: 2px;
background-color: #f00;
position: absolute;
}
</style>
</head>
<body>
<div id="gameArea"></div>
<script>
/*游戲初始化*/
function init(){
var gameArea = document.getElementById("gameArea");
var divWidth = gameArea.offsetWidth / 10;
var divHeight = gameArea.offsetHeight / 10;
var arr = [];//記錄所有矩形塊
//創建100個矩形塊
for(var i = 0; i < 10; i++){
for(var j = 0; j < 10; j++){
var rect = document.createElement("div");
rect.className = "rect";
rect.style.left = (i * divWidth + 2) + "px";
rect.style.top = (j * divHeight + 2) + "px";
gameArea.appendChild(rect);
//將矩形塊存儲到數組中
arr.push(rect);
}
}
//根據隨機數設置不同的顏色
for(var k = 0; k < arr.length; k++){
var r = parseInt(Math.random() * 255);
var g = parseInt(Math.random() * 255);
var b = parseInt(Math.random() * 255);
var color = "rgb(" + r + "," + g + "," + b + ")";
arr[k].style.backgroundColor = color;
}
}
window.onload = init;
</script>
</body>
</html>
上述代碼實現了一個簡單的HTML+5連連看游戲,游戲區域大小為600px * 600px,劃分成100個50px * 50px的矩形塊,每個矩形塊隨機染色,玩家需要通過消除相同顏色的矩形塊來獲得分數。