Advertisement
Guest User

Untitled

a guest
Aug 18th, 2013
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Game = {
  2.     // This defines our grid's size and the size of each of its tiles
  3.     map_grid: {
  4.         width:  32 *3,
  5.         height: 32 *3,
  6.         tile: {
  7.             width:  32,
  8.             height: 32
  9.         },
  10.         map: {},
  11.         map_entities: []
  12.     },
  13.  
  14.     // The total width of the game screen. Since our grid takes up the entire screen
  15.     //  this is just the width of a tile times the width of the grid
  16.     width: function() {
  17.         return this.map_grid.width * this.map_grid.tile.width;
  18.     },
  19.  
  20.     // The total height of the game screen. Since our grid takes up the entire screen
  21.     //  this is just the height of a tile times the height of the grid
  22.     height: function() {
  23.         return this.map_grid.height * this.map_grid.tile.height;
  24.     },
  25.  
  26.     // Initialize and start our game
  27.     start: function() {
  28.         // Start crafty and set a background color so that we can see it's working
  29.         Crafty.init(Game.width(), Game.height());
  30.         Crafty.background('rgb(87, 109, 20)');
  31.  
  32.         // Simply start the "Loading" scene to get things going
  33.         Crafty.scene('Loading');
  34.     }
  35. }
  36.  
  37. // The Grid component allows an element to be located
  38. //  on a grid of tiles
  39. Crafty.c('Grid', {
  40.     init: function() {
  41.         this.attr({
  42.             w: Game.map_grid.tile.width,
  43.             h: Game.map_grid.tile.height
  44.         })
  45.     },
  46.  
  47.     // Locate this entity at the given position on the grid
  48.     at: function(x, y) {
  49.         if (x === undefined && y === undefined) {
  50.             return { x: this.x/Game.map_grid.tile.width, y: this.y/Game.map_grid.tile.height }
  51.         } else {
  52.             this.attr({ x: x * Game.map_grid.tile.width, y: y * Game.map_grid.tile.height });
  53.             return this;
  54.         }
  55.     }
  56. });
  57.  
  58. // An "Actor" is an entity that is drawn in 2D on canvas
  59. //  via our logical coordinate grid
  60. Crafty.c('Actor', {
  61.     init: function() {
  62.         this.requires('2D, Canvas, Grid');
  63.     },
  64. });
  65.  
  66.  
  67. //player position
  68. //hardcoded initial position
  69.  
  70.  
  71.  
  72. // This is the player-controlled character
  73. Crafty.c('PlayerCharacter', {
  74.     init: function() {
  75.         this.requires('Actor, Fourway, Collision, spr_player, SpriteAnimation')
  76.             //speed given here
  77.             .fourway(2)
  78.             //TODO put back in
  79.             //.stopOnSolids()
  80.             .onHit('Village', this.visitVillage)
  81.  
  82.             .animate('PlayerMovingUp',    0, 1, 7)
  83.             .animate('PlayerMovingRight', 8, 0, 15)
  84.             .animate('PlayerMovingDown',  8, 1, 15)
  85.             .animate('PlayerMovingLeft',  0, 0, 7);
  86.  
  87.         // Watch for a change of direction and switch animations accordingly
  88.         var animation_speed = 4;
  89.         this.bind('NewDirection', function(data) {
  90.             this.stop();
  91.             if (data.x > 0) {
  92.                 this.animate('PlayerMovingRight', animation_speed, -1);
  93.             } else if (data.x < 0) {
  94.                 this.animate('PlayerMovingLeft', animation_speed, -1);
  95.             } else if (data.y > 0) {
  96.                 this.animate('PlayerMovingDown', animation_speed, -1);
  97.             } else if (data.y < 0) {
  98.                 this.animate('PlayerMovingUp', animation_speed, -1);
  99.             }
  100.         });
  101.         this.player = new Player();
  102.         this.player.submap.x = 5;
  103.         this.player.submap.y = 5;
  104.         this.bind("Change", this.updatePlayerChanged);
  105.         this.bind("Moved", this.updatePlayerMoved);
  106.         this.bind("KeyDown", this.updatePlayerKeyDown);
  107.     },
  108.  
  109.     updatePlayerMoved: function(pos)
  110.     {
  111.         //console.log(pos);
  112.         var vpx = this._x - (Crafty.viewport.width/2),
  113.             vpy = this._y - (Crafty.viewport.height/2);
  114.  
  115.         if(vpx > 0 && vpx < (Game.width() - Crafty.viewport.width) ){
  116.             Crafty.viewport.x= -vpx;
  117.         }
  118.         if(vpy > 0 && vpy < (Game.height()- Crafty.viewport.height) ){
  119.             Crafty.viewport.y= -vpy;
  120.         }
  121.  
  122.  
  123.         if(typeof pos === "undefined") return;
  124.  
  125.         var pix_per_submap = this.player.submap_size * 32;
  126.         var x_submap_offset = this.player.view_map["xorigin"] - this.player.view_map_radius;
  127.         var y_submap_offset = this.player.view_map["yorigin"] - this.player.view_map_radius;
  128.  
  129.         this.player.submap.x = Math.floor(pos.x/ pix_per_submap) + x_submap_offset;
  130.         this.player.submap.y = Math.floor(pos.y/ pix_per_submap) + y_submap_offset;
  131.        
  132.         this.player.submap_pos.x = pos.x % pix_per_submap;
  133.         this.player.submap_pos.y = pos.y % pix_per_submap;
  134.         this.player.global_pos = this.player.submap_to_global(this.player.submap, this.player.submap_pos);
  135.  
  136.         //TODO chnage the if to trigger when player is on teh boundary of the view map
  137.         // see view_map_radius in player class
  138.  
  139.         console.log(this.player.submap_pos.x + "," + this.player.submap_pos.y + "  " + this.player.submap.x + "," + this.player.submap.y + "  " +
  140.             this.player.global_pos.x + "," + this.player.global_pos.y + " " +
  141.             pos.x + "," + pos.y
  142.             );
  143.         if(this.player.submap.x != this.player.view_map["xorigin"] || this.player.submap.y != this.player.view_map["yorigin"]){
  144.  
  145.             console.log("***new view map origin " + this.player.submap.x + "," + this.player.submap.y);
  146.             var start = new Date().getTime();
  147.             this.player.fill_buffer_view_map(Game.map_grid.map, this.player.submap.x, this.player.submap.y);
  148.             this.player.switch_view_maps();
  149.             this.view_map = this.player.view_map;
  150.  
  151.             for(var i = 0; i < Game.map_grid.map_entities.length; i ++){
  152.  
  153.                 Game.map_grid.map_entities[i].destroy();
  154.             }
  155.             Game.map_grid.map_entities = [];
  156.  
  157. // RENDER TERRAIN CODE TO BE TAKEN INTO SEPARATE METHOD
  158.                 //render background terrain
  159.             for (var i = 0; i < this.view_map["background"].length; i++) {
  160.  
  161.                 var tile_object = this.view_map["background"][i];
  162.                 var tile = tile_object["type"];
  163.                 var tile_ent = Crafty.e("Actor", "spr_"+tile);
  164.                 tile_ent.at(tile_object["x"] - this.view_map["xoffset"], tile_object["y"] - this.view_map["yoffset"]);
  165.                 tile_ent.z = 0;
  166.                 Game.map_grid.map_entities.push(tile_ent);
  167.             }
  168.  
  169.             //render background terrain
  170.             for (var i = 0; i < this.view_map["detail"].length; i++) {
  171.                 var tile_object = this.view_map["detail"][i];
  172.  
  173.                 var tile = tile_object["type"];
  174.                 var tile_ent = Crafty.e("Actor", "Solid", "spr_"+tile);
  175.                 tile_ent.at(tile_object["x"] - this.view_map["xoffset"], tile_object["y"] - this.view_map["yoffset"]);
  176.                 tile_ent.shift(tile_object["xoffset"], tile_object["yoffset"]);
  177.                 tile_ent.z = 1;
  178.                 Game.map_grid.map_entities.push(tile_ent);
  179.             }
  180.  
  181.             var end = new Date().getTime();
  182.             var time = end - start;
  183.             console.log(this.view_map["background"].length + " + " + this.view_map["detail"].length + " map tiles loaded in " + time + "ms");
  184.             this.shift(0, pix_per_submap);
  185.             console.log("set new origin " + this.player.view_map["xorigin"] + "," + this.player.view_map["yorigin"]);
  186.  
  187.         }
  188.     },
  189.  
  190.     updatePlayerChanged: function(pos)
  191.     {
  192.        
  193.     },
  194.  
  195.     //store key presses
  196.     updatePlayerKeyDown: function(e)
  197.     {
  198.         /*
  199.         //TODO link to players input buffer
  200.         Taking out just now
  201.         if(e.key == Crafty.keys['LEFT_ARROW']) {
  202.  
  203.            this.key_inputs.push("l");
  204.  
  205.         } else if (e.key == Crafty.keys['RIGHT_ARROW']) {
  206.  
  207.             this.key_inputs.push("r");
  208.  
  209.         } else if (e.key == Crafty.keys['UP_ARROW']) {
  210.  
  211.             this.key_inputs.push("u");
  212.  
  213.         } else if (e.key == Crafty.keys['DOWN_ARROW']) {
  214.  
  215.             this.key_inputs.push("d");
  216.         }
  217.         */
  218.     },
  219.  
  220.  
  221.     // Registers a stop-movement function to be called when
  222.     //  this entity hits an entity with the "Solid" component
  223.     stopOnSolids: function() {
  224.         this.onHit('Solid', this.stopMovement);
  225.  
  226.         return this;
  227.     },
  228.  
  229.     // Stops the movement
  230.     stopMovement: function() {
  231.         this._speed = 0;
  232.         if (this._movement) {
  233.             this.x -= this._movement.x;
  234.             this.y -= this._movement.y;
  235.         }
  236.     },
  237.  
  238. });
  239.  
  240.  
  241.  
  242.  
  243. // Game scene
  244. // -------------
  245. // Runs the core gameplay loop
  246. Crafty.scene('Game', function() {
  247.  
  248.    
  249.  
  250.  
  251.  
  252.     Crafty.viewport.init(16*Game.map_grid.tile.width, 16*Game.map_grid.tile.height);
  253.  
  254.     // A 2D array to keep track of all occupied tiles
  255.     this.occupied = new Array(Game.map_grid.width);
  256.     for (var i = 0; i < Game.map_grid.width; i++) {
  257.         this.occupied[i] = new Array(Game.map_grid.height);
  258.         for (var y = 0; y < Game.map_grid.height; y++) {
  259.             this.occupied[i][y] = false;
  260.         }
  261.     }
  262.  
  263.  
  264.     // Player character, placed at 5, 5 on our grid
  265.     this.player = Crafty.e('PlayerCharacter').at(33, 33);
  266.     Crafty.viewport.centerOn(this.player, 1);
  267.     this.occupied[this.player.at().x][this.player.at().y] = true;
  268.     this.player.z = 2;
  269.  
  270.     //load surrounding maps
  271.     var pp = this.player.player.submap;
  272.    
  273.  
  274.     //get map terrain for current submap
  275.    
  276.     var start = new Date().getTime();
  277.     this.player.player.set_view_map(Game.map_grid.map);
  278.     this.view_map = this.player.player.view_map;
  279.    
  280.  
  281.     /*TODO
  282.  
  283.     Instead of loading just current submap, work out what tiles are needed for a submap buffer
  284.     */
  285.  
  286.    
  287.     //=========================================================
  288.     // RENDER TERRAIN FOR THE FIRST TIME
  289.     //=========================================================
  290.    
  291.  
  292.  
  293.     //render background terrain
  294.     for (var i = 0; i < this.view_map["background"].length; i++) {
  295.  
  296.         var tile_object = this.view_map["background"][i];
  297.         var tile = tile_object["type"];
  298.         var tile_ent = Crafty.e("Actor", "spr_"+tile);
  299.         tile_ent.at(tile_object["x"] - this.view_map["xoffset"], tile_object["y"] - this.view_map["yoffset"]);
  300.         tile_ent.z = 0;
  301.         Game.map_grid.map_entities.push(tile_ent);
  302.     }
  303.  
  304.     //render background terrain
  305.     for (var i = 0; i < this.view_map["detail"].length; i++) {
  306.         var tile_object = this.view_map["detail"][i];
  307.  
  308.         var tile = tile_object["type"];
  309.         //var tile_ent = Crafty.e("Actor", "Solid", "spr_"+tile);
  310.         var tile_ent = Crafty.e("Actor", "Solid", "spr_"+tile);
  311.         tile_ent.at(tile_object["x"] - this.view_map["xoffset"], tile_object["y"] - this.view_map["yoffset"]);
  312.         tile_ent.shift(tile_object["xoffset"], tile_object["yoffset"]);
  313.         tile_ent.z = 1;
  314.         Game.map_grid.map_entities.push(tile_ent);
  315.     }
  316.  
  317.     var end = new Date().getTime();
  318.     var time = end - start;
  319.     console.log(this.view_map["background"].length + " + " + this.view_map["detail"].length + " map tiles loaded in " + time + "ms");
  320.    
  321.     // Show the victory screen once all villages are visisted
  322.     this.show_victory = this.bind('VillageVisited', function() {
  323.         if (!Crafty('Village').length) {
  324.             Crafty.scene('Victory');
  325.         }
  326.     });
  327.    
  328. }, function() {
  329.     // Remove our event binding from above so that we don't
  330.     //  end up having multiple redundant event watchers after
  331.     //  multiple restarts of the game
  332.     this.unbind('VillageVisited', this.show_victory);
  333. });
  334.  
  335.  
  336. // Victory scene
  337. // -------------
  338. // Tells the player when they've won and lets them start a new game
  339. Crafty.scene('Victory', function() {
  340.     // Display some text in celebration of the victory
  341.     Crafty.e('2D, DOM, Text')
  342.         .attr({ x: 0, y: 0 })
  343.         .text('Victory!');
  344.  
  345.     // Watch for the player to press a key, then restart the game
  346.     //  when a key is pressed
  347.     this.restart_game = this.bind('KeyDown', function() {
  348.         Crafty.scene('Game');
  349.     });
  350. }, function() {
  351.     // Remove our event binding from above so that we don't
  352.     //  end up having multiple redundant event watchers after
  353.     //  multiple restarts of the game
  354.     this.unbind('KeyDown', this.restart_game);
  355. });
  356.  
  357.  
  358. //temp network module
  359. var net_game = {};
  360.  
  361.  
  362. // Loading scene
  363. // -------------
  364. // Handles the loading of binary assets such as images and audio files
  365. Crafty.scene('Loading', function(){
  366.     // Load our sprite map image
  367.     /* old assets
  368.                 ['http://desolate-caverns-4829.herokuapp.com/assets/16x16_forest_1.gif',
  369.                 'http://desolate-caverns-4829.herokuapp.com/assets/hunter.png',
  370.                 'http://desolate-caverns-4829.herokuapp.com/assets/door_knock_3x.mp3',
  371.                 'http://desolate-caverns-4829.herokuapp.com/assets/door_knock_3x.ogg',
  372.                 'http://desolate-caverns-4829.herokuapp.com/assets/door_knock_3x.aac']
  373.     */
  374.  
  375.  
  376.     Crafty.load(
  377.         //new
  378.         //['http://localhost:4004/img/terrain/terrain.png',
  379.         //old
  380.         ['https://dl.dropboxusercontent.com/u/939544/assets/img/terrain/grass_with_cliffs.png',
  381.         'https://dl.dropboxusercontent.com/u/939544/assets/img/character/link.gif'
  382.         ], function(){
  383.         // Once the images are loaded...
  384.  
  385.         //get sprite sheet metadata
  386.         var spritesheet_json = $.ajax({
  387.             url: "/img/terrain/terrain.json",
  388.             data: "",
  389.             async: false
  390.             }).responseText;
  391.         var spritesheet_json = JSON && JSON.parse(spritesheet_json) || $.parseJSON(spritesheet_json);
  392.  
  393.         //use spritesheet_json to get sprite coordinate and size
  394.        
  395.         var spr_map = {}
  396.         var frames = spritesheet_json.frames;
  397.  
  398.         for (var i in frames) {
  399.             //create new sprite entity with filename - extension and + "spr_" at the start
  400.             var spr = "spr_"+i.slice(0,-4);
  401.             spr_map[spr] = [];
  402.             spr_map[spr][0] = frames[i]["frame"]["x"];
  403.             spr_map[spr][1] = frames[i]["frame"]["y"];
  404.             spr_map[spr][2] = frames[i]["frame"]["w"];
  405.             spr_map[spr][3] = frames[i]["frame"]["h"];
  406.         }
  407.         Crafty.sprite('http://localhost:4004/img/terrain/terrain.png', spr_map);
  408.  
  409.  
  410.         // Define the individual sprites in the image
  411.         // Each one (spr_tree, etc.) becomes a component
  412.         // These components' names are prefixed with "spr_"
  413.         //  to remind us that they simply cause the entity
  414.         //  to be drawn with a certain sprite
  415.        
  416.         //old sprite sheet
  417.         /*
  418.         Crafty.sprite(25, 25, 'https://dl.dropboxusercontent.com/u/939544/assets/img/terrain/grass_with_cliffs.png', {
  419.             spr_cliff_NE_NS:    [0,0],
  420.             spr_cliff_NE_SN:    [1,0],
  421.             spr_cliff_NW_NS:    [2,0],
  422.             spr_cliff_SE_NS:    [3,0],
  423.             spr_cliff_NS_EW:    [0,1],
  424.             spr_cliff_NS_WE:    [1,1],
  425.             spr_cliff_NW_SN:    [2,1],
  426.             spr_cliff_SE_SN:    [3,1],
  427.             spr_cliff_SW_NS:    [0,2],
  428.             spr_cliff_WE_NS:    [1,2],
  429.             spr_cliff_WE_SN:    [2,2],
  430.             spr_grass0:         [3,2],
  431.             spr_cliff_SW_SN:    [0,3],
  432.             spr_grass1:         [1,3],
  433.             spr_grass2:         [2,3],
  434.             spr_grass3:         [3,3]
  435.         });
  436.         */
  437.        
  438.  
  439.        
  440.         Crafty.sprite(24,32,'https://dl.dropboxusercontent.com/u/939544/assets/img/character/link.gif', {
  441.             spr_player:  [0, 0],
  442.         });
  443.        
  444.  
  445.         //load initial map
  446.         Game.map_grid.map = new Map();
  447.  
  448.         /*
  449.         Initiate network code here
  450.         */
  451.         //net_game = new networking();
  452.         //net_game.connect_to_server();
  453.  
  454.         // Draw some text for the player to see in case the file
  455.         //  takes a noticeable amount of time to load
  456.         Crafty.e('2D, DOM, Text')
  457.             .attr({ x: 0, y: Game.height()/2 - 24, w: Game.width() })
  458.             .text('Loading...');
  459.  
  460.         // Now that our sprites are ready to draw, start the game
  461.         Crafty.scene('Game');
  462.     })
  463. });
  464.  
  465. Game.start();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement