hook-miner/src/level.js

137 lines
2.7 KiB
JavaScript

import { ctx } from './canvas'
import { randomi } from './utils'
import RES from './resource'
const offset = 50
// Objects
export class GameObject {
constructor (x, y, w, h, img) {
this.x = x
this.y = y
this.w = w
this.h = h
this.img = img
this.physical = true
}
draw () {
if (!this.physical) return
if (this.img.indexOf('#') === 0) {
ctx.fillStyle = this.img
ctx.fillRect(ctx.oX + this.x, ctx.oY + this.y, this.w, this.h)
} else {
ctx.drawImage(RES.loadImage(this.img, true), ctx.oX + this.x, ctx.oY + this.y, this.w, this.h)
}
}
destroy () {
this.physical = false
}
get weight () {
return 0.1
}
}
export class Rock extends GameObject {
constructor (x, y, size) {
let o = size * 20
super(x, y, o, o, 'static/rock_' + size + '.png')
this.size = size
}
get weight () {
return Math.min(0.20 * this.size, 1)
}
}
export class Gold extends GameObject {
constructor (x, y, size) {
let o = size * 24
super(x, y, o, o, 'static/gold_' + size + '.png')
this.size = size
}
get weight () {
return Math.min(0.25 * this.size, 1)
}
}
export class Diamond extends GameObject {
constructor (x, y) {
super(x, y, 16, 16, 'static/diamond.png')
}
get weight () {
return 0.11
}
}
export class Lootbag extends GameObject {
constructor (x, y) {
super(x, y, 30, 30, 'static/loot.png')
}
get weight () {
return 0.56
}
}
// Level
export class Level {
constructor (id, objects) {
this.id = id
this.objects = objects || []
}
draw () {
for (let i in this.objects) {
this.objects[i].draw()
}
}
static create (index, my, width, height) {
let objects = []
let rocks = randomi(4, 12)
let gold = randomi(4, 12)
let diamond = randomi(0, 2)
let loot = randomi(0, 2)
// Add rocks
for (let r = 0; r < rocks; r++) {
let x = randomi(offset, width - offset)
let y = randomi(offset + my, height - (offset + my))
let size = randomi(1, 4)
objects.push(new Rock(x, y, size))
}
// Add gold
for (let r = 0; r < gold; r++) {
let x = randomi(offset, width - offset)
let y = randomi(offset + my, height - (offset + my))
let size = randomi(1, 4)
objects.push(new Gold(x, y, size))
}
// Add diamonds
for (let r = 0; r < diamond; r++) {
let x = randomi(offset, width - offset)
let y = randomi(offset + my, height - (offset + my))
objects.push(new Diamond(x, y))
}
// Add loot
for (let r = 0; r < loot; r++) {
let x = randomi(offset, width - offset)
let y = randomi(offset + my, height - (offset + my))
objects.push(new Lootbag(x, y))
}
let n = new Level(index, objects)
return n
}
}