Skip to content

Instantly share code, notes, and snippets.

@yoo2001818
Created April 29, 2015 07:30
Show Gist options
  • Save yoo2001818/69429f7472f5006f2e8d to your computer and use it in GitHub Desktop.
Save yoo2001818/69429f7472f5006f2e8d to your computer and use it in GitHub Desktop.
TileMap rotation
function Tile(type) {
this.type = type;
}
function TileMap(w, h, initial) {
this._width = w;
this._height = h;
this.rotation = 0;
this.reset(initial);
}
TileMap.prototype.reset = function(initial) {
this.map = [];
for(var y = 0; y < this._height; ++y) {
this.map[y] = [];
for(var x = 0; x < this._width; ++x) {
this.map[y][x] = new Tile(initial || 0);
}
}
}
TileMap.prototype.getWidth = function() {
return (this.rotation % 2 != 0) ? this._height : this._width;
}
TileMap.prototype.getHeight = function() {
return (this.rotation % 2 != 0) ? this._width : this._height;
}
TileMap.prototype.get = function(x, y) {
var realX = x, realY = y;
if(this.rotation % 2 != 0) {
realX ^= realY;
realY ^= realX;
realX ^= realY;
}
if(this.rotation == 1) {
realX = this._width - realX - 1;
} else if(this.rotation == 3) {
realY = this._height - realY - 1;
} else if(this.rotation == 2) {
realX = this._width - realX - 1;
realY = this._height - realY - 1;
}
if(realX >= 0 && realX < this._width &&
realY >= 0 && realY < this._height) {
return this.map[realY][realX];
} else {
return null;
}
}
TileMap.prototype.set = function(x, y, value) {
var realX = x, realY = y;
if(this.rotation % 2 != 0) {
realX ^= realY;
realY ^= realX;
realX ^= realY;
}
if(this.rotation == 1) {
realX = this._width - realX - 1;
} else if(this.rotation == 3) {
realY = this._height - realY - 1;
} else if(this.rotation == 2) {
realX = this._width - realX - 1;
realY = this._height - realY - 1;
}
if(realX >= 0 && realX < this._width &&
realY >= 0 && realY < this._height) {
this.map[realY][realX] = value;
}
}
TileMap.prototype.rotate90 = function() {
this.rotation += 1;
this.rotation %= 4;
}
TileMap.prototype.rotate180 = function() {
this.rotation += 2;
this.rotation %= 4;
}
TileMap.prototype.rotate270 = function() {
this.rotation += 3;
this.rotation %= 4;
}
TileMap.fromArray = function(arr) {
var tileMap = new TileMap(arr[0].length, arr.length);
var w = tileMap.getWidth();
var h = tileMap.getHeight();
for(var y = 0; y < h; ++y) {
for(var x = 0; x < w; ++x) {
var tile = tileMap.get(x, y);
tile.type = arr[y][x];
}
}
return tileMap;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment