Advertisement
Guest User

map.js

a guest
Mar 15th, 2015
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //This javascript file creates a simple 2d map representation
  2.  
  3.  
  4. function d2_array(size){
  5.     //Returns a basic 2D array of specified size
  6.     x = new Array(size);
  7.     for (var i = 0; i < size; i++) {
  8.         x[i] = new Array(size)
  9.     }
  10.     for (var i = 0; i < size; i++) {
  11.         for (var j = 0; j < size; j++) {
  12.             x[i][j] = 0
  13.         }
  14.     }
  15.     return x
  16. }
  17. //-----------------------------------------------------------------------------
  18. var Map = function (size) {
  19.     //Creates an empty map
  20.     this.size = size
  21.     this.raw_map = d2_array(size)
  22. }
  23.  
  24. Map.prototype.set_point = function(x,y,z) {
  25.     //Sets the height of a specified point, doesn't have to be set to a number :-)
  26.     if (x >= this.size || y >= this.size || x < 0 || y < 0){
  27.         console.log('Improper Map Access:',x,y)
  28.     } else {
  29.         this.raw_map[x][y] = z
  30.     }
  31. }
  32.  
  33. Map.prototype.get_point = function(x,y) {
  34.     //Returns the height of a specified point or 1 if outside map area
  35.     if (x >= this.size || y >= this.size || x < 0 || y < 0){
  36.         return 1
  37.     } else {
  38.         return this.raw_map[x][y]
  39.     }
  40. }
  41.  
  42. Map.prototype.display = function(new_line, border) {
  43.     //Returns a string containing a representation of the map
  44.     out_str = '\n'
  45.     for (var i = 0-border; i < this.size+border; i++) {
  46.        
  47.         for (var j = 0-border; j < this.size+border; j++) {
  48.             out_str += this.get_point(i,j)
  49.            
  50.         }
  51.         out_str += new_line
  52.     }
  53.     return out_str
  54. }
  55.  
  56. Map.prototype.get_num_neighbours = function(x,y) {
  57.     //Returns the number of neighbours of a map
  58.     total = 0
  59.     for (var i = -1; i <= 1; i++) {
  60.         for (var j = -1; j <= 1; j++) {
  61.             total += this.get_point(x+i,y+j)
  62.         }
  63.     }
  64.     return total
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement