Advertisement
mauricioribeiro

Snake maneirinha

May 26th, 2015
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 7.76 KB | None | 0 0
  1. <html>
  2. <head>
  3.     <title></title>
  4. </head>
  5. <body>
  6. <style>
  7. html, body {
  8.     margin:0;
  9.     padding:0
  10. }
  11. canvas {
  12.     display: block;
  13. }
  14. canvas {width: auto; max-width: 100%; height: auto;}
  15. </style>
  16.  
  17.  <canvas></canvas>
  18.  
  19. <script>
  20. /**
  21.  * A lightweight game wrapper
  22.  *
  23.  * @constructor
  24.  */
  25.  
  26.  var canvas;
  27.  var ctx;
  28.  var rndNum;
  29.  
  30. function Game(canvas, options) {
  31.     this.canvas = canvas;
  32.     this.context = canvas.getContext('2d');
  33.  
  34.     this.score = 0;
  35.     this.key = 'right';
  36.     this.entities = [];
  37.  
  38.     this.options = {
  39.         fps: 10
  40.     };
  41.  
  42.     if (options) {
  43.         for (var i in options) this.options[i] = options[i];
  44.     }
  45.    
  46.     this.scale();
  47. }
  48.  
  49.  
  50. /**
  51.  * Start the game loop
  52.  * and initialize the keybindings
  53.  */
  54. Game.prototype.start = function () {
  55.     this.keyBindings();
  56.     this.gameLoop();
  57. };
  58.  
  59.  
  60. /**
  61.  * Stop the game loop
  62.  */
  63. Game.prototype.stop = function() {
  64.     this.pause = true;
  65. };
  66.  
  67.  
  68. /**
  69.  * Scale the canvas element
  70.  * in accordance with the correct ratio
  71.  */
  72. Game.prototype.scale = function () {
  73.     this.ratio = innerWidth < innerHeight ? innerWidth : innerHeight;
  74.    this.tile = (this.ratio / 20) | 0;
  75.    this.grid = this.ratio / this.tile;
  76.  
  77.    this.canvas.width = this.canvas.height = this.ratio;
  78. };
  79.  
  80.  
  81. /**
  82. * Adds an entity to the game
  83. *
  84. * @param {Function} entity
  85. */
  86. Game.prototype.addEntity = function (entity) {
  87.    this.entities.push(entity);
  88. };
  89.  
  90.  
  91. /**
  92. * Determines if an entity collides with another
  93. *
  94. * @param {Object} a
  95. * @param {Object} b
  96. */
  97. Game.prototype.collide = function(a, b){
  98.    return a.x === b.x && a.y === b.y;
  99. };
  100.  
  101.  
  102. /**
  103. * Tracks the pressed keys
  104. */
  105. Game.prototype.keyBindings = function () {
  106.    var that = this;
  107.  
  108.    // define some keys
  109.    var keys = {
  110.        a: 65,
  111.        left: 37,
  112.        d: 68,
  113.        right: 39,
  114.        w: 87,
  115.        up: 38,
  116.        s: 83,
  117.        down: 40
  118.      
  119.    };
  120.  
  121.  
  122.    /**
  123.     * Attach keyboard arrows to snake direction
  124.     */
  125.    document.onkeydown = function (e) {
  126.        switch ((e.which || e.keyCode) | 0) {
  127.            case keys.a:
  128.            case keys.left:
  129.                if (that.key !== 'right') that.key = 'left';
  130.                break;
  131.  
  132.            case keys.d:
  133.            case keys.right:
  134.                if (that.key !== 'left') that.key = 'right';
  135.                break;
  136.  
  137.            case keys.w:
  138.            case keys.up:
  139.            case ' up':
  140.            case 'up':
  141.  
  142.                if (that.key !== 'down') that.key = 'up';
  143.                break;
  144.  
  145.            case keys.s:
  146.            case keys.down:
  147.                if (that.key !== 'up') that.key = 'down';
  148.        }
  149.    };
  150.  
  151. };
  152.  
  153.  
  154. /**
  155. * The gameloop - and entity (update/draw) calls
  156. * Use of `setTimeout` instead of animationFrame
  157. * in order to keep it simple as possible
  158. */
  159. Game.prototype.gameLoop = function () {
  160.    if(this.pause) return;
  161.  
  162.    var self = this,
  163.        ctx = this.context;
  164.  
  165.    // clear the view area
  166.    ctx.fillStyle = "#123";
  167.  
  168.    // add some blur
  169.    ctx.globalAlpha = 0.5;
  170.    ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
  171.  
  172.    // disable blur
  173.    ctx.globalAlpha = 1;
  174.  
  175.    var i = this.entities.length;
  176.  
  177.    while(i--) {
  178.        var entity = this.entities[i];
  179.        if(entity.update) entity.update();
  180.        if(entity.draw) entity.draw(ctx);
  181.    }
  182.  
  183.  
  184.    setTimeout(function(){
  185.        self.gameLoop()
  186.    }, 1000 / this.options.fps);
  187. };
  188.  
  189.  
  190.  
  191. /**
  192. * The whole snake things
  193. *
  194. * @constructor
  195. */
  196. function Snake(game, food){
  197.    var tile = game.tile;
  198.    var grid = game.grid;
  199.    var collide = game.collide;
  200.  
  201.    this.x = 4;
  202.    this.y = 4;
  203.    this.segments = [];
  204.  
  205.    this.update = function() {
  206.  
  207.        // change direction -depending on which key was pressed
  208.        if(game.key === 'left') this.x--;
  209.        if(game.key === 'right') this.x++;
  210.        if(game.key === 'up') this.y--;
  211.        if(game.key === 'down') this.y++;
  212.      
  213.      
  214.  
  215.  
  216.        // boundaries
  217.        this.x = (this.x + tile) % tile;
  218.        this.y = (this.y + tile) % tile;
  219.      
  220.        /**
  221.         * check snake-food collision
  222.         */
  223.        if (game.collide(this, food)) {
  224.  
  225.            // randomize point position
  226.            food.x = food.y = Math.random() * tile | 0;
  227.          
  228.            // each 5th cake count up the score and increase the speed
  229.            if (!((game.score += 10) % 50)) {
  230.                game.options.fps += 5;
  231.            }
  232.          
  233.        } else {
  234.            // remove last segment if snake
  235.            // didn't got a point in this turn
  236.            if (this.segments.length) this.segments.pop();
  237.        }
  238.      
  239.      
  240.        // push next x and y to the beginning of segments
  241.        this.segments.unshift({x:this.x, y:this.y});
  242.      
  243.        /**
  244.         * check collision with snake itself - skipping the head (`--i` instead of `i--`)
  245.         */
  246.        var i = this.segments.length;
  247.        while (--i) {
  248.            if(game.collide(this, this.segments[i])) {
  249.                // break the loop and slice the worm in point of intersection
  250.                // here's in reality gameover...
  251.                game.stop();
  252.              
  253.                return this.segments.splice(i);
  254.            }
  255.        }
  256.  
  257.    };
  258.  
  259.    this.draw = function(ctx) {
  260.        // draw rectangle for each segment
  261.        // head gets another color
  262.        var i = this.segments.length;
  263.        while (i--) {
  264.            var segment = this.segments[i];
  265.            ctx.fillStyle = !i ? '#0cf' : '#0ae';
  266.            ctx.fillRect(
  267.            segment.x * grid,
  268.            segment.y * grid,
  269.            grid, grid);
  270.        }
  271.    };
  272.  
  273.    /* função maneira */
  274.    this.moveBySound = function(command){
  275.        var arrayCommands = command.split(' ');
  276.  
  277.        if(arrayCommands.indexOf('right')>0) game.key = 'right';
  278.         if(arrayCommands.indexOf('left')>0) game.key = 'left';
  279.         if(arrayCommands.indexOf('up')>0) game.key = 'up';
  280.         if(arrayCommands.indexOf('down')>0) game.key = 'down';
  281.  
  282.         console.log(arrayCommands);
  283.     };
  284. }
  285.  
  286.  
  287. /**
  288.  * The whole things to eat
  289.  *
  290.  * @constructor
  291.  */
  292. function Food(game){
  293.     var grid = game.grid;
  294.  
  295.     this.x = 4;
  296.     this.y = 4;
  297.  
  298.     this.draw = function(ctx){
  299.         ctx.fillStyle = "#f05";
  300.         ctx.fillRect(this.x * grid, this.y * grid, grid, grid);
  301.     };
  302. }
  303.  
  304.  
  305. // create the canvas element
  306. var canvas = document.createElement("canvas");
  307. document.body.appendChild(canvas);
  308.  
  309. /**
  310.  * Game initialization
  311.  * and entity preparation
  312.  */
  313. var game = new Game(canvas);
  314. var food = new Food(game);
  315. var snake = new Snake(game, food);
  316.  
  317. game.addEntity(food);
  318. game.addEntity(snake);
  319. game.start();
  320.  
  321.  
  322. if (!('webkitSpeechRecognition' in window)) {
  323.         alert('Web speech API is not supported in this browser');
  324.       }
  325. else {
  326.  
  327.     // Speech recognizer init
  328.     var recognizer = new webkitSpeechRecognition();
  329.  
  330.     // continously listen to speech
  331.     recognizer.continuous = true;
  332.  
  333.     // set languages supported
  334.     recognizer.lang = ['English', ['en-US', 'United States']];
  335.  
  336.     // We return non-final strings so gameplay isn't laggy
  337.     recognizer.interimResults = true;
  338.  
  339.     recognizer.onresult = function(e) {
  340.  
  341.     // set variable
  342.     var interim_transcript = '';
  343.       if (e.results.length) {
  344.          for (var i = event.resultIndex; i < event.results.length; i++) {
  345.            interim_transcript = event.results[i][0].transcript;
  346.            /* chamando a função maneira aqui */
  347.            snake.moveBySound(interim_transcript);
  348.          }
  349.      
  350.      
  351.      }
  352.    };
  353.  // start speech to text translation
  354.  recognizer.start();
  355.  
  356. }
  357. </script>
  358.  
  359. </body>
  360. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement