jQuery实现别踩白块儿网页版小游戏

2020-05-27 18:01:29易采站长站整理

font-weight: bold;
font-size: 20px;
color: #fff;
text-align: center;
position: absolute;
}
.coBlock{
background-color: #000;
}
.gameover {
display: block;
margin: 0 auto;
width: 300px;
text-align: center;
vertical-align: middle;
position: absolute;
}
.gameover p {
font-family: Arial;
font-size: 50px;
color: white;
margin: 50px auto;
margin-top: 150px;
}
.gameover span {
font-family: Arial;
font-size: 50px;
color: white;
margin: 50px auto;
}
.restartGame {
display: block;
margin: 20px auto;
width: 180px;
padding: 10px 10px;
background-color: #8f7a66;
font-family: Arial;
font-size: 30px;
color: white;
border-radius: 10px;
text-decoration: none;
}
.restartGame:hover {
background-color: #9f8b77;
}

这里并没有设置每个格子的位置,位置由js代码来设置,以及第二层的二维数组、第三层的显示层都由js来设置,这里和 jQuery编写网页版2048小游戏 并没有什么大的区别

代码:


function init(){
timerRan = 0.000;
keyDown = true;
for(var i=0;i<4;i++){
board[i] = [];
for(var j=0;j<3;j++){
board[i][j] = [];
var grid = $('#grid-'+ i +'-'+ j);
grid.css({
'top':getPosTop(i,j),
'left':getPosLeft(i,j)
});
$('#container').append('<div class="block" id="block-'+ i +'-'+ j +'"></div>');
var block = $('#block-'+ i +'-'+ j);
block.css({
'top':getPosTop(i,j),
'left':getPosLeft(i,j)
});
board[i][j] = 0;
}
}


function getPosTop(i,j){
return i*100;
}
function getPosLeft(i,j){
return j*100;
}

初始化

游戏开始时,要在每一行随机的位置显示一个黑色的方块,并且在最下面的那一行的黑色方块上要有提示信息

代码:


for(var i=0;i<4;i++){
var randj = parseInt(Math.floor(Math.random() * 3));
if(i >0 && board[i-1][randj] == 1){
randj = parseInt(Math.floor(Math.random() * 3));
}
$('#block-'+ i +'-'+ randj).addClass('coBlock');
board[i][randj] = 1;
}
$('#block-3-0').text('按J开始游戏');
$('#block-3-1').text('按K开始游戏');
$('#block-3-2').text('按L开始游戏');

基本操作

我们通过switch循环,来根据用户不同的输入进行不同的操作

代码:


$(document).keydown(function(event) {
switch(event.keyCode){
case 74:
if(board[3][0] == 1 && keyDown){
timeRan();