在線預覽:http://osgames.duapp.com/apprun.html?appid=osgames1-801422234293697
在線編輯:http://osgames.duapp.com/gamebuilder.php?appid=osgames1-801422234293697
微信掃描:
運行截圖:
除了重力感應遊戲,GameBuilder開發傳統的遊戲也毫不遜色,作爲一個懷舊的人,總是對這類遊戲情有獨鍾。
貪喫蛇主要靠一個UICanvas來實現,前面一片博客GameBuilder開發遊戲應用系列之100行代碼實現別踩白塊有介紹過,配合四個UIButton來控制方向。
食物生成
win.makeFoodBlock = function(num) {
var bl = win.blockList;
var fl = win.foodList;
Math.min(48 * 72 - bl.length - fl.length, num);
var x, y;
for(var i = 0; i < num; i++) {
var block = {x:0, y:0};
do {
x = Math.floor(Math.random() * 48);
y = Math.floor(Math.random() * 72);
block.x = x; block.y = y;
} while(win.blockInList(block, win.blockList) || win.blockInList(block, win.foodList));
win.foodList.push(block);
}
};
方向控制
var win = this.getWindow();
win.changeDirection(win.DIR_UP);
//播放音效
this.playSoundEffect("disappear.mp3");
win.changeDirection = function(dir) {
switch(win.direction) {
case win.DIR_RIGHT:
if(dir == win.DIR_LEFT) {
return;
}
break;
case win.DIR_UP:
if(dir == win.DIR_DOWN) {
return;
}
break;
case win.DIR_LEFT:
if(dir == win.DIR_RIGHT) {
return;
}
break;
case win.DIR_DOWN:
if(dir == win.DIR_UP) {
return;
}
break;
}
win.direction = dir;
};
計算蛇頭下一個位置
win.nextFirst = function (first) {
var nextFirst = {x:0, y:0};
switch(win.direction) {
case win.DIR_RIGHT:
nextFirst.x = (first.x + 1) % 48;
nextFirst.y = first.y;
break;
case win.DIR_UP:
nextFirst.y = (first.y === 0) ? 71 : first.y - 1;
nextFirst.x = first.x;
break;
case win.DIR_LEFT:
nextFirst.x = (first.x === 0) ? 47 : first.x - 1;
nextFirst.y = first.y;
break;
case win.DIR_DOWN:
nextFirst.y = (first.y + 1) % 72;
nextFirst.x = first.x;
}
return nextFirst;
};
貪喫蛇主要邏輯
win.updateList = function() {
var last = win.blockList[win.blockList.length - 1];
var first = win.blockList[0];
var nf = win.nextFirst(first);
//喫到食物了
if(win.blockInList(nf, win.foodList)) {
win.removeBlockFromFL(nf);
win.blockList.unshift(nf);
win.find("ui-sound-effects").play("disappear.mp3");
win.makeFoodBlock(1);
if(48 * 72 === win.blockList.length) {
win.openWindow("win-result", function(ret){}, false, win.blockList.length);
win.initGame();
}
} else if(win.blockInList(nf, win.blockList) && !win.checkEqual(nf, last)) {
//蛇頭碰到蛇身,遊戲結束!
win.openWindow("win-result", function(ret){}, false, win.blockList.length);
win.initGame();
console.log("Game Over");
} else {
//正常行進
win.blockList.pop();
win.blockList.unshift(nf);
}
setTimeout(win.updateList, 150);
};
繪製貪喫蛇
實現UICanvas的onPaint接口。
var win = this.getWindow();
var bl = win.blockList;
var fl = win.foodList;
var ctx = canvas2dCtx;
for(var i = 0; bl !== null && i < bl.length; i++) {
ctx.strokeStyle = "white";
ctx.fillStyle = "block";
ctx.strokeRect(bl[i].x * 10, bl[i].y * 10, 10, 10);
ctx.fillRect(bl[i].x * 10, bl[i].y * 10, 10, 10);
}
for(var i = 0; fl !== null && i < fl.length; i++) {
ctx.strokeRect(fl[i].x * 10, fl[i].y * 10, 10, 10);
ctx.fillRect(fl[i].x * 10, fl[i].y * 10, 10, 10);
}
之所以用了100行代碼,是因爲食物是一個列表,而不是傳統的一個食物,這樣會多費一些代碼維護食物列表。