WebGL實現HTML5貪吃蛇3D遊戲

js1k.com收集了小於1k的javascript小例子,裏面有不少很炫很酷的遊戲和特效,今年規則又增長了新花樣,傳統的classic類型基礎上又增長了WebGL類型,以及容許增長到2K的++類型,屢次想嘗試提交個小遊戲但總沒法寫出讓本身滿意還能控制在這麼小的字節範圍。javascript

本身寫不出來,站在巨人肩膀老是有機會吧,想起《基於HTML5的電信網管3D機房監控應用》這篇提到的threejs,babylonjs和Hightopo的幾種基於WebGL的3D引擎,忽然想挑戰下本身實現個100行JS的3D小遊戲,折騰了一番最終採用Hightopo搞了個3D貪吃蛇遊戲,算了算JS代碼還只有90來行,終於知足了本身的小當心願寫完這篇能夠滿意去睡覺了。html

http://www.hightopo.com/demo/snake_20151106/GreedySnake.htmljava

060128389406803.png

http://www.hightopo.com/demo/snake_20151106/GreedySnake.htmlnode

如下先上一段最終3D遊戲在平板上的運行交互視頻效果:app

http://www.hightopo.com/demo/snake_20151106/GreedySnake.htmldom

傳統2D的貪吃蛇遊戲通常經過方向鍵盤控制蛇的前進方向,我一開始就想定位可運行在平板上的Touch交互,因此不考慮鍵盤的操做交互方式,採用徹底用點擊的方式來控制,經過HT的g3d.getHitPosition(e)函數我能獲得鼠標點擊所在的平面位置,這樣與蛇頭的位置作比較就能判斷出新的前進方向,若是點擊位置超出了貪吃蛇的運行矩陣範圍我就不作處理,這時候留給HT的標準orbit旋轉操做方式,經過ht.Default.isDoubleClick(e)監聽雙擊事件重啓遊戲。所謂的可移動化方面也沒太多須要考慮的設計,僅在添加點擊時須要考慮touch的狀況 view.addEventListener(ht.Default.isTouchable ? 'touchstart' : 'mousedown', 函數

90來行全部JS源代碼以下,各位遊戲高手不要噴我,確定不少人能夠寫得更精煉,但我只想經過這個玩一玩3D,HTML5和WebGL,包括給成天搞企業應用的本身換換腦子思考些新元素。spa

http://www.hightopo.com/demo/snake_20151106/GreedySnake.html設計

function init() {                
    w = 40; m = 20; d = w * m / 2; food = null;            
    dm = new ht.DataModel();            
    g3d = new ht.graph3d.Graph3dView(dm);                
    g3d.setGridVisible(true);
    g3d.setGridColor('#29B098');
    g3d.setGridSize(m);
    g3d.setGridGap(w);            
    view = g3d.getView();            
    view.className = 'main';
    document.body.appendChild(view);    
    window.addEventListener('resize', function (e) {  g3d.invalidate(); }, false);                                                                                            
    g3d.sm().setSelectionMode('none');
    view.addEventListener(ht.Default.isTouchable ? 'touchstart' : 'mousedown', function(e){                
        if(isRunning){
            var p = g3d.getHitPosition(e);
            if(Math.abs(p[0]) < d && Math.abs(p[2]) < d){
                if(direction === 'up' || direction === 'down'){
                    direction = p[0] > snake[0].p3()[0] ? 'right' : 'left';                       
                }
                else if(direction === 'left' || direction === 'right'){
                    direction = p[2] > snake[0].p3()[2] ? 'down' : 'up';                                             
                }                        
            }
        }else if(ht.Default.isDoubleClick(e)){
            start();    
        }                
    }, false);                        
    start();            
    setInterval(function(){ if(isRunning){ isRunning = next(); } }, 200);
}                
function start(){
    dm.clear(); snake = []; score = 0; direction = 'up'; isRunning = true;
    shape = new ht.Shape();
    shape.setPoints(new ht.List([
        {x: -d, y: d},
        {x: d, y: d},
        {x: d, y: -d},
        {x: -d, y: -d},
        {x: -d, y: d}
    ]));
    shape.setThickness(4);
    shape.setTall(w);
    shape.setElevation(w/2);
    shape.s({'all.color': 'rgba(20, 120, 120, 0.5)', 'all.transparent': true, 'all.reverse.cull': true});
    dm.add(shape);                         
    for(var i=0; i<m/2; i++) { snake.push(createNode(m/2 + i, m/2)); }            
    createFood();                        
}        
function createNode(x, y){
    var node = new ht.Node();
    node.a({ x: x,  y: y });
    node.s3(w*0.9, w*0.9, w*0.9);
    node.p3(-w*m/2+w*x+w/2, w/2, -w*m/2+w*y+w/2);
    dm.add(node);
    return node;
}        
function getRandom(){
    return parseInt(Math.random() * m);
}        
function createFood(){
    var x = getRandom(), y = getRandom();
    while(touchFood(x, y) || touchSnake(x, y)){ x = getRandom(); y = getRandom(); }
    if(food) dm.remove(food);            
    food = createNode(x, y); 
    food.s({'shape3d': 'sphere',  'shape3d.color': 'red'});
}        
function touchSnake(x, y){
    for(var i=0; i<snake.length; i++){                
        if(snake[i].a('x') === x && snake[i].a('y') === y){ return true; }
    }
    return false;
}        
function touchFood(x, y){
    return food && food.a('x') === x && food.a('y') === y;
}        
function next(){
    var node = snake[0], x = node.a('x'), y = node.a('y');
    if(direction === 'up') y--;
    if(direction === 'down') y++;       
    if(direction === 'left') x--;
    if(direction === 'right') x++;
    if(x < 0 || x >= m || y < 0 || y >= m || touchSnake(x, y)){ return false; }                        
    if(touchFood(x, y)){
        score++;                
        snake.splice(0, 0, createNode(x, y));                
        createFood();
    }else{
        snake.splice(0, 0, createNode(x, y));
        dm.remove(snake.pop());                
    }
    return true;
}
相關文章
相關標籤/搜索