Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var Maze = Class({
- $statics: {
- N: 1,
- S: 2,
- E: 4,
- W: 8,
- DX: {
- E: 1,
- W: -1,
- N: 0,
- S: 0
- },
- DY: {
- E: 0,
- W: 0,
- N: -1,
- S: 1
- },
- OPPOSITE: {
- E: this.W,
- W: this.E,
- N: this.S,
- S: this.N
- },
- directions: ['N', 'S', 'E', 'W'],
- dirVal: {
- E: this.E,
- W: this.W,
- N: this.N,
- S: this.S
- },
- shuffle: function(arr) {
- for (var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
- return arr;
- },
- create2DArray: function(h, w) {
- var array = [];
- for (var i = 0; i < h; i++) {
- array[i] = [];
- }
- for (i = 0; i < h; i++) {
- for (var j = 0; j < w; j++) {
- array[i][j] = 0;
- }
- }
- return array;
- }
- },
- constructor: function(width, height) {
- this.width = width;
- this.height = height;
- this.grid = this.create2DArray(this.height, this.width);
- this.maze = this.create2DArray(2 * this.height + 1, 2 * this.width + 1);
- this.carve_pass();
- this.toBlocks();
- this.toArray();
- },
- carve_pass: function(cx, cy) {
- cx = cx ? cx : 0;
- cy = cy ? cy : 0;
- this.directions = this.shuffle(this.directions);
- for (var i = 0; i < 4; i++) {
- var direction = this.directions[i];
- var nx = cx + this.DX[direction],
- ny = cy + this.DY[direction];
- if (this.grid && ny >= 0 && ny <= ((this.grid).length - 1) && nx >= 0 && nx <= ((this.grid).length - 1) && this.grid[ny][nx] === 0) {
- this.grid[cy][cx] |= this.dirVal[direction];
- this.grid[ny][nx] |= this.OPPOSITE[direction];
- this.carve_pass(nx, ny);
- }
- }
- },
- toBlocks: function() {
- if (this.maze) {
- for (var i = 0; i < 2 * this.width + 1; i++) {
- this.maze[0][i] = 1;
- this.maze[2 * this.height][i] = 1;
- this.maze[i][0] = 1;
- this.maze[i][this.width * 2] = 1;
- }
- var x, y;
- for (i = 0; i < this.height; i++) {
- for (var j = 0; j < this.width; j++) {
- x = i * 2 + 1;
- y = j * 2 + 1;
- this.maze[x + 1][y] = (this.grid[i][j] & this.S) === 0;
- if (this.grid[i][j] & this.E)
- this.maze[x + 1][y + 1] = ((this.grid[i][j] | this.grid[i][j + 1]) & this.S) === 0;
- else
- this.maze[x][y + 1] = this.maze[x + 1][y + 1] = 1;
- }
- }
- }
- },
- toArray: function() {
- if (this.maze) {
- for (var i = 0; i < 2 * this.height + 1; i++) {
- var line = '';
- for (var j = 0; j < 2 * this.width + 1; j++) {
- line += ((this.maze[i][j]) ? '#' : '.');
- }
- document.write(line + "<br>");
- }
- }
- },
- getMazeArray: function() {
- // console.log(this.width);
- return this.maze;
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement