dirty initial commit

This commit is contained in:
Zutatensuppe 2020-11-07 11:35:29 +01:00
commit 2351c93677
24 changed files with 2203 additions and 0 deletions

78
game/Bitmap.js Normal file
View file

@ -0,0 +1,78 @@
import BoundingRectangle from './BoundingRectangle.js'
export default class Bitmap {
constructor(width, height, rgba = null) {
this._w = width
this._h = height
this._com = 4 // number of components per pixel (RGBA)
this._boundingRect = new BoundingRectangle(0, this._w - 1, 0, this._h -1)
const len = this._w * this._h * this._com
this._data = new Uint8ClampedArray(len)
if (rgba) {
for (let i = 0; i < len; i+=4) {
this._data[i] = rgba[0]
this._data[i + 1] = rgba[1]
this._data[i + 2] = rgba[2]
this._data[i + 3] = rgba[3]
}
}
// public
this.width = this._w
this.height = this._h
}
toImage() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = this._w;
canvas.height = this._h;
const imgData = ctx.createImageData(canvas.width, canvas.height);
imgData.data.set(this._data);
ctx.putImageData(imgData, 0, 0);
return new Promise((resolve) => {
const img = document.createElement('img')
img.onload = () => {
resolve(img)
}
img.src = canvas.toDataURL()
return img
})
}
getPix(x, y, out) {
if (x < 0 || y < 0 || x >= this._w || y >= this._h) {
return false;
}
x = Math.round(x)
y = Math.round(y)
const idx = (y * 4 * this._w) + (x * 4)
out[0] = this._data[idx]
out[1] = this._data[idx + 1]
out[2] = this._data[idx + 2]
out[3] = this._data[idx + 3]
return true
}
putPix(x, y, rgba) {
if (x < 0 || y < 0 || x >= this._w || y >= this._h) {
return;
}
x = Math.round(x)
y = Math.round(y)
const idx = (y * this._com * this._w) + (x * this._com)
this._data[idx] = rgba[0]
this._data[idx + 1] = rgba[1]
this._data[idx + 2] = rgba[2]
this._data[idx + 3] = rgba[3]
}
getBoundingRect() {
return this._boundingRect
}
}

46
game/BoundingRectangle.js Normal file
View file

@ -0,0 +1,46 @@
import Point from './Point.js'
export default class BoundingRectangle {
constructor(x0, x1, y0, y1) {
this.x0 = x0
this.x1 = x1
this.y0 = y0
this.y1 = y1
this.width = (x1 - x0) + 1
this.height = (y1 - y0) + 1
}
div(d) {
this.x0 /= d
this.x1 /= d
this.y0 /= d
this.y1 /= d
}
move(x, y) {
this.x0 += x
this.x1 += x
this.y0 += y
this.y1 += y
}
moved(x, y) {
return new BoundingRectangle(
this.x0 + x,
this.x1 + x,
this.y0 + y,
this.y1 + y
)
}
center() {
return new Point(
this.x0 + this.width / 2,
this.y0 + this.height / 2,
)
}
centerDistance(other) {
return this.center().distance(other.center())
}
}

77
game/Camera.js Normal file
View file

@ -0,0 +1,77 @@
import BoundingRectangle from "./BoundingRectangle.js"
export default class Camera {
constructor(canvas) {
this.x = 0
this.y = 0
// TODO: when canvas resizes, this should
// syncronize with the cam
this.width = canvas.width
this.height = canvas.height
this.zoom = 1
this.minZoom = .2
this.maxZoom = 6
this.zoomStep = .05
}
rect() {
// when no zoom is relevant:
return new BoundingRectangle(
this.x,
this.x + this.width - 1,
this.y,
this.y + this.height - 1
)
// when zoom is relevant:
// TODO: check if still true
const w_final = this.width * this.zoom
const h_final = this.height * this.zoom
return new BoundingRectangle(
this.x + (this.width - w_final) / 2,
this.x + (this.width + w_final) / 2,
this.y + (this.height - h_final) / 2,
this.y + (this.height + h_final) / 2
)
}
move(x, y) {
this.x += x / this.zoom
this.y += y / this.zoom
}
zoomOut() {
const newzoom = Math.max(this.zoom - this.zoomStep, this.minZoom)
if (newzoom !== this.zoom) {
// centered zoom
this.x -= ((this.width / this.zoom) - (this.width / newzoom)) / 2
this.y -= ((this.height / this.zoom) - (this.height / newzoom)) / 2
this.zoom = newzoom
return true
}
return false
}
zoomIn() {
const newzoom = Math.min(this.zoom + this.zoomStep, this.maxZoom)
if (newzoom !== this.zoom) {
// centered zoom
this.x -= ((this.width / this.zoom) - (this.width / newzoom)) / 2
this.y -= ((this.height / this.zoom) - (this.height / newzoom)) / 2
this.zoom = newzoom
return true
}
return false
}
translateMouse(mouse) {
return {
x: (mouse.x / this.zoom) - this.x,
y: (mouse.y / this.zoom) - this.y,
}
}
}

58
game/CanvasAdapter.js Normal file
View file

@ -0,0 +1,58 @@
import BoundingRectangle from './BoundingRectangle.js'
export default class CanvasAdapter {
constructor(canvas) {
this._canvas = canvas
this._ctx = this._canvas.getContext('2d')
this._w = this._canvas.width
this._h = this._canvas.height
this._boundingRect = new BoundingRectangle(0, this._w - 1, 0, this._h - 1)
this._imageData = this._ctx.createImageData(this._w, this._h)
this._data = this._imageData.data
this.width = this._w
this.height = this._h
}
clear() {
this._imageData = this._ctx.createImageData(this._w, this._h)
this._data = this._imageData.data
this.apply()
}
getPix(x, y, out) {
if (x < 0 || y < 0 || x >= this._w || y >= this._h) {
return false;
}
x = Math.round(x)
y = Math.round(y)
const idx = (y * 4 * this._w) + (x * 4)
out[0] = this._data[idx]
out[1] = this._data[idx + 1]
out[2] = this._data[idx + 2]
out[3] = this._data[idx + 3]
return true
}
putPix(x, y, rgba) {
if (x < 0 || y < 0 || x >= this._w || y >= this._h) {
return null;
}
x = Math.round(x)
y = Math.round(y)
const idx = (y * 4 * this._w) + (x * 4)
this._data[idx] = rgba[0]
this._data[idx + 1] = rgba[1]
this._data[idx + 2] = rgba[2]
this._data[idx + 3] = rgba[3]
}
getBoundingRect() {
return this._boundingRect
}
apply() {
this._ctx.putImageData(this._imageData, 0, 0)
}
}

22
game/Color.js Normal file
View file

@ -0,0 +1,22 @@
export function tint(c, f) {
return [
Math.max(0, Math.min(255, Math.round((255 - c[0]) * f))),
Math.max(0, Math.min(255, Math.round((255 - c[1]) * f))),
Math.max(0, Math.min(255, Math.round((255 - c[2]) * f))),
c[3]
]
}
export function shade(c, f) {
return [
Math.max(0, Math.min(255, Math.round(c[0] * f))),
Math.max(0, Math.min(255, Math.round(c[1] * f))),
Math.max(0, Math.min(255, Math.round(c[2] * f))),
c[3]
]
}
export default {
tint,
shade
}

38
game/EventAdapter.js Normal file
View file

@ -0,0 +1,38 @@
export default class EventAdapter {
constructor(canvas) {
this._mouseEvts = []
canvas.addEventListener('mousedown', this._mouseDown.bind(this))
canvas.addEventListener('mouseup', this._mouseUp.bind(this))
canvas.addEventListener('mousemove', this._mouseMove.bind(this))
canvas.addEventListener('wheel', this._wheel.bind(this))
}
consumeAll() {
if (this._mouseEvts.length === 0) {
return []
}
const all = this._mouseEvts.slice()
this._mouseEvts = []
return all
}
_mouseDown(e) {
if (e.button === 0) {
this._mouseEvts.push({type: 'down', x: e.offsetX, y: e.offsetY})
}
}
_mouseUp(e) {
if (e.button === 0) {
this._mouseEvts.push({type: 'up', x: e.offsetX, y: e.offsetY})
}
}
_mouseMove(e) {
this._mouseEvts.push({type: 'move', x: e.offsetX, y: e.offsetY})
}
_wheel(e) {
this._mouseEvts.push({type: 'wheel', y: e.deltaY})
}
}

27
game/Point.js Normal file
View file

@ -0,0 +1,27 @@
export default class Point {
constructor(x,y) {
this.x = x
this.y = y
}
move(x, y) {
this.x += x
this.y += y
}
add(other) {
return new Point(
this.x + other.x,
this.y + other.y
)
}
sub(other) {
return new Point(
this.x - other.x,
this.y - other.y
)
}
distance(other) {
const diffX = this.x - other.x
const diffY = this.y - other.y
return Math.sqrt(diffX * diffX + diffY * diffY)
}
}

64
game/WsClient.js Normal file
View file

@ -0,0 +1,64 @@
import WsWrapper from './WsWrapper.js'
export default class WsClient extends WsWrapper {
constructor(addr, protocols) {
super(addr, protocols)
this._on = {}
this.onopen = (e) => {
this._dispatch('socket', 'open', e)
}
this.onmessage = (e) => {
this._dispatch('socket', 'message', e)
if (!!this._on['message']) {
const d = this._parseMessageData(e.data)
if (d.event) {
this._dispatch('message', d.event, d.data)
}
}
}
this.onclose = (e) => {
this._dispatch('socket', 'close', e)
}
}
onSocket(tag, callback) {
this.addEventListener('socket', tag, callback)
}
onMessage(tag, callback) {
this.addEventListener('message', tag, callback)
}
addEventListener(type, tag, callback) {
const tags = Array.isArray(tag) ? tag : [tag]
this._on[type] = this._on[type] || {}
for (const t of tags) {
this._on[type][t] = this._on[type][t] || []
this._on[type][t].push(callback)
}
}
_parseMessageData(data) {
try {
const d = JSON.parse(data)
if (d.event) {
return {event: d.event, data: d.data || null}
}
} catch {
}
return {event: null, data: null}
}
_dispatch(type, tag, ...args) {
const t = this._on[type] || {}
const callbacks = (t[tag] || [])
if (callbacks.length === 0) {
return
}
console.log(`ws dispatch ${type} ${tag}`)
for (const callback of callbacks) {
callback(...args)
}
}
}

55
game/WsWrapper.js Normal file
View file

@ -0,0 +1,55 @@
/**
* Wrapper around ws that
* - buffers 'send' until a connection is available
* - automatically tries to reconnect on close
*/
export default class WsWrapper {
// actual ws handle
handle = null
// timeout for automatic reconnect
reconnectTimeout = null
// buffer for 'send'
sendBuffer = []
constructor(addr, protocols) {
this.addr = addr
this.protocols = protocols
this.onopen = () => {}
this.onclose = () => {}
this.onmessage = () => {}
}
send (txt) {
if (this.handle) {
this.handle.send(txt)
} else {
this.sendBuffer.push(txt)
}
}
connect() {
let ws = new WebSocket(this.addr, this.protocols)
ws.onopen = (e) => {
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout)
}
this.handle = ws
// should have a queue worker
while (this.sendBuffer.length > 0) {
this.handle.send(this.sendBuffer.shift())
}
this.onopen(e)
}
ws.onmessage = (e) => {
this.onmessage(e)
}
ws.onclose = (e) => {
this.handle = null
this.reconnectTimeout = setTimeout(() => { this.connect() }, 1000)
this.onclose(e)
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 603 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 320 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 657 KiB

31
game/gameloop.js Normal file
View file

@ -0,0 +1,31 @@
export const run = options => {
const fps = options.fps || 60
const slow = options.slow || 1
const update = options.update
const render = options.render
const raf = window.requestAnimationFrame
const step = 1 / fps
const slowStep = slow * step
let now
let dt = 0
let last = window.performance.now()
const frame = () => {
now = window.performance.now()
dt = dt + Math.min(1, (now - last) / 1000) // duration capped at 1.0 seconds
while (dt > slowStep) {
dt = dt - slowStep
update(step)
}
render(dt / slow)
last = now
raf(frame)
}
raf(frame)
}
export default {
run
}

11
game/index.html Normal file
View file

@ -0,0 +1,11 @@
<html>
<head>
<style>
html,body {margin: 0; overflow: hidden;}
html, body, #main { background: #222 }
</style>
</head>
<body>
<script src="index.js" type="module"></script>
</body>
</html>

1073
game/index.js Normal file

File diff suppressed because it is too large Load diff

25
game/util.js Normal file
View file

@ -0,0 +1,25 @@
// get a random int between min and max (inclusive)
export const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
// get one random item from the given array
export const choice = (array) => array[randomInt(0, array.length - 1)]
// return a shuffled (shallow) copy of the given array
export const shuffle = (array) => {
let arr = array.slice()
for (let i = 0; i <= arr.length - 2; i++)
{
const j = randomInt(i, arr.length -1);
const tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
return arr
}
export default {
randomInt,
choice,
shuffle,
}