|
| 1 | +enum LineType { |
| 2 | + Diagonal = 0, |
| 3 | + Covering = 1 |
| 4 | +} |
| 5 | + |
1 | 6 | //% blockNamespace=scene |
2 | 7 | namespace tilesExt { |
| 8 | + |
| 9 | + //% l1.shadow=mapgettile |
| 10 | + //% l2.shadow=mapgettile |
| 11 | + export function coveringLineBetweenTiles<T>(l1: tiles.Location, l2: tiles.Location, exclusive: boolean, handler: (col: number, row: number) => T): T { |
| 12 | + // https://www.redblobgames.com/grids/line-drawing/#stepping |
| 13 | + const dx = l2.col-l1.col, dy = l2.row-l1.row; |
| 14 | + const absx = Math.abs(dx), absy = Math.abs(dy); |
| 15 | + const stepx = Math.sign(dx), stepy = Math.sign(dy); |
| 16 | + |
| 17 | + let x = l1.col, y = l1.row; |
| 18 | + let ix = 0, iy = 0; |
| 19 | + if (exclusive) { |
| 20 | + if ((1+ix<<1)*absy < (1+iy<<1)*absx) { |
| 21 | + x += stepx; |
| 22 | + ix++; |
| 23 | + } else { |
| 24 | + y += stepy; |
| 25 | + iy++; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + for (; ix < absx || iy < absy;) { |
| 30 | + const res = handler(x,y); |
| 31 | + if (res) return res; |
| 32 | + if ((1+ix<<1)*absy < (1+iy<<1)*absx) { |
| 33 | + x += stepx; |
| 34 | + ix++; |
| 35 | + } else { |
| 36 | + y += stepy; |
| 37 | + iy++; |
| 38 | + } |
| 39 | + } |
| 40 | + if (!exclusive) { |
| 41 | + const res = handler(x,y); |
| 42 | + if (res) return res; |
| 43 | + } |
| 44 | + |
| 45 | + return undefined; |
| 46 | + } |
| 47 | + |
| 48 | + export function isWallBetweenLocations(l1: tiles.Location, l2: tiles.Location, tileMap?: tiles.TileMap): tiles.Location | undefined { |
| 49 | + tileMap = tileMap || game.currentScene().tileMap; |
| 50 | + return coveringLineBetweenTiles(l1, l2, true, (x,y) => tileMap.isObstacle(x,y) ? new tiles.Location(x,y,l1.tileMap) : undefined); |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | + export function setTileBetweenLocations(l1: tiles.Location, l2: tiles.Location, im: Image, tileMap?: tiles.TileMap): void { |
| 55 | + tileMap = tileMap || game.currentScene().tileMap; |
| 56 | + const index = tileMap.getImageType(im); |
| 57 | + coveringLineBetweenTiles(l1, l2, false, (x,y) => tileMap.setTileAt(x,y,index)); |
| 58 | + } |
| 59 | + |
| 60 | + |
3 | 61 | /** |
4 | 62 | * Get a random tile of the given type |
5 | 63 | * @param tile the type of tile to get a random selection of |
|
0 commit comments