Add basic map rendering

dev
Fabian Schöttl 5 years ago
parent 731404aea0
commit f9322831f9

@ -1,6 +1,88 @@
console.log('import entrypoint lib')
const cos_60 = Math.cos(60 * Math.PI / 180)
const sin_60 = Math.sin(60 * Math.PI / 180)
const TileType = {
LAND : 0,
WATER : 1
}
class TileGrid {
constructor(width = 100, height = 100) {
this.width = 100
this.height = 100
this.tiles = new Array(this.width * this.height)
for (let y=0; y<this.height; y++) {
for (let x=0; x<this.width; x++) {
this.tiles[this.get_index(x, y)] = TileType.LAND
}
}
}
get_tile(x, y) {
return this.tiles[this.get_index(x, y)]
}
set_tile(x, y, type) {
this.tiles[this.get_index(x, y)] = type
}
get_index(x, y) {
return y * this.width + x
}
}
function draw_hex_tile(ctx, center, size, type) {
switch(type) {
case TileType.LAND:
ctx.fillStyle = 'green'
break
case TileType.WATER:
ctx.fillStyle = 'blue'
break
}
ctx.strokeStyle = 'black'
ctx.save()
ctx.translate(center[0], center[1])
ctx.scale(size[0], size[1])
ctx.beginPath()
ctx.moveTo(-1, 0)
ctx.lineTo(-cos_60, sin_60)
ctx.lineTo(cos_60, sin_60)
ctx.lineTo(1, 0)
ctx.lineTo(cos_60, -sin_60)
ctx.lineTo(-cos_60, -sin_60)
ctx.lineTo(-1, 0)
ctx.restore()
ctx.fill()
ctx.stroke()
}
function draw_map(ctx, scale, offset) {
const tile_grid = new TileGrid(100, 100)
tile_grid.set_tile(2, 2, TileType.WATER)
tile_grid.set_tile(50, 10, TileType.WATER)
const x_stride = 2 * cos_60 + 2
const y_stride = sin_60
for (let y=0; y<tile_grid.height; y++) {
for (let x=0; x<tile_grid.width; x++) {
let x_offset = 0
if (y % 2 === 0) {
x_offset = 1 + cos_60
}
draw_hex_tile(ctx, [(x * x_stride + x_offset) * scale + offset[0], y * y_stride * scale + offset[1]], [scale, scale], tile_grid.get_tile(x, y))
}
}
}
export function main(canvas) {
console.log('entrypoint function')
console.log(canvas)
if (canvas.getContext) {
const ctx = canvas.getContext('2d')
draw_map(ctx, 10, [50, 50])
}
}

Loading…
Cancel
Save