Advertisement
owlman

snake | JavaScript

Mar 14th, 2016
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. JavaScript Snake
  3. By Patrick Gillespie
  4. http://patorjk.com/games/snake
  5. */
  6.  
  7. /**
  8. * @module Snake
  9. * @class SNAKE
  10. */
  11.  
  12. var SNAKE = SNAKE || {};
  13.  
  14. /**
  15. * @method addEventListener
  16. * @param {Object} obj The object to add an event listener to.
  17. * @param {String} event The event to listen for.
  18. * @param {Function} funct The function to execute when the event is triggered.
  19. * @param {Boolean} evtCapturing True to do event capturing, false to do event bubbling.
  20. */
  21.  
  22. SNAKE.addEventListener = (function() {
  23.     if (window.addEventListener) {
  24.         return function(obj, event, funct, evtCapturing) {
  25.             obj.addEventListener(event, funct, evtCapturing);
  26.         };
  27.     } else if (window.attachEvent) {
  28.         return function(obj, event, funct) {
  29.             obj.attachEvent("on" + event, funct);
  30.         };
  31.     }
  32. })();
  33.  
  34. /**
  35. * @method removeEventListener
  36. * @param {Object} obj The object to remove an event listener from.
  37. * @param {String} event The event that was listened for.
  38. * @param {Function} funct The function that was executed when the event is triggered.
  39. * @param {Boolean} evtCapturing True if event capturing was done, false otherwise.
  40. */
  41.  
  42. SNAKE.removeEventListener = (function() {
  43.     if (window.removeEventListener) {
  44.         return function(obj, event, funct, evtCapturing) {
  45.             obj.removeEventListener(event, funct, evtCapturing);
  46.         };
  47.     } else if (window.detachEvent) {
  48.         return function(obj, event, funct) {
  49.             obj.detachEvent("on" + event, funct);
  50.         };
  51.     }
  52. })();
  53.  
  54. /**
  55. * This class manages the snake which will reside inside of a SNAKE.Board object.
  56. * @class Snake
  57. * @constructor
  58. * @namespace SNAKE
  59. * @param {Object} config The configuration object for the class. Contains playingBoard (the SNAKE.Board that this snake resides in), startRow and startCol.
  60. */
  61. SNAKE.Snake = SNAKE.Snake || (function() {
  62.    
  63.     // -------------------------------------------------------------------------
  64.     // Private static variables and methods
  65.     // -------------------------------------------------------------------------
  66.    
  67.     var instanceNumber = 0;
  68.     var blockPool = [];
  69.    
  70.     var SnakeBlock = function() {
  71.         this.elm = null;
  72.         this.elmStyle = null;
  73.         this.row = -1;
  74.         this.col = -1;
  75.         this.xPos = -1000;
  76.         this.yPos = -1000;
  77.         this.next = null;
  78.         this.prev = null;
  79.     };
  80.    
  81.     // this function is adapted from the example at http://greengeckodesign.com/blog/2007/07/get-highest-z-index-in-javascript.html
  82.     function getNextHighestZIndex(myObj) {
  83.         var highestIndex = 0,
  84.             currentIndex = 0,
  85.             ii;
  86.         for (ii in myObj) {
  87.             if (myObj[ii].elm.currentStyle){  
  88.                 currentIndex = parseFloat(myObj[ii].elm.style["z-index"],10);
  89.             }else if(window.getComputedStyle) {
  90.                 currentIndex = parseFloat(document.defaultView.getComputedStyle(myObj[ii].elm,null).getPropertyValue("z-index"),10);  
  91.             }
  92.             if(!isNaN(currentIndex) && currentIndex > highestIndex){
  93.                 highestIndex = currentIndex;
  94.             }
  95.         }
  96.         return(highestIndex+1);  
  97.     }
  98.    
  99.     // -------------------------------------------------------------------------
  100.     // Contructor + public and private definitions
  101.     // -------------------------------------------------------------------------
  102.    
  103.     /*
  104.         config options:
  105.             playingBoard - the SnakeBoard that this snake belongs too.
  106.             startRow - The row the snake should start on.
  107.             startCol - The column the snake should start on.
  108.     */
  109.     return function(config) {
  110.    
  111.         if (!config||!config.playingBoard) {return;}
  112.    
  113.         // ----- private variables -----
  114.  
  115.         var me = this,
  116.             playingBoard = config.playingBoard,
  117.             myId = instanceNumber++,
  118.             growthIncr = 5,
  119.             moveQueue = [], // a queue that holds the next moves of the snake
  120.             currentDirection = 1, // 0: up, 1: left, 2: down, 3: right
  121.             columnShift = [0, 1, 0, -1],
  122.             rowShift = [-1, 0, 1, 0],
  123.             xPosShift = [],
  124.             yPosShift = [],
  125.             snakeSpeed = 75,
  126.             isDead = false;
  127.        
  128.         // ----- public variables -----
  129.  
  130.         me.snakeBody = {};
  131.         me.snakeBody["b0"] = new SnakeBlock(); // create snake head
  132.         me.snakeBody["b0"].row = config.startRow || 1;
  133.         me.snakeBody["b0"].col = config.startCol || 1;
  134.         me.snakeBody["b0"].xPos = me.snakeBody["b0"].row * playingBoard.getBlockWidth();
  135.         me.snakeBody["b0"].yPos = me.snakeBody["b0"].col * playingBoard.getBlockHeight();
  136.         me.snakeBody["b0"].elm = createSnakeElement();
  137.         me.snakeBody["b0"].elmStyle = me.snakeBody["b0"].elm.style;
  138.         playingBoard.getBoardContainer().appendChild( me.snakeBody["b0"].elm );
  139.         me.snakeBody["b0"].elm.style.left = me.snakeBody["b0"].xPos + "px";
  140.         me.snakeBody["b0"].elm.style.top = me.snakeBody["b0"].yPos + "px";
  141.         me.snakeBody["b0"].next = me.snakeBody["b0"];
  142.         me.snakeBody["b0"].prev = me.snakeBody["b0"];
  143.        
  144.         me.snakeLength = 1;
  145.         me.snakeHead = me.snakeBody["b0"];
  146.         me.snakeTail = me.snakeBody["b0"];
  147.         me.snakeHead.elm.className = me.snakeHead.elm.className.replace(/\bsnake-snakebody-dead\b/,'');
  148.         me.snakeHead.elm.className += " snake-snakebody-alive";
  149.        
  150.         // ----- private methods -----
  151.        
  152.         function createSnakeElement() {
  153.             var tempNode = document.createElement("div");
  154.             tempNode.className = "snake-snakebody-block";
  155.             tempNode.style.left = "-1000px";
  156.             tempNode.style.top = "-1000px";
  157.             tempNode.style.width = playingBoard.getBlockWidth() + "px";
  158.             tempNode.style.height = playingBoard.getBlockHeight() + "px";
  159.             return tempNode;
  160.         }
  161.        
  162.         function createBlocks(num) {
  163.             var tempBlock;
  164.             var tempNode = createSnakeElement();
  165.  
  166.             for (var ii = 1; ii < num; ii++){
  167.                 tempBlock = new SnakeBlock();
  168.                 tempBlock.elm = tempNode.cloneNode(true);
  169.                 tempBlock.elmStyle = tempBlock.elm.style;
  170.                 playingBoard.getBoardContainer().appendChild( tempBlock.elm );
  171.                 blockPool[blockPool.length] = tempBlock;
  172.             }
  173.            
  174.             tempBlock = new SnakeBlock();
  175.             tempBlock.elm = tempNode;
  176.             playingBoard.getBoardContainer().appendChild( tempBlock.elm );
  177.             blockPool[blockPool.length] = tempBlock;
  178.         }
  179.        
  180.         // ----- public methods -----
  181.        
  182.         /**
  183.         * This method is called when a user presses a key. It logs arrow key presses in "moveQueue", which is used when the snake needs to make its next move.
  184.         * @method handleArrowKeys
  185.         * @param {Number} keyNum A number representing the key that was pressed.
  186.         */
  187.         /*
  188.             Handles what happens when an arrow key is pressed.
  189.             Direction explained (0 = up, etc etc)
  190.                     0
  191.                   3   1
  192.                     2
  193.         */
  194.         me.handleArrowKeys = function(keyNum) {
  195.             if (isDead) {return;}
  196.            
  197.             var snakeLength = me.snakeLength;
  198.             var lastMove = moveQueue[0] || currentDirection;
  199.  
  200.             switch (keyNum) {
  201.                 case 37:
  202.                     if ( lastMove !== 1 || snakeLength === 1 ) {
  203.                         moveQueue.unshift(3); //SnakeDirection = 3;
  204.                     }
  205.                     break;    
  206.                 case 38:
  207.                     if ( lastMove !== 2 || snakeLength === 1 ) {
  208.                         moveQueue.unshift(0);//SnakeDirection = 0;
  209.                     }
  210.                     break;    
  211.                 case 39:
  212.                     if ( lastMove !== 3 || snakeLength === 1 ) {
  213.                         moveQueue.unshift(1); //SnakeDirection = 1;
  214.                     }
  215.                     break;    
  216.                 case 40:
  217.                     if ( lastMove !== 0 || snakeLength === 1 ) {
  218.                         moveQueue.unshift(2);//SnakeDirection = 2;
  219.                     }
  220.                     break;  
  221.             }
  222.         };
  223.        
  224.         /**
  225.         * This method is executed for each move of the snake. It determines where the snake will go and what will happen to it. This method needs to run quickly.
  226.         * @method go
  227.         */
  228.         me.go = function() {
  229.        
  230.             var oldHead = me.snakeHead,
  231.                 newHead = me.snakeTail,
  232.                 myDirection = currentDirection,
  233.                 grid = playingBoard.grid; // cache grid for quicker lookup
  234.        
  235.             me.snakeTail = newHead.prev;
  236.             me.snakeHead = newHead;
  237.        
  238.             // clear the old board position
  239.             if ( grid[newHead.row] && grid[newHead.row][newHead.col] ) {
  240.                 grid[newHead.row][newHead.col] = 0;
  241.             }
  242.        
  243.             if (moveQueue.length){
  244.                 myDirection = currentDirection = moveQueue.pop();
  245.             }
  246.        
  247.             newHead.col = oldHead.col + columnShift[myDirection];
  248.             newHead.row = oldHead.row + rowShift[myDirection];
  249.             newHead.xPos = oldHead.xPos + xPosShift[myDirection];
  250.             newHead.yPos = oldHead.yPos + yPosShift[myDirection];
  251.            
  252.             if ( !newHead.elmStyle ) {
  253.                 newHead.elmStyle = newHead.elm.style;
  254.             }
  255.            
  256.             newHead.elmStyle.left = newHead.xPos + "px";
  257.             newHead.elmStyle.top = newHead.yPos + "px";
  258.  
  259.             // check the new spot the snake moved into
  260.  
  261.             if (grid[newHead.row][newHead.col] === 0) {
  262.                 grid[newHead.row][newHead.col] = 1;
  263.                 setTimeout(function(){me.go();}, snakeSpeed);
  264.             } else if (grid[newHead.row][newHead.col] > 0) {
  265.                 me.handleDeath();
  266.             } else if (grid[newHead.row][newHead.col] === playingBoard.getGridFoodValue()) {
  267.                 grid[newHead.row][newHead.col] = 1;
  268.                 me.eatFood();
  269.                 setTimeout(function(){me.go();}, snakeSpeed);
  270.             }
  271.         };
  272.        
  273.         /**
  274.         * This method is called when it is determined that the snake has eaten some food.
  275.         * @method eatFood
  276.         */
  277.         me.eatFood = function() {
  278.             if (blockPool.length <= growthIncr) {
  279.                 createBlocks(growthIncr*2);
  280.             }
  281.             var blocks = blockPool.splice(0, growthIncr);
  282.            
  283.             var ii = blocks.length,
  284.                 index,
  285.                 prevNode = me.snakeTail;
  286.             while (ii--) {
  287.                 index = "b" + me.snakeLength++;
  288.                 me.snakeBody[index] = blocks[ii];
  289.                 me.snakeBody[index].prev = prevNode;
  290.                 me.snakeBody[index].elm.className = me.snakeHead.elm.className.replace(/\bsnake-snakebody-dead\b/,'')
  291.                 me.snakeBody[index].elm.className += " snake-snakebody-alive";
  292.                 prevNode.next = me.snakeBody[index];
  293.                 prevNode = me.snakeBody[index];
  294.             }
  295.             me.snakeTail = me.snakeBody[index];
  296.             me.snakeTail.next = me.snakeHead;
  297.             me.snakeHead.prev = me.snakeTail;
  298.  
  299.             playingBoard.foodEaten();
  300.         };
  301.        
  302.         /**
  303.         * This method handles what happens when the snake dies.
  304.         * @method handleDeath
  305.         */
  306.         me.handleDeath = function() {
  307.             me.snakeHead.elm.style.zIndex = getNextHighestZIndex(me.snakeBody);
  308.             me.snakeHead.elm.className = me.snakeHead.elm.className.replace(/\bsnake-snakebody-alive\b/,'')
  309.             me.snakeHead.elm.className += " snake-snakebody-dead";
  310.  
  311.             isDead = true;
  312.             playingBoard.handleDeath();
  313.             moveQueue.length = 0;
  314.         };
  315.  
  316.         /**
  317.         * This method sets a flag that lets the snake be alive again.
  318.         * @method rebirth
  319.         */  
  320.         me.rebirth = function() {
  321.             isDead = false;
  322.         };
  323.        
  324.         /**
  325.         * This method reset the snake so it is ready for a new game.
  326.         * @method reset
  327.         */        
  328.         me.reset = function() {
  329.             if (isDead === false) {return;}
  330.            
  331.             var blocks = [],
  332.                 curNode = me.snakeHead.next,
  333.                 nextNode;
  334.             while (curNode !== me.snakeHead) {
  335.                 nextNode = curNode.next;
  336.                 curNode.prev = null;
  337.                 curNode.next = null;
  338.                 blocks.push(curNode);
  339.                 curNode = nextNode;
  340.             }
  341.             me.snakeHead.next = me.snakeHead;
  342.             me.snakeHead.prev = me.snakeHead;
  343.             me.snakeTail = me.snakeHead;
  344.             me.snakeLength = 1;
  345.            
  346.             for (var ii = 0; ii < blocks.length; ii++) {
  347.                 blocks[ii].elm.style.left = "-1000px";
  348.                 blocks[ii].elm.style.top = "-1000px";
  349.                 blocks[ii].elm.className = me.snakeHead.elm.className.replace(/\bsnake-snakebody-dead\b/,'')
  350.                 blocks[ii].elm.className += " snake-snakebody-alive";
  351.             }
  352.            
  353.             blockPool.concat(blocks);
  354.             me.snakeHead.elm.className = me.snakeHead.elm.className.replace(/\bsnake-snakebody-dead\b/,'')
  355.             me.snakeHead.elm.className += " snake-snakebody-alive";
  356.             me.snakeHead.row = config.startRow || 1;
  357.             me.snakeHead.col = config.startCol || 1;
  358.             me.snakeHead.xPos = me.snakeHead.row * playingBoard.getBlockWidth();
  359.             me.snakeHead.yPos = me.snakeHead.col * playingBoard.getBlockHeight();
  360.             me.snakeHead.elm.style.left = me.snakeHead.xPos + "px";
  361.             me.snakeHead.elm.style.top = me.snakeHead.yPos + "px";
  362.         };
  363.        
  364.         // ---------------------------------------------------------------------
  365.         // Initialize
  366.         // ---------------------------------------------------------------------
  367.        
  368.         createBlocks(growthIncr*2);
  369.         xPosShift[0] = 0;
  370.         xPosShift[1] = playingBoard.getBlockWidth();
  371.         xPosShift[2] = 0;
  372.         xPosShift[3] = -1 * playingBoard.getBlockWidth();
  373.        
  374.         yPosShift[0] = -1 * playingBoard.getBlockHeight();
  375.         yPosShift[1] = 0;
  376.         yPosShift[2] = playingBoard.getBlockHeight();
  377.         yPosShift[3] = 0;
  378.     };
  379. })();
  380.  
  381. /**
  382. * This class manages the food which the snake will eat.
  383. * @class Food
  384. * @constructor
  385. * @namespace SNAKE
  386. * @param {Object} config The configuration object for the class. Contains playingBoard (the SNAKE.Board that this food resides in).
  387. */
  388.  
  389. SNAKE.Food = SNAKE.Food || (function() {
  390.    
  391.     // -------------------------------------------------------------------------
  392.     // Private static variables and methods
  393.     // -------------------------------------------------------------------------
  394.    
  395.     var instanceNumber = 0;
  396.    
  397.     function getRandomPosition(x, y){
  398.         return Math.floor(Math.random()*(y+1-x)) + x;
  399.     }
  400.    
  401.     // -------------------------------------------------------------------------
  402.     // Contructor + public and private definitions
  403.     // -------------------------------------------------------------------------
  404.    
  405.     /*
  406.         config options:
  407.             playingBoard - the SnakeBoard that this object belongs too.
  408.     */
  409.     return function(config) {
  410.        
  411.         if (!config||!config.playingBoard) {return;}
  412.  
  413.         // ----- private variables -----
  414.  
  415.         var me = this;
  416.         var playingBoard = config.playingBoard;
  417.         var fRow, fColumn;
  418.         var myId = instanceNumber++;
  419.  
  420.         var elmFood = document.createElement("div");
  421.         elmFood.setAttribute("id", "snake-food-"+myId);
  422.         elmFood.className = "snake-food-block";
  423.         elmFood.style.width = playingBoard.getBlockWidth() + "px";
  424.         elmFood.style.height = playingBoard.getBlockHeight() + "px";
  425.         elmFood.style.left = "-1000px";
  426.         elmFood.style.top = "-1000px";
  427.         playingBoard.getBoardContainer().appendChild(elmFood);
  428.        
  429.         // ----- public methods -----
  430.        
  431.         /**
  432.         * @method getFoodElement
  433.         * @return {DOM Element} The div the represents the food.
  434.         */        
  435.         me.getFoodElement = function() {
  436.             return elmFood;  
  437.         };
  438.        
  439.         /**
  440.         * Randomly places the food onto an available location on the playing board.
  441.         * @method randomlyPlaceFood
  442.         */    
  443.         me.randomlyPlaceFood = function() {
  444.             // if there exist some food, clear its presence from the board
  445.             if (playingBoard.grid[fRow] && playingBoard.grid[fRow][fColumn] === playingBoard.getGridFoodValue()){
  446.                 playingBoard.grid[fRow][fColumn] = 0;
  447.             }
  448.  
  449.             var row = 0, col = 0, numTries = 0;
  450.  
  451.             var maxRows = playingBoard.grid.length-1;
  452.             var maxCols = playingBoard.grid[0].length-1;
  453.            
  454.             while (playingBoard.grid[row][col] !== 0){
  455.                 row = getRandomPosition(1, maxRows);
  456.                 col = getRandomPosition(1, maxCols);
  457.  
  458.                 // in some cases there may not be any room to put food anywhere
  459.                 // instead of freezing, exit out
  460.                 numTries++;
  461.                 if (numTries > 20000){
  462.                     row = -1;
  463.                     col = -1;
  464.                     break;
  465.                 }
  466.             }
  467.  
  468.             playingBoard.grid[row][col] = playingBoard.getGridFoodValue();
  469.             fRow = row;
  470.             fColumn = col;
  471.             elmFood.style.top = row * playingBoard.getBlockHeight() + "px";
  472.             elmFood.style.left = col * playingBoard.getBlockWidth() + "px";
  473.         };
  474.     };
  475. })();
  476.  
  477. /**
  478. * This class manages playing board for the game.
  479. * @class Board
  480. * @constructor
  481. * @namespace SNAKE
  482. * @param {Object} config The configuration object for the class. Set fullScreen equal to true if you want the game to take up the full screen, otherwise, set the top, left, width and height parameters.
  483. */
  484.  
  485. SNAKE.Board = SNAKE.Board || (function() {
  486.  
  487.     // -------------------------------------------------------------------------
  488.     // Private static variables and methods
  489.     // -------------------------------------------------------------------------
  490.  
  491.     var instanceNumber = 0;
  492.  
  493.     // this function is adapted from the example at http://greengeckodesign.com/blog/2007/07/get-highest-z-index-in-javascript.html
  494.     function getNextHighestZIndex(myObj) {
  495.         var highestIndex = 0,
  496.             currentIndex = 0,
  497.             ii;
  498.         for (ii in myObj) {
  499.             if (myObj[ii].elm.currentStyle){  
  500.                 currentIndex = parseFloat(myObj[ii].elm.style["z-index"],10);
  501.             }else if(window.getComputedStyle) {
  502.                 currentIndex = parseFloat(document.defaultView.getComputedStyle(myObj[ii].elm,null).getPropertyValue("z-index"),10);  
  503.             }
  504.             if(!isNaN(currentIndex) && currentIndex > highestIndex){
  505.                 highestIndex = currentIndex;
  506.             }
  507.         }
  508.         return(highestIndex+1);  
  509.     }
  510.  
  511.     /*
  512.         This function returns the width of the available screen real estate that we have
  513.     */
  514.     function getClientWidth(){
  515.         var myWidth = 0;
  516.         if( typeof window.innerWidth === "number" ) {
  517.             myWidth = window.innerWidth;//Non-IE
  518.         } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
  519.             myWidth = document.documentElement.clientWidth;//IE 6+ in 'standards compliant mode'
  520.         } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
  521.             myWidth = document.body.clientWidth;//IE 4 compatible
  522.         }
  523.         return myWidth;
  524.     }
  525.     /*
  526.         This function returns the height of the available screen real estate that we have
  527.     */
  528.     function getClientHeight(){
  529.         var myHeight = 0;
  530.         if( typeof window.innerHeight === "number" ) {
  531.             myHeight = window.innerHeight;//Non-IE
  532.         } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
  533.             myHeight = document.documentElement.clientHeight;//IE 6+ in 'standards compliant mode'
  534.         } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
  535.             myHeight = document.body.clientHeight;//IE 4 compatible
  536.         }
  537.         return myHeight;
  538.     }
  539.  
  540.     // -------------------------------------------------------------------------
  541.     // Contructor + public and private definitions
  542.     // -------------------------------------------------------------------------
  543.    
  544.     return function(inputConfig) {
  545.    
  546.         // --- private variables ---
  547.         var me = this,
  548.             myId = instanceNumber++,
  549.             config = inputConfig || {},
  550.             MAX_BOARD_COLS = 250,
  551.             MAX_BOARD_ROWS = 250,
  552.             blockWidth = 20,
  553.             blockHeight = 20,
  554.             GRID_FOOD_VALUE = -1, // the value of a spot on the board that represents snake food, MUST BE NEGATIVE
  555.             myFood,
  556.             mySnake,
  557.             boardState = 1, // 0: in active; 1: awaiting game start; 2: playing game
  558.             myKeyListener,
  559.             // Board components
  560.             elmContainer, elmPlayingField, elmAboutPanel, elmLengthPanel, elmWelcome, elmTryAgain;
  561.        
  562.         // --- public variables ---
  563.         me.grid = [];
  564.        
  565.         // ---------------------------------------------------------------------
  566.         // private functions
  567.         // ---------------------------------------------------------------------
  568.        
  569.         function createBoardElements() {
  570.             elmPlayingField = document.createElement("div");
  571.             elmPlayingField.setAttribute("id", "playingField");
  572.             elmPlayingField.className = "snake-playing-field";
  573.            
  574.             SNAKE.addEventListener(elmPlayingField, "click", function() {
  575.                 elmContainer.focus();
  576.             }, false);
  577.            
  578.             elmAboutPanel = document.createElement("div");
  579.             elmAboutPanel.className = "snake-panel-component";
  580.             elmAboutPanel.innerHTML = "<a href='http://patorjk.com/blog/software/' class='snake-link'>more patorjk.com apps</a> - <a href='https://github.com/patorjk/JavaScript-Snake' class='snake-link'>source code</a>";
  581.            
  582.             elmLengthPanel = document.createElement("div");
  583.             elmLengthPanel.className = "snake-panel-component";
  584.             elmLengthPanel.innerHTML = "Length: 1";
  585.            
  586.             elmWelcome = createWelcomeElement();
  587.             elmTryAgain = createTryAgainElement();
  588.            
  589.             SNAKE.addEventListener( elmContainer, "keyup", function(evt) {
  590.                 if (!evt) var evt = window.event;
  591.                 evt.cancelBubble = true;
  592.                 if (evt.stopPropagation) {evt.stopPropagation();}
  593.                 if (evt.preventDefault) {evt.preventDefault();}
  594.                 return false;
  595.             }, false);
  596.            
  597.             elmContainer.className = "snake-game-container";
  598.            
  599.             elmContainer.appendChild(elmPlayingField);
  600.             elmContainer.appendChild(elmAboutPanel);
  601.             elmContainer.appendChild(elmLengthPanel);
  602.             elmContainer.appendChild(elmWelcome);
  603.             elmContainer.appendChild(elmTryAgain);
  604.            
  605.             mySnake = new SNAKE.Snake({playingBoard:me,startRow:2,startCol:2});
  606.             myFood = new SNAKE.Food({playingBoard: me});
  607.            
  608.             elmWelcome.style.zIndex = 1000;
  609.         }
  610.         function maxBoardWidth() {
  611.             return MAX_BOARD_COLS * me.getBlockWidth();  
  612.         }
  613.         function maxBoardHeight() {
  614.             return MAX_BOARD_ROWS * me.getBlockHeight();
  615.         }
  616.        
  617.         function createWelcomeElement() {
  618.             var tmpElm = document.createElement("div");
  619.             tmpElm.id = "sbWelcome" + myId;
  620.             tmpElm.className = "snake-welcome-dialog";
  621.            
  622.             var welcomeTxt = document.createElement("div");
  623.             var fullScreenText = "";
  624.             if (config.fullScreen) {
  625.                 fullScreenText = "On Windows, press F11 to play in Full Screen mode.";  
  626.             }
  627.             welcomeTxt.innerHTML = "JavaScript Snake<p></p>Use the <strong>arrow keys</strong> on your keyboard to play the game. " + fullScreenText + "<p></p>";
  628.             var welcomeStart = document.createElement("button");
  629.             welcomeStart.appendChild( document.createTextNode("Play Game"));
  630.            
  631.             var loadGame = function() {
  632.                 SNAKE.removeEventListener(window, "keyup", kbShortcut, false);
  633.                 tmpElm.style.display = "none";
  634.                 me.setBoardState(1);
  635.                 me.getBoardContainer().focus();
  636.             };
  637.            
  638.             var kbShortcut = function(evt) {
  639.                 if (!evt) var evt = window.event;
  640.                 var keyNum = (evt.which) ? evt.which : evt.keyCode;
  641.                 if (keyNum === 32 || keyNum === 13) {
  642.                     loadGame();
  643.                 }
  644.             };
  645.             SNAKE.addEventListener(window, "keyup", kbShortcut, false);
  646.             SNAKE.addEventListener(welcomeStart, "click", loadGame, false);
  647.            
  648.             tmpElm.appendChild(welcomeTxt);
  649.             tmpElm.appendChild(welcomeStart);
  650.             return tmpElm;
  651.         }
  652.        
  653.         function createTryAgainElement() {
  654.             var tmpElm = document.createElement("div");
  655.             tmpElm.id = "sbTryAgain" + myId;
  656.             tmpElm.className = "snake-try-again-dialog";
  657.            
  658.             var tryAgainTxt = document.createElement("div");
  659.             tryAgainTxt.innerHTML = "JavaScript Snake<p></p>You died :(.<p></p>";
  660.             var tryAgainStart = document.createElement("button");
  661.             tryAgainStart.appendChild( document.createTextNode("Play Again?"));
  662.            
  663.             var reloadGame = function() {
  664.                 tmpElm.style.display = "none";
  665.                 me.resetBoard();
  666.                 me.setBoardState(1);
  667.                 me.getBoardContainer().focus();
  668.             };
  669.            
  670.             var kbTryAgainShortcut = function(evt) {
  671.                 if (boardState !== 0 || tmpElm.style.display !== "block") {return;}
  672.                 if (!evt) var evt = window.event;
  673.                 var keyNum = (evt.which) ? evt.which : evt.keyCode;
  674.                 if (keyNum === 32 || keyNum === 13) {
  675.                     reloadGame();
  676.                 }
  677.             };
  678.             SNAKE.addEventListener(window, "keyup", kbTryAgainShortcut, true);
  679.            
  680.             SNAKE.addEventListener(tryAgainStart, "click", reloadGame, false);
  681.             tmpElm.appendChild(tryAgainTxt);
  682.             tmpElm.appendChild(tryAgainStart);
  683.             return tmpElm;
  684.         }
  685.        
  686.         // ---------------------------------------------------------------------
  687.         // public functions
  688.         // ---------------------------------------------------------------------
  689.        
  690.         /**
  691.         * Resets the playing board for a new game.
  692.         * @method resetBoard
  693.         */  
  694.         me.resetBoard = function() {
  695.             SNAKE.removeEventListener(elmContainer, "keydown", myKeyListener, false);
  696.             mySnake.reset();
  697.             elmLengthPanel.innerHTML = "Length: 1";
  698.             me.setupPlayingField();
  699.         };
  700.         /**
  701.         * Gets the current state of the playing board. There are 3 states: 0 - Welcome or Try Again dialog is present. 1 - User has pressed "Start Game" on the Welcome or Try Again dialog but has not pressed an arrow key to move the snake. 2 - The game is in progress and the snake is moving.
  702.         * @method getBoardState
  703.         * @return {Number} The state of the board.
  704.         */  
  705.         me.getBoardState = function() {
  706.             return boardState;
  707.         };
  708.         /**
  709.         * Sets the current state of the playing board. There are 3 states: 0 - Welcome or Try Again dialog is present. 1 - User has pressed "Start Game" on the Welcome or Try Again dialog but has not pressed an arrow key to move the snake. 2 - The game is in progress and the snake is moving.
  710.         * @method setBoardState
  711.         * @param {Number} state The state of the board.
  712.         */  
  713.         me.setBoardState = function(state) {
  714.             boardState = state;
  715.         };
  716.         /**
  717.         * @method getGridFoodValue
  718.         * @return {Number} A number that represents food on a number representation of the playing board.
  719.         */  
  720.         me.getGridFoodValue = function() {
  721.             return GRID_FOOD_VALUE;
  722.         };
  723.         /**
  724.         * @method getPlayingFieldElement
  725.         * @return {DOM Element} The div representing the playing field (this is where the snake can move).
  726.         */
  727.         me.getPlayingFieldElement = function() {
  728.             return elmPlayingField;
  729.         };
  730.         /**
  731.         * @method setBoardContainer
  732.         * @param {DOM Element or String} myContainer Sets the container element for the game.
  733.         */
  734.         me.setBoardContainer = function(myContainer) {
  735.             if (typeof myContainer === "string") {
  736.                 myContainer = document.getElementById(myContainer);  
  737.             }
  738.             if (myContainer === elmContainer) {return;}
  739.             elmContainer = myContainer;
  740.             elmPlayingField = null;
  741.            
  742.             me.setupPlayingField();
  743.         };
  744.         /**
  745.         * @method getBoardContainer
  746.         * @return {DOM Element}
  747.         */
  748.         me.getBoardContainer = function() {
  749.             return elmContainer;
  750.         };
  751.         /**
  752.         * @method getBlockWidth
  753.         * @return {Number}
  754.         */
  755.         me.getBlockWidth = function() {
  756.             return blockWidth;  
  757.         };
  758.         /**
  759.         * @method getBlockHeight
  760.         * @return {Number}
  761.         */
  762.         me.getBlockHeight = function() {
  763.             return blockHeight;  
  764.         };
  765.         /**
  766.         * Sets up the playing field.
  767.         * @method setupPlayingField
  768.         */
  769.         me.setupPlayingField = function () {
  770.            
  771.             if (!elmPlayingField) {createBoardElements();} // create playing field
  772.            
  773.             // calculate width of our game container
  774.             var cWidth, cHeight;
  775.             if (config.fullScreen === true) {
  776.                 cTop = 0;
  777.                 cLeft = 0;
  778.                 cWidth = getClientWidth()-5;
  779.                 cHeight = getClientHeight()-5;
  780.                 document.body.style.backgroundColor = "#FC5454";
  781.             } else {
  782.                 cTop = config.top;
  783.                 cLeft = config.left;
  784.                 cWidth = config.width;
  785.                 cHeight = config.height;
  786.             }
  787.            
  788.             // define the dimensions of the board and playing field
  789.             var wEdgeSpace = me.getBlockWidth()*2 + (cWidth % me.getBlockWidth());
  790.             var fWidth = Math.min(maxBoardWidth()-wEdgeSpace,cWidth-wEdgeSpace);
  791.             var hEdgeSpace = me.getBlockHeight()*3 + (cHeight % me.getBlockHeight());
  792.             var fHeight = Math.min(maxBoardHeight()-hEdgeSpace,cHeight-hEdgeSpace);
  793.            
  794.             elmContainer.style.left = cLeft + "px";
  795.             elmContainer.style.top = cTop + "px";
  796.             elmContainer.style.width = cWidth + "px";
  797.             elmContainer.style.height = cHeight + "px";
  798.             elmPlayingField.style.left = me.getBlockWidth() + "px";
  799.             elmPlayingField.style.top  = me.getBlockHeight() + "px";
  800.             elmPlayingField.style.width = fWidth + "px";
  801.             elmPlayingField.style.height = fHeight + "px";
  802.            
  803.             // the math for this will need to change depending on font size, padding, etc
  804.             // assuming height of 14 (font size) + 8 (padding)
  805.             var bottomPanelHeight = hEdgeSpace - me.getBlockHeight();
  806.             var pLabelTop = me.getBlockHeight() + fHeight + Math.round((bottomPanelHeight - 30)/2) + "px";
  807.            
  808.             elmAboutPanel.style.top = pLabelTop;
  809.             elmAboutPanel.style.width = "450px";
  810.             elmAboutPanel.style.left = Math.round(cWidth/2) - Math.round(450/2) + "px";
  811.            
  812.             elmLengthPanel.style.top = pLabelTop;
  813.             elmLengthPanel.style.left = cWidth - 120 + "px";
  814.            
  815.             // if width is too narrow, hide the about panel
  816.             if (cWidth < 700) {
  817.                 elmAboutPanel.style.display = "none";
  818.             } else {
  819.                 elmAboutPanel.style.display = "block";
  820.             }
  821.            
  822.             me.grid = [];
  823.             var numBoardCols = fWidth / me.getBlockWidth() + 2;
  824.             var numBoardRows = fHeight / me.getBlockHeight() + 2;
  825.            
  826.             for (var row = 0; row < numBoardRows; row++) {
  827.                 me.grid[row] = [];
  828.                 for (var col = 0; col < numBoardCols; col++) {
  829.                     if (col === 0 || row === 0 || col === (numBoardCols-1) || row === (numBoardRows-1)) {
  830.                         me.grid[row][col] = 1; // an edge
  831.                     } else {
  832.                         me.grid[row][col] = 0; // empty space
  833.                     }
  834.                 }
  835.             }
  836.            
  837.             myFood.randomlyPlaceFood();
  838.            
  839.             // setup event listeners
  840.            
  841.             myKeyListener = function(evt) {
  842.                 if (!evt) var evt = window.event;
  843.                 var keyNum = (evt.which) ? evt.which : evt.keyCode;
  844.  
  845.                 if (me.getBoardState() === 1) {
  846.                     if ( !(keyNum >= 37 && keyNum <= 40) ) {return;} // if not an arrow key, leave
  847.                    
  848.                     // This removes the listener added at the #listenerX line
  849.                     SNAKE.removeEventListener(elmContainer, "keydown", myKeyListener, false);
  850.                    
  851.                     myKeyListener = function(evt) {
  852.                         if (!evt) var evt = window.event;
  853.                         var keyNum = (evt.which) ? evt.which : evt.keyCode;
  854.                        
  855.                         mySnake.handleArrowKeys(keyNum);
  856.                        
  857.                         evt.cancelBubble = true;
  858.                         if (evt.stopPropagation) {evt.stopPropagation();}
  859.                         if (evt.preventDefault) {evt.preventDefault();}
  860.                         return false;
  861.                     };
  862.                     SNAKE.addEventListener( elmContainer, "keydown", myKeyListener, false);
  863.                    
  864.                     mySnake.rebirth();
  865.                     mySnake.handleArrowKeys(keyNum);
  866.                     me.setBoardState(2); // start the game!
  867.                     mySnake.go();
  868.                 }
  869.                
  870.                 evt.cancelBubble = true;
  871.                 if (evt.stopPropagation) {evt.stopPropagation();}
  872.                 if (evt.preventDefault) {evt.preventDefault();}
  873.                 return false;
  874.             };
  875.            
  876.             // Search for #listenerX to see where this is removed
  877.             SNAKE.addEventListener( elmContainer, "keydown", myKeyListener, false);
  878.         };
  879.        
  880.         /**
  881.         * This method is called when the snake has eaten some food.
  882.         * @method foodEaten
  883.         */
  884.         me.foodEaten = function() {
  885.             elmLengthPanel.innerHTML = "Length: " + mySnake.snakeLength;
  886.             myFood.randomlyPlaceFood();
  887.         };
  888.        
  889.         /**
  890.         * This method is called when the snake dies.
  891.         * @method handleDeath
  892.         */
  893.         me.handleDeath = function() {
  894.             var index = Math.max(getNextHighestZIndex( mySnake.snakeBody), getNextHighestZIndex( {tmp:{elm:myFood.getFoodElement()}} ));
  895.             elmContainer.removeChild(elmTryAgain);
  896.             elmContainer.appendChild(elmTryAgain);
  897.             elmTryAgain.style.zIndex = index;
  898.             elmTryAgain.style.display = "block";
  899.             me.setBoardState(0);
  900.         };
  901.        
  902.         // ---------------------------------------------------------------------
  903.         // Initialize
  904.         // ---------------------------------------------------------------------
  905.  
  906.         config.fullScreen = (typeof config.fullScreen === "undefined") ? false : config.fullScreen;        
  907.         config.top = (typeof config.top === "undefined") ? 0 : config.top;
  908.         config.left = (typeof config.left === "undefined") ? 0 : config.left;
  909.         config.width = (typeof config.width === "undefined") ? 400 : config.width;        
  910.         config.height = (typeof config.height === "undefined") ? 400 : config.height;
  911.        
  912.         if (config.fullScreen) {
  913.             SNAKE.addEventListener(window,"resize", function() {
  914.                 me.setupPlayingField();
  915.             }, false);
  916.         }
  917.        
  918.         me.setBoardState(0);
  919.        
  920.         if (config.boardContainer) {
  921.             me.setBoardContainer(config.boardContainer);
  922.         }
  923.        
  924.     }; // end return function
  925. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement