用100行javascript實現HTML 5的3D貪吃蛇遊戲

來源:互聯網
上載者:User

js1k.com收集了小於1k的javascript小例子,裡面有很多很炫很酷的遊戲和特 效,今年規則又增加了新花樣,傳統的classic類型基礎上又增加了WebGL類型, 以及允許增加到2K的++類型,多次想嘗試提交個小遊戲但總無法寫出讓自己滿意 還能控制在這麼小的位元組範圍。

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

查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/

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

傳統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,包括給整天搞公司專屬應用程式的自己 換換腦子思考些新元素。

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;        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.