/* global requestAnimationFrame */ import { canvas, ctx } from './canvas' import { TileMap, World } from './tiles' import { HeightMap } from './heightmap' import Debug from './debug' import Input from './input' import Viewport from './viewport' import RES from './resource' let playing = false let frameTime = 0 let frameCount = 0 let fps = 0 let vp = new Viewport(0, 0) let height = new HeightMap(0, 32, 16, 0) let map = new TileMap('assets/ground.png', 32) const chunkSize = 32 const tileSize = 12 // Define dirt tiles map.define({ 'DIRT_CORNER_TOP_LEFT': 0, 'DIRT_TOP': 1, 'DIRT_CORNER_TOP_RIGHT': 2, 'DIRT_INNER_BOTTOM_RIGHT': 3, 'DIRT_INNER_BOTTOM_LEFT': 4, 'DIRT_LEFT': 32, 'DIRT': 33, 'DIRT_RIGHT': 34, 'DIRT_INNER_TOP_RIGHT': 35, 'DIRT_INNER_TOP_LEFT': 36, 'DIRT_CORNER_BOTTOM_LEFT': 64, 'DIRT_BOTTOM': 65, 'DIRT_CORNER_BOTTOM_RIGHT': 66 }) // Define grass tiles map.define({ 'GRASS_CORNER_TOP_LEFT': 5, 'GRASS_TOP': 6, 'GRASS_CORNER_TOP_RIGHT': 7, 'GRASS_INNER_BOTTOM_RIGHT': 8, 'GRASS_INNER_BOTTOM_LEFT': 9, 'GRASS_LEFT': 37, 'GRASS_MID': 38, 'GRASS_RIGHT': 39, 'GRASS_INNER_TOP_RIGHT': 40, 'GRASS_INNER_TOP_LEFT': 41, 'GRASS_CORNER_BOTTOM_LEFT': 69, 'GRASS_BOTTOM': 70, 'GRASS_CORNER_BOTTOM_RIGHT': 71 }) map.define({ 'AIR': -1, 'STONE': 10 }) let world = new World(height, { GROUND: map }, chunkSize, tileSize, 32, 64) function update (dt) { world.update(dt, vp) if (Input.isDown('w')) { vp.y -= 15 } else if (Input.isDown('s')) { vp.y += 15 } if (Input.isDown('a')) { vp.x -= 15 } else if (Input.isDown('d')) { vp.x += 15 } let full = world.chunkSize * world.tileSize if (vp.x < 0) { vp.x = 0 } else if (vp.x + vp.width > world.width * full) { vp.x = (full * world.width) - vp.width } if (vp.y < 0) { vp.y = 0 } else if (vp.y + vp.height > world.height * full) { vp.y = (full * world.height) - vp.height } } function draw () { world.draw(vp) Debug.draw(vp, world, fps) } function step () { draw() let ts = window.performance.now() let timeDiff = ts - frameTime // time difference in milliseconds frameCount++ if (timeDiff > 0) { fps = Math.floor(frameCount / timeDiff * 1000) frameCount = 0 frameTime = ts } update(timeDiff / 1000) } function gameLoop () { playing && requestAnimationFrame(gameLoop) ctx.fillStyle = '#111' ctx.fillRect(0, 0, canvas.width, canvas.height) step() Input.update() } function start () { Debug.createSliders(height, { amplitude: [0, 100, 1], persistence: [0.1, 5, 0.1], octaves: [1, 16, 1], period: [1, 100, 1], lacunarity: [1, 5, 1] }, function (key, val) { world.chunks = [] }) Debug.addCheckbox(Debug, 'drawGrid', function (argument) { world.chunks = [] }) playing = true gameLoop() } async function loadAll () { let images = ['assets/ground.png'] for (let i in images) { await RES.loadImage(images[i]) } } loadAll().then(start)