Html5写一个简单的俄罗斯方块小游戏

2020-04-25 07:31:30易采站长站整理

var myCanvas;
var canvasCtx;
var tetris_status;//地图数据
var currentFall;//当前下落的block

游戏界面的完善


//create canvas
function createCanvas(){
myCanvas=document.createElement("canvas");
myCanvas.width=TETRIS_COLS*CELL_SIZE;
myCanvas.height=TETRIS_ROWS*CELL_SIZE;
//绘制背景
canvasCtx=myCanvas.getContext("2d");
canvasCtx.beginPath();
//TETRIS_COS
for(let i=1; i<TETRIS_COLS; i++){
canvasCtx.moveTo(i*CELL_SIZE, 0);
canvasCtx.lineTo(i*CELL_SIZE, myCanvas.height);
}
for(let i=1; i<TETRIS_ROWS; i++){
canvasCtx.moveTo(0, i*CELL_SIZE);
canvasCtx.lineTo(myCanvas.width, i*CELL_SIZE);
}
canvasCtx.closePath();
canvasCtx.strokeStyle="#b4a79d";
canvasCtx.lineWidth=0.6;
canvasCtx.stroke();
//第一行,最后一行,第一列,最后一列粗一点。
canvasCtx.beginPath();
canvasCtx.moveTo(0, 0);
canvasCtx.lineTo(myCanvas.width, 0);
canvasCtx.moveTo(0, myCanvas.height);
canvasCtx.lineTo(myCanvas.width, myCanvas.height);
canvasCtx.moveTo(0, 0);
canvasCtx.lineTo(0, myCanvas.height);
canvasCtx.moveTo(myCanvas.width, 0);
canvasCtx.lineTo(myCanvas.width, myCanvas.height);
canvasCtx.closePath();
canvasCtx.strokeStyle="#b4a79d";
canvasCtx.lineWidth=4;
canvasCtx.stroke();
//设置绘制block时的style
canvasCtx.fillStyle="#201a14";
}

draw canvas


function changeWidthAndHeight(w, h){
//通过jquery设置css
h+=$("ui_bg").css("height")+$("ui_bg").css("margin-rop")+$("ui_bg").css("margin-bottom")+$("ui_bg").css("padding-top")+$("ui_bg").css("padding-bottom");
$(".bg").css({
"width":w,
"height":h,
"top":0, "bottom":0, "right":0, "left":0,
"margin":"auto"
});
}

change width and height


//draw blocks
function drawBlocks(){
//清空地图
for(let i=0; i<TETRIS_ROWS;i++){
for(let j=0;j<TETRIS_COLS;j++)
canvasCtx.clearRect(j*CELL_SIZE+1, i*CELL_SIZE+1, CELL_SIZE-2, CELL_SIZE-2);
}
//绘制地图
for(let i=0; i<TETRIS_ROWS;i++){
for(let j=0;j<TETRIS_COLS;j++){
if(tetris_status[i][j]!=NO_BLOCK)
canvasCtx.fillRect(j*CELL_SIZE+1, i*CELL_SIZE+1, CELL_SIZE-2, CELL_SIZE-2);//中间留点缝隙
}
}
//绘制currentFall
for(let i=0;i<currentFall.length;i++)
canvasCtx.fillRect(currentFall[i].x*CELL_SIZE+1, currentFall[i].y*CELL_SIZE+1, CELL_SIZE-2,CELL_SIZE-2);
}

draw block

游戏逻辑