3D Snake game with HTML 5 in 100 lines of JavaScript

Source: Internet
Author: User
Tags abs range touch


Js1k.com has a small sample of JavaScript less than 1k, with lots of cool games and special effects, and this year's rules add a little twist, and the traditional classic type increases the WEBGL type and the type of + + that is allowed to increase to 2K, Many times trying to submit a small game, but can not write to their satisfaction and control in such a small byte range.



I can not write, standing on the shoulders of giants always have a chance, think of "based on HTML5 Telecom network management 3D computer room monitoring Application" This mentioned Threejs,babylonjs and Hightopo of several WebGL 3D engine, Suddenly want to challenge their own implementation of a 100-line JS 3D games, toss a bit of the end of the use of Hightopo made a 3D greedy snake game, calculate the JS code only 90来 line, finally satisfied their small wish to write this article can be satisfied to go to sleep.






See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/



The following is the final 3D game on the flat panel running interactive video effect:



The traditional 2D snake game in general through the direction of the keyboard to control the snake's way forward, I started to position can run on the tablet touch interaction, so do not consider the keyboard operation interactive mode, using a full click of the way to control, through the HT g3d.gethitposition (e) function I can get the location of the mouse click on the plane, so as compared to the position of the snake can be judged a new way forward, if the click position beyond the snake's operating matrix range I do not do processing, this time left to HT standard orbit rotation operation, through the HT. Default.isdoubleclick (e) listens for double click event Restart game. There is not much to consider in the so-called mobility aspect, only when adding clicks you need to consider the touch of the situation View.addeventlistener (HT. Default.istouchable? ' Touchstart ': ' MouseDown ',



90来 line all JS source code as follows, you do not spray me Game Master, I am sure many people can write more refined, but I just want to play through this 3d,html5 and WebGL, including the whole day to engage in enterprise applications to change their brains to think about some new elements.


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.