game stuff

This commit is contained in:
Zutatensuppe 2020-11-25 22:03:35 +01:00
parent 07da40dce7
commit e75cd7406f
20 changed files with 1527 additions and 387 deletions

View file

@ -9,7 +9,7 @@ export default class Camera {
this.height = canvas.height
this.zoom = 1
this.minZoom = .2
this.minZoom = .1
this.maxZoom = 6
this.zoomStep = .05
}
@ -44,11 +44,11 @@ export default class Camera {
}
zoomOut() {
return this.setZoom(this.zoom - this.zoomStep)
return this.setZoom(this.zoom - this.zoomStep * this.zoom)
}
zoomIn() {
return this.setZoom(this.zoom + this.zoomStep)
return this.setZoom(this.zoom + this.zoomStep * this.zoom)
}
/**

View file

@ -15,13 +15,13 @@ function send(message) {
let clientSeq
let events
function connect(gameId, clientId, name) {
function connect(gameId, clientId) {
clientSeq = 0
events = {}
conn = new WsClient(WS_ADDRESS, clientId + '|' + gameId)
return new Promise(r => {
conn.connect()
send([Protocol.EV_CLIENT_INIT, name])
send([Protocol.EV_CLIENT_INIT])
conn.onSocket('message', async ({ data }) => {
const msg = JSON.parse(data)
const msgType = msg[0]

View file

@ -1,7 +1,7 @@
function createCanvas(width = 0, height = 0) {
const c = document.createElement('canvas')
c.width = width === 0 ? window.innerWidth : width
c.height = height === 0 ? window.innerHeight : height
c.width = width
c.height = height
return c
}
@ -29,9 +29,26 @@ async function createBitmap(width, height, color) {
return await createImageBitmap(c)
}
async function colorize(image, mask, color) {
const c = createCanvas(image.width, image.height)
const ctx = c.getContext('2d')
ctx.save()
ctx.drawImage(mask, 0, 0)
ctx.fillStyle = color
ctx.globalCompositeOperation = "source-in"
ctx.fillRect(0, 0, mask.width, mask.height)
ctx.restore()
ctx.save()
ctx.globalCompositeOperation = "destination-over"
ctx.drawImage(image, 0, 0)
ctx.restore()
return await createImageBitmap(c)
}
export default {
createBitmap,
createCanvas,
loadImageToBitmap,
resizeBitmap,
colorize,
}

View file

@ -27,33 +27,50 @@ async function createPuzzleTileBitmaps(img, tiles, info) {
const path = new Path2D()
const topLeftEdge = { x: tileMarginWidth, y: tileMarginWidth }
path.moveTo(topLeftEdge.x, topLeftEdge.y)
for (let i = 0; i < curvyCoords.length / 6; i++) {
const p1 = Geometry.pointAdd(topLeftEdge, { x: curvyCoords[i * 6 + 0] * tileRatio, y: shape.top * curvyCoords[i * 6 + 1] * tileRatio })
const p2 = Geometry.pointAdd(topLeftEdge, { x: curvyCoords[i * 6 + 2] * tileRatio, y: shape.top * curvyCoords[i * 6 + 3] * tileRatio })
const p3 = Geometry.pointAdd(topLeftEdge, { x: curvyCoords[i * 6 + 4] * tileRatio, y: shape.top * curvyCoords[i * 6 + 5] * tileRatio })
path.bezierCurveTo(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
}
const topRightEdge = Geometry.pointAdd(topLeftEdge, { x: tileSize, y: 0 })
for (let i = 0; i < curvyCoords.length / 6; i++) {
const p1 = Geometry.pointAdd(topRightEdge, { x: -shape.right * curvyCoords[i * 6 + 1] * tileRatio, y: curvyCoords[i * 6 + 0] * tileRatio })
const p2 = Geometry.pointAdd(topRightEdge, { x: -shape.right * curvyCoords[i * 6 + 3] * tileRatio, y: curvyCoords[i * 6 + 2] * tileRatio })
const p3 = Geometry.pointAdd(topRightEdge, { x: -shape.right * curvyCoords[i * 6 + 5] * tileRatio, y: curvyCoords[i * 6 + 4] * tileRatio })
path.bezierCurveTo(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
}
const bottomRightEdge = Geometry.pointAdd(topRightEdge, { x: 0, y: tileSize })
for (let i = 0; i < curvyCoords.length / 6; i++) {
let p1 = Geometry.pointSub(bottomRightEdge, { x: curvyCoords[i * 6 + 0] * tileRatio, y: shape.bottom * curvyCoords[i * 6 + 1] * tileRatio })
let p2 = Geometry.pointSub(bottomRightEdge, { x: curvyCoords[i * 6 + 2] * tileRatio, y: shape.bottom * curvyCoords[i * 6 + 3] * tileRatio })
let p3 = Geometry.pointSub(bottomRightEdge, { x: curvyCoords[i * 6 + 4] * tileRatio, y: shape.bottom * curvyCoords[i * 6 + 5] * tileRatio })
path.bezierCurveTo(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
}
const bottomLeftEdge = Geometry.pointSub(bottomRightEdge, { x: tileSize, y: 0 })
for (let i = 0; i < curvyCoords.length / 6; i++) {
let p1 = Geometry.pointSub(bottomLeftEdge, { x: -shape.left * curvyCoords[i * 6 + 1] * tileRatio, y: curvyCoords[i * 6 + 0] * tileRatio })
let p2 = Geometry.pointSub(bottomLeftEdge, { x: -shape.left * curvyCoords[i * 6 + 3] * tileRatio, y: curvyCoords[i * 6 + 2] * tileRatio })
let p3 = Geometry.pointSub(bottomLeftEdge, { x: -shape.left * curvyCoords[i * 6 + 5] * tileRatio, y: curvyCoords[i * 6 + 4] * tileRatio })
path.bezierCurveTo(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
path.moveTo(topLeftEdge.x, topLeftEdge.y)
if (shape.top !== 0) {
for (let i = 0; i < curvyCoords.length / 6; i++) {
const p1 = Geometry.pointAdd(topLeftEdge, { x: curvyCoords[i * 6 + 0] * tileRatio, y: shape.top * curvyCoords[i * 6 + 1] * tileRatio })
const p2 = Geometry.pointAdd(topLeftEdge, { x: curvyCoords[i * 6 + 2] * tileRatio, y: shape.top * curvyCoords[i * 6 + 3] * tileRatio })
const p3 = Geometry.pointAdd(topLeftEdge, { x: curvyCoords[i * 6 + 4] * tileRatio, y: shape.top * curvyCoords[i * 6 + 5] * tileRatio })
path.bezierCurveTo(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
}
} else {
path.lineTo(topRightEdge.x, topRightEdge.y)
}
if (shape.right !== 0) {
for (let i = 0; i < curvyCoords.length / 6; i++) {
const p1 = Geometry.pointAdd(topRightEdge, { x: -shape.right * curvyCoords[i * 6 + 1] * tileRatio, y: curvyCoords[i * 6 + 0] * tileRatio })
const p2 = Geometry.pointAdd(topRightEdge, { x: -shape.right * curvyCoords[i * 6 + 3] * tileRatio, y: curvyCoords[i * 6 + 2] * tileRatio })
const p3 = Geometry.pointAdd(topRightEdge, { x: -shape.right * curvyCoords[i * 6 + 5] * tileRatio, y: curvyCoords[i * 6 + 4] * tileRatio })
path.bezierCurveTo(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
}
} else {
path.lineTo(bottomRightEdge.x, bottomRightEdge.y)
}
if (shape.bottom !== 0) {
for (let i = 0; i < curvyCoords.length / 6; i++) {
let p1 = Geometry.pointSub(bottomRightEdge, { x: curvyCoords[i * 6 + 0] * tileRatio, y: shape.bottom * curvyCoords[i * 6 + 1] * tileRatio })
let p2 = Geometry.pointSub(bottomRightEdge, { x: curvyCoords[i * 6 + 2] * tileRatio, y: shape.bottom * curvyCoords[i * 6 + 3] * tileRatio })
let p3 = Geometry.pointSub(bottomRightEdge, { x: curvyCoords[i * 6 + 4] * tileRatio, y: shape.bottom * curvyCoords[i * 6 + 5] * tileRatio })
path.bezierCurveTo(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
}
} else {
path.lineTo(bottomLeftEdge.x, bottomLeftEdge.y)
}
if (shape.left !== 0) {
for (let i = 0; i < curvyCoords.length / 6; i++) {
let p1 = Geometry.pointSub(bottomLeftEdge, { x: -shape.left * curvyCoords[i * 6 + 1] * tileRatio, y: curvyCoords[i * 6 + 0] * tileRatio })
let p2 = Geometry.pointSub(bottomLeftEdge, { x: -shape.left * curvyCoords[i * 6 + 3] * tileRatio, y: curvyCoords[i * 6 + 2] * tileRatio })
let p3 = Geometry.pointSub(bottomLeftEdge, { x: -shape.left * curvyCoords[i * 6 + 5] * tileRatio, y: curvyCoords[i * 6 + 4] * tileRatio })
path.bezierCurveTo(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
}
} else {
path.lineTo(topLeftEdge.x, topLeftEdge.y)
}
paths[key] = path
return path
@ -65,13 +82,37 @@ async function createPuzzleTileBitmaps(img, tiles, info) {
const c = Graphics.createCanvas(tileDrawSize, tileDrawSize)
const ctx = c.getContext('2d')
// stroke (slightly darker version of image)
// -----------------------------------------------------------
// -----------------------------------------------------------
ctx.save()
ctx.lineWidth = 2
ctx.stroke(path)
ctx.globalCompositeOperation = 'source-in'
ctx.drawImage(
img,
srcRect.x - tileMarginWidth,
srcRect.y - tileMarginWidth,
tileDrawSize,
tileDrawSize,
0,
0,
tileDrawSize,
tileDrawSize,
)
ctx.restore()
ctx.save()
ctx.globalCompositeOperation = 'source-in'
ctx.globalAlpha = .2
ctx.fillStyle = 'black'
ctx.fillRect(0,0, c.width, c.height)
ctx.restore()
// main image
// -----------------------------------------------------------
// -----------------------------------------------------------
ctx.save();
ctx.save()
ctx.clip(path)
ctx.drawImage(
img,
@ -84,8 +125,65 @@ async function createPuzzleTileBitmaps(img, tiles, info) {
tileDrawSize,
tileDrawSize,
)
ctx.restore()
// INSET SHADOW (bottom, right)
// -----------------------------------------------------------
// -----------------------------------------------------------
ctx.save()
ctx.clip(path)
ctx.strokeStyle = 'rgba(0,0,0,.4)'
ctx.lineWidth = 0
ctx.shadowColor = "black";
ctx.shadowBlur = 2;
ctx.shadowOffsetX = -1;
ctx.shadowOffsetY = -1;
ctx.stroke(path)
ctx.restore();
ctx.restore()
// INSET SHADOW (top, left)
// -----------------------------------------------------------
// -----------------------------------------------------------
ctx.save()
ctx.clip(path)
ctx.strokeStyle = 'rgba(255,255,255,.4)'
ctx.lineWidth = 0
ctx.shadowColor = "white";
ctx.shadowBlur = 2;
ctx.shadowOffsetX = 1;
ctx.shadowOffsetY = 1;
ctx.stroke(path)
ctx.restore()
// -----------------------------------------------------------
// -----------------------------------------------------------
const tmpc = Graphics.createCanvas(tileDrawSize, tileDrawSize)
const ctx2 = tmpc.getContext('2d')
ctx2.save()
ctx2.lineWidth = 1
ctx2.stroke(path)
ctx2.globalCompositeOperation = 'source-in'
ctx2.drawImage(
img,
srcRect.x - tileMarginWidth - 50,
srcRect.y - tileMarginWidth - 50,
tileDrawSize + 100,
tileDrawSize + 100,
0 - 50,
0 - 50,
tileDrawSize + 100,
tileDrawSize + 100,
)
ctx2.restore()
// ctx2.save()
// ctx2.globalCompositeOperation = 'source-in'
// ctx2.globalAlpha = .1
// ctx2.fillStyle = 'black'
// ctx2.fillRect(0,0, c.width, c.height)
// ctx2.restore()
// ctx.globalCompositeOperation = 'darken'
ctx.drawImage(tmpc, 0, 0)
bitmaps[tile.idx] = await createImageBitmap(c)
}

503
game/game.js Normal file
View file

@ -0,0 +1,503 @@
"use strict"
import {run} from './gameloop.js'
import Camera from './Camera.js'
import Graphics from './Graphics.js'
import Debug from './Debug.js'
import Communication from './Communication.js'
import Util from './../common/Util.js'
import PuzzleGraphics from './PuzzleGraphics.js'
import Game from './Game.js'
if (typeof GAME_ID === 'undefined') throw '[ GAME_ID not set ]'
if (typeof WS_ADDRESS === 'undefined') throw '[ WS_ADDRESS not set ]'
if (typeof DEBUG === 'undefined') window.DEBUG = false
let RERENDER = true
function addCanvasToDom(canvas) {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
document.body.appendChild(canvas)
window.addEventListener('resize', () => {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
RERENDER = true
})
return canvas
}
function getActivePlayers(players) {
const ts = Util.timestamp()
const activePlayers = []
for (let id of Object.keys(players)) {
const player = players[id]
if (player.ts >= ts - 30000) {
activePlayers.push(player)
}
}
return activePlayers
}
function addMenuToDom(previewImageUrl) {
function row (...elements) {
const row = document.createElement('tr')
for (let el of elements) {
const td = document.createElement('td')
td.appendChild(el)
row.appendChild(td)
}
return row
}
function colorinput() {
const input = document.createElement('input')
input.type = 'color'
return input
}
function textinput(maxLength) {
const input = document.createElement('input')
input.type = 'text'
input.maxLength = maxLength
return input
}
function label(text) {
const label = document.createElement('label')
label.innerText = text
return label
}
const bgColorPickerEl = colorinput()
const bgColorPickerRow = row(
label('Background: '),
bgColorPickerEl
)
const playerColorPickerEl = colorinput()
const playerColorPickerRow = row(
label('Color: '),
playerColorPickerEl
)
const nameChangeEl = textinput(16)
const nameChangeRow = row(
label('Name: '),
nameChangeEl
)
const settingsEl = document.createElement('table')
settingsEl.classList.add('layer', 'settings', 'closed')
settingsEl.appendChild(bgColorPickerRow)
settingsEl.appendChild(playerColorPickerRow)
settingsEl.appendChild(nameChangeRow)
const previewEl = document.createElement('div')
previewEl.classList.add('preview')
const imgEl = document.createElement('div')
imgEl.classList.add('img')
imgEl.style.backgroundImage = `url(${previewImageUrl})`
previewEl.appendChild(imgEl)
const previewOverlay = document.createElement('div')
previewOverlay.classList.add('overlay', 'closed')
previewOverlay.appendChild(previewEl)
previewOverlay.addEventListener('click', () => {
previewOverlay.classList.toggle('closed')
})
const settingsOpenerEl = document.createElement('div')
settingsOpenerEl.classList.add('opener')
settingsOpenerEl.appendChild(document.createTextNode('🛠️ Settings'))
settingsOpenerEl.addEventListener('click', () => {
settingsEl.classList.toggle('closed')
})
const homeEl = document.createElement('a')
homeEl.classList.add('opener')
homeEl.appendChild(document.createTextNode('🧩 Puzzles'))
homeEl.href = "/"
const previewOpenerEl = document.createElement('div')
previewOpenerEl.classList.add('opener')
previewOpenerEl.appendChild(document.createTextNode('🖼️ Preview'))
previewOpenerEl.addEventListener('click', () => {
previewOverlay.classList.toggle('closed')
})
const tabsEl = document.createElement('div')
tabsEl.classList.add('tabs')
tabsEl.appendChild(homeEl)
tabsEl.appendChild(previewOpenerEl)
tabsEl.appendChild(settingsOpenerEl)
const menuEl = document.createElement('div')
menuEl.classList.add('menu')
menuEl.appendChild(tabsEl)
const scoresTitleEl = document.createElement('div')
scoresTitleEl.appendChild(document.createTextNode('Scores'))
const scoresListEl = document.createElement('table')
const updateScores = (players) => {
const activePlayers = getActivePlayers(players)
const scores = activePlayers.map(p => ({
name: p.name,
points: p.points,
color: p.color,
}))
scores.sort((a, b) => b.points - a.points)
scoresListEl.innerHTML = ''
for (let score of scores) {
const r = row(
document.createTextNode(score.name),
document.createTextNode(score.points)
)
r.style.color = score.color
scoresListEl.appendChild(r)
}
}
const scoresEl = document.createElement('div')
scoresEl.classList.add('scores')
scoresEl.appendChild(scoresTitleEl)
scoresEl.appendChild(scoresListEl)
document.body.appendChild(settingsEl)
document.body.appendChild(previewOverlay)
document.body.appendChild(menuEl)
document.body.appendChild(scoresEl)
return {
bgColorPickerEl,
playerColorPickerEl,
nameChangeEl,
updateScores,
}
}
function initme() {
// return uniqId()
let ID = localStorage.getItem('ID')
if (!ID) {
ID = Util.uniqId()
localStorage.setItem('ID', ID)
}
return ID
}
const getFirstOwnedTile = (puzzle, userId) => {
for (let t of puzzle.tiles) {
if (t.owner === userId) {
return t
}
}
return null
}
export default class EventAdapter {
constructor(canvas, viewport) {
this.events = []
this._viewport = viewport
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))
}
addEvent(event) {
this.events.push(event)
}
consumeAll() {
if (this.events.length === 0) {
return []
}
const all = this.events.slice()
this.events = []
return all
}
_mouseDown(e) {
if (e.button === 0) {
const pos = this._viewport.viewportToWorld({
x: e.offsetX,
y: e.offsetY,
})
this.addEvent(['down', pos.x, pos.y])
}
}
_mouseUp(e) {
if (e.button === 0) {
const pos = this._viewport.viewportToWorld({
x: e.offsetX,
y: e.offsetY,
})
this.addEvent(['up', pos.x, pos.y])
}
}
_mouseMove(e) {
const pos = this._viewport.viewportToWorld({
x: e.offsetX,
y: e.offsetY,
})
this.addEvent(['move', pos.x, pos.y])
}
_wheel(e) {
const pos = this._viewport.viewportToWorld({
x: e.offsetX,
y: e.offsetY,
})
const evt = e.deltaY < 0 ? 'zoomin' : 'zoomout'
this.addEvent([evt, pos.x, pos.y])
}
}
async function main() {
let gameId = GAME_ID
let CLIENT_ID = initme()
const cursorGrab = await Graphics.loadImageToBitmap('/grab.png')
const cursorHand = await Graphics.loadImageToBitmap('/hand.png')
const cursorGrabMask = await Graphics.loadImageToBitmap('/grab_mask.png')
const cursorHandMask = await Graphics.loadImageToBitmap('/hand_mask.png')
const cursors = {}
const getPlayerCursor = async (p) => {
let key = p.color + ' ' + p.d
if (!cursors[key]) {
const cursor = p.d ? cursorGrab : cursorHand
const mask = p.d ? cursorGrabMask : cursorHandMask
cursors[key] = await Graphics.colorize(cursor, mask, p.color)
}
return cursors[key]
}
const game = await Communication.connect(gameId, CLIENT_ID)
Game.createGame(GAME_ID, game);
const bitmaps = await PuzzleGraphics.loadPuzzleBitmaps(game.puzzle)
const puzzle = game.puzzle
const players = game.players
let bgColor = '#222222'
const changePlayer = (change) => {
for (let k of Object.keys(change)) {
players[CLIENT_ID][k] = change[k]
}
}
const {bgColorPickerEl, playerColorPickerEl, nameChangeEl, updateScores} = addMenuToDom(game.puzzle.info.imageUrl)
updateScores(players)
// Create a dom and attach adapters to it so we can work with it
const canvas = addCanvasToDom(Graphics.createCanvas())
const ctx = canvas.getContext('2d')
// initialize some view data
// this global data will change according to input events
const viewport = new Camera(canvas)
// center viewport
viewport.move(
-(puzzle.info.table.width - viewport.width) /2,
-(puzzle.info.table.height - viewport.height) /2
)
const evts = new EventAdapter(canvas, viewport)
bgColorPickerEl.value = bgColor
bgColorPickerEl.addEventListener('change', () => {
evts.addEvent(['bg_color', bgColorPickerEl.value])
})
playerColorPickerEl.value = players[CLIENT_ID].color
playerColorPickerEl.addEventListener('change', () => {
evts.addEvent(['player_color', playerColorPickerEl.value])
})
nameChangeEl.value = players[CLIENT_ID].name
nameChangeEl.addEventListener('change', () => {
evts.addEvent(['player_name', nameChangeEl.value])
})
Communication.onServerChange((msg) => {
const msgType = msg[0]
const evClientId = msg[1]
const evClientSeq = msg[2]
const evChanges = msg[3]
for(let [changeType, changeData] of evChanges) {
switch (changeType) {
case 'player': {
if (changeData.id !== CLIENT_ID) {
players[changeData.id] = changeData
RERENDER = true
}
} break;
case 'tile': {
puzzle.tiles[changeData.idx] = changeData
RERENDER = true
} break;
case 'data': {
puzzle.data = changeData
RERENDER = true
} break;
}
}
})
const tilesSortedByZIndex = () => {
const sorted = puzzle.tiles.slice()
return sorted.sort((t1, t2) => t1.z - t2.z)
}
let _last_mouse_down = null
const onUpdate = () => {
for (let evt of evts.consumeAll()) {
// LOCAL ONLY CHANGES
// -------------------------------------------------------------
const type = evt[0]
if (type === 'bg_color') {
const color = evt[1]
bgColor = color
RERENDER = true
} else if (type === 'move') {
const pos = { x: evt[1], y: evt[2] }
RERENDER = true
changePlayer(pos)
if (_last_mouse_down && !getFirstOwnedTile(puzzle, CLIENT_ID)) {
// move the cam
const mouse = viewport.worldToViewport(pos)
const diffX = Math.round(mouse.x - _last_mouse_down.x)
const diffY = Math.round(mouse.y - _last_mouse_down.y)
viewport.move(diffX, diffY)
_last_mouse_down = mouse
}
} else if (type === 'down') {
const pos = { x: evt[1], y: evt[2] }
_last_mouse_down = viewport.worldToViewport(pos)
} else if (type === 'up') {
_last_mouse_down = null
} else if (type === 'zoomin') {
if (viewport.zoomIn()) {
const pos = { x: evt[1], y: evt[2] }
RERENDER = true
changePlayer(pos)
}
} else if (type === 'zoomout') {
if (viewport.zoomOut()) {
const pos = { x: evt[1], y: evt[2] }
RERENDER = true
changePlayer(pos)
}
}
// LOCAL + SERVER CHANGES
// -------------------------------------------------------------
const changes = Game.handleInput(GAME_ID, CLIENT_ID, evt)
if (changes.length > 0) {
RERENDER = true
}
Communication.sendClientEvent(evt)
}
}
const onRender = async () => {
if (!RERENDER) {
return
}
let pos
let dim
if (DEBUG) Debug.checkpoint_start(0)
// CLEAR CTX
// ---------------------------------------------------------------
ctx.fillStyle = bgColor
ctx.fillRect(0, 0, canvas.width, canvas.height)
if (DEBUG) Debug.checkpoint('clear done')
// ---------------------------------------------------------------
// DRAW BOARD
// ---------------------------------------------------------------
pos = viewport.worldToViewport({
x: (puzzle.info.table.width - puzzle.info.width) / 2,
y: (puzzle.info.table.height - puzzle.info.height) / 2
})
dim = viewport.worldDimToViewport({
w: puzzle.info.width,
h: puzzle.info.height,
})
ctx.fillStyle = 'rgba(255, 255, 255, .5)'
ctx.fillRect(pos.x, pos.y, dim.w, dim.h)
if (DEBUG) Debug.checkpoint('board done')
// ---------------------------------------------------------------
// DRAW TILES
// ---------------------------------------------------------------
for (let tile of tilesSortedByZIndex()) {
const bmp = bitmaps[tile.idx]
pos = viewport.worldToViewport({
x: puzzle.info.tileDrawOffset + tile.pos.x,
y: puzzle.info.tileDrawOffset + tile.pos.y,
})
dim = viewport.worldDimToViewport({
w: puzzle.info.tileDrawSize,
h: puzzle.info.tileDrawSize,
})
ctx.drawImage(bmp,
0, 0, bmp.width, bmp.height,
pos.x, pos.y, dim.w, dim.h
)
}
if (DEBUG) Debug.checkpoint('tiles done')
// ---------------------------------------------------------------
// DRAW PLAYERS
// ---------------------------------------------------------------
for (let p of getActivePlayers(players)) {
const cursor = await getPlayerCursor(p)
const pos = viewport.worldToViewport(p)
ctx.drawImage(cursor,
Math.round(pos.x - cursor.width/2),
Math.round(pos.y - cursor.height/2)
)
if (p.id !== CLIENT_ID) {
ctx.fillStyle = 'white'
ctx.font = '10px sans-serif'
ctx.textAlign = 'center'
ctx.fillText(p.name + ' (' + p.points + ')',
Math.round(pos.x),
Math.round(pos.y) + cursor.height
)
}
}
if (DEBUG) Debug.checkpoint('players done')
// DRAW PLAYERS
// ---------------------------------------------------------------
updateScores(players)
if (DEBUG) Debug.checkpoint('scores done')
// ---------------------------------------------------------------
RERENDER = false
}
run({
update: onUpdate,
render: onRender,
})
}
main()

BIN
game/grab_mask.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 B

BIN
game/hand_mask.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 B

View file

@ -1,307 +1,98 @@
"use strict"
import {run} from './gameloop.js'
import Camera from './Camera.js'
import Graphics from './Graphics.js'
import Debug from './Debug.js'
import Communication from './Communication.js'
import Util from './../common/Util.js'
import PuzzleGraphics from './PuzzleGraphics.js'
import Game from './Game.js'
if (typeof GAME_ID === 'undefined') throw '[ GAME_ID not set ]'
if (typeof WS_ADDRESS === 'undefined') throw '[ WS_ADDRESS not set ]'
if (typeof DEBUG === 'undefined') window.DEBUG = false
function addCanvasToDom(canvas) {
document.body.append(canvas)
return canvas
}
function initme() {
// return uniqId()
let ID = localStorage.getItem('ID')
if (!ID) {
ID = Util.uniqId()
localStorage.setItem('ID', ID)
}
let name = localStorage.getItem('NAME')
if (!name) {
name = prompt('What\'s your name?');
localStorage.setItem('NAME', name)
}
return [ID, name]
}
const getFirstOwnedTile = (puzzle, userId) => {
for (let t of puzzle.tiles) {
if (t.owner === userId) {
return t
}
}
return null
}
export default class EventAdapter {
constructor(canvas, viewport) {
this._mouseEvts = []
this._viewport = viewport
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) {
const pos = this._viewport.viewportToWorld({
x: e.offsetX,
y: e.offsetY,
const Upload = {
name: 'upload',
props: {
accept: String,
label: String,
},
template: `
<label>
<input type="file" style="display: none" @change="upload" :accept="accept" />
<span class="btn">{{label || 'Upload File'}}</span>
</label>
`,
methods: {
async upload(evt) {
const file = evt.target.files[0]
if (!file) return;
const formData = new FormData();
formData.append('file', file, file.name);
const res = await fetch('/upload', {
method: 'post',
body: formData,
})
this._mouseEvts.push(['down', pos.x, pos.y])
}
}
_mouseUp(e) {
if (e.button === 0) {
const pos = this._viewport.viewportToWorld({
x: e.offsetX,
y: e.offsetY,
})
this._mouseEvts.push(['up', pos.x, pos.y])
}
}
_mouseMove(e) {
const pos = this._viewport.viewportToWorld({
x: e.offsetX,
y: e.offsetY,
})
this._mouseEvts.push(['move', pos.x, pos.y])
}
_wheel(e) {
const pos = this._viewport.viewportToWorld({
x: e.offsetX,
y: e.offsetY,
})
const evt = e.deltaY < 0 ? 'zoomin' : 'zoomout'
this._mouseEvts.push([evt, pos.x, pos.y])
const j = await res.json()
this.$emit('uploaded', j)
},
}
}
async function main() {
let gameId = GAME_ID
let [CLIENT_ID, name] = initme()
export default {
components: {
Upload,
},
props: {
games: Array,
images: Array,
},
template: `
<div id="app">
<h1>Running games</h1>
<div v-for="g in games">
<a :href="'/g/' + g.id">{{g.title}}</a>
</div>
let cursorGrab = await Graphics.loadImageToBitmap('/grab.png')
let cursorHand = await Graphics.loadImageToBitmap('/hand.png')
<h1>New game</h1>
<div>
<label>Tiles: </label>
<input type="text" v-model="tiles" />
</div>
<div>
<label>Image: </label>
<span v-if="image">
<img :src="image.url" style="width: 150px;" />
or
<upload @uploaded="mediaImgUploaded($event)" accept="image/*" label="Upload an image" />
</span>
<span v-else>
<upload @uploaded="mediaImgUploaded($event)" accept="image/*" label="Upload an image" />
(or select from below)
</span>
</div>
<span class="btn" :class="" @click="newGame">Start new game</span>
const game = await Communication.connect(gameId, CLIENT_ID, name)
Game.createGame(GAME_ID, game);
const bitmaps = await PuzzleGraphics.loadPuzzleBitmaps(game.puzzle)
const puzzle = game.puzzle
const players = game.players
let rerender = true
const changePlayer = (change) => {
for (let k of Object.keys(change)) {
players[CLIENT_ID][k] = change[k]
<h1>Image lib</h1>
<div>
<img
v-for="i in images"
:src="i.url"
@click="image = i"
style="width: 150px; display: inline-block; margin: 5px;"
/>
</div>
</div>`,
data() {
return {
tiles: 1000,
image: '',
}
}
// Create a dom and attach adapters to it so we can work with it
const canvas = addCanvasToDom(Graphics.createCanvas())
const ctx = canvas.getContext('2d')
// initialize some view data
// this global data will change according to input events
const viewport = new Camera(canvas)
// center viewport
viewport.move(
-(puzzle.info.table.width - viewport.width) /2,
-(puzzle.info.table.height - viewport.height) /2
)
const evts = new EventAdapter(canvas, viewport)
Communication.onServerChange((msg) => {
const msgType = msg[0]
const evClientId = msg[1]
const evClientSeq = msg[2]
const evChanges = msg[3]
for(let [changeType, changeData] of evChanges) {
switch (changeType) {
case 'player': {
if (changeData.id !== CLIENT_ID) {
players[changeData.id] = changeData
rerender = true
}
} break;
case 'tile': {
puzzle.tiles[changeData.idx] = changeData
rerender = true
} break;
case 'data': {
puzzle.data = changeData
rerender = true
} break;
},
methods: {
mediaImgUploaded(j) {
this.image = j.image
},
async newGame() {
const res = await fetch('/newgame', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({tiles: this.tiles, image: this.image}),
})
if (res.status === 200) {
const game = await res.json()
location.assign(game.url)
}
}
})
// In the middle of the table, there is a board. this is to
// tell the player where to place the final puzzle
const boardColor = '#505050'
const tilesSortedByZIndex = () => {
const sorted = puzzle.tiles.slice()
return sorted.sort((t1, t2) => t1.z - t2.z)
}
let _last_mouse_down = null
const onUpdate = () => {
for (let evt of evts.consumeAll()) {
// LOCAL ONLY CHANGES
// -------------------------------------------------------------
const type = evt[0]
const pos = {x: evt[1], y: evt[2]}
if (type === 'move') {
rerender = true
changePlayer(pos)
if (_last_mouse_down && !getFirstOwnedTile(puzzle, CLIENT_ID)) {
// move the cam
const mouse = viewport.worldToViewport(pos)
const diffX = Math.round(mouse.x - _last_mouse_down.x)
const diffY = Math.round(mouse.y - _last_mouse_down.y)
viewport.move(diffX, diffY)
_last_mouse_down = mouse
}
} else if (type === 'down') {
_last_mouse_down = viewport.worldToViewport(pos)
} else if (type === 'up') {
_last_mouse_down = null
} else if (type === 'zoomin') {
if (viewport.zoomIn()) {
rerender = true
changePlayer(pos)
}
} else if (type === 'zoomout') {
if (viewport.zoomOut()) {
rerender = true
changePlayer(pos)
}
}
// LOCAL + SERVER CHANGES
// -------------------------------------------------------------
const changes = Game.handleInput(GAME_ID, CLIENT_ID, evt)
if (changes.length > 0) {
rerender = true
}
Communication.sendClientEvent(evt)
}
}
const onRender = () => {
if (!rerender) {
return
}
let pos
let dim
if (DEBUG) Debug.checkpoint_start(0)
// CLEAR CTX
// ---------------------------------------------------------------
ctx.clearRect(0, 0, canvas.width, canvas.height)
if (DEBUG) Debug.checkpoint('clear done')
// ---------------------------------------------------------------
// DRAW BOARD
// ---------------------------------------------------------------
pos = viewport.worldToViewport({
x: (puzzle.info.table.width - puzzle.info.width) / 2,
y: (puzzle.info.table.height - puzzle.info.height) / 2
})
dim = viewport.worldDimToViewport({
w: puzzle.info.width,
h: puzzle.info.height,
})
ctx.fillStyle = boardColor
ctx.fillRect(pos.x, pos.y, dim.w, dim.h)
if (DEBUG) Debug.checkpoint('board done')
// ---------------------------------------------------------------
// DRAW TILES
// ---------------------------------------------------------------
for (let tile of tilesSortedByZIndex()) {
const bmp = bitmaps[tile.idx]
pos = viewport.worldToViewport({
x: puzzle.info.tileDrawOffset + tile.pos.x,
y: puzzle.info.tileDrawOffset + tile.pos.y,
})
dim = viewport.worldDimToViewport({
w: puzzle.info.tileDrawSize,
h: puzzle.info.tileDrawSize,
})
ctx.drawImage(bmp,
0, 0, bmp.width, bmp.height,
pos.x, pos.y, dim.w, dim.h
)
}
if (DEBUG) Debug.checkpoint('tiles done')
// ---------------------------------------------------------------
// DRAW PLAYERS
// ---------------------------------------------------------------
for (let id of Object.keys(players)) {
const p = players[id]
const cursor = p.down ? cursorGrab : cursorHand
const pos = viewport.worldToViewport(p)
ctx.drawImage(cursor,
Math.round(pos.x - cursor.width/2),
Math.round(pos.y - cursor.height/2)
)
if (id !== CLIENT_ID) {
ctx.fillStyle = 'white'
ctx.font = '10px sans-serif'
ctx.textAlign = 'center'
ctx.fillText(p.name,
Math.round(pos.x),
Math.round(pos.y) + cursor.height
)
}
}
if (DEBUG) Debug.checkpoint('players done')
// ---------------------------------------------------------------
rerender = false
}
run({
update: onUpdate,
render: onRender,
})
}
main()

145
game/style.css Normal file
View file

@ -0,0 +1,145 @@
:root {
--main-color: #c1b19f;
--link-color: #808db0;
--link-hover-color: #c5cfeb;
--highlight-color: #dd7e7e;
--input-bg-color: #262523;
--bg-color: rgba(0,0,0,.7);
}
html,
body {
margin: 0;
background: #2b2b2b;
color: var(--main-color);
height: 100%;
font-family: sans-serif;
}
a { color: var(--link-color); text-decoration: none; }
a:hover { color: var(--link-hover-color); }
.scores {
position: absolute;
right: 0;
background: var(--bg-color);
padding: 5px;
border: solid 1px black;
box-shadow: 0 0 10px 0 rgba(0,0,0,.7);
}
.menu {
position: absolute;
left: 50%;
transform: translateX(-50%);
background: var(--bg-color);
padding: 5px;
border: solid 1px black;
box-shadow: 0 0 10px 0 rgba(0,0,0,.7);
z-index: 2;
}
.closed {
display: none;
}
.layer {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
background: var(--bg-color);
padding: 5px;
border: solid 1px black;
box-shadow: 0 0 10px 0 rgba(0,0,0,.7);
z-index: 1;
}
.overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 10;
background: var(--bg-color);
}
.preview {
position: absolute;
top: 20px;
left: 20px;
bottom: 20px;
right: 20px;
}
.preview .img {
height: 100%;
width: 100%;
position: absolute;
background-repeat: no-repeat;
background-position: center;
background-size: contain;
}
.menu .opener {
display: inline-block;
margin-right: 10px;
color: var(--link-color);
}
.menu .opener:last-child {
margin-right: 0;
}
.menu .opener:hover {
color: var(--link-hover-color);
cursor: pointer;
}
canvas {
cursor: none;
}
input {
background: #333230;
border-radius: 4px;
color: var(--main-color);
padding: 6px 10px;
border: solid 1px black;
box-shadow: 0 0 3px rgba(0, 0,0,0.3) inset;
}
input:focus {
border: solid 1px #686767;
background: var(--input-bg-color);
}
.btn {
font: 15px sans-serif;
display: inline-block;
background: var(--input-bg-color);
color: var(--link-color);
border: solid 1px black;
padding: 5px 10px;
box-shadow: 1px 1px 2px rgba(0,0,0,.5), 0 0 1px rgba(150,150,150,.4) inset;
border-radius: 4px;
user-select: none;
}
.btn:hover {
background: #2f2e2c;
color: var(--link-hover-color);
border: solid 1px #111;
box-shadow: 0 0 1px rgba(150,150,150,.4) inset;
cursor: pointer;
}
.btn:disabled {
background: #2f2e2c;
color: #8c4747 !important;
border: solid 1px #111;
box-shadow: 0 0 1px rgba(150,150,150,.4) inset;
cursor: not-allowed;
}

View file

@ -0,0 +1,16 @@
<html>
<head>
<link rel="stylesheet" href="/style.css" />
<style type="text/css">
html,
body {
overflow: hidden;
}
</style>
</head>
<body>
<script>window.GAME_ID = '{{GAME_ID}}'</script>
<script>window.WS_ADDRESS = '{{WS_ADDRESS}}'</script>
<script src="/game.js" type="module"></script>
</body>
</html>

View file

@ -0,0 +1,21 @@
<html>
<head>
<link rel="stylesheet" href="/style.css" />
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
</head>
<body>
<div id="app"></div>
<script type="module">
import Page from "/index.js"
new Vue({
el: '#app',
render: (h) => h(Page, {
props: {
games: {{ games|json_encode|raw }},
images: {{ images|json_encode|raw }},
},
}),
})
</script>
</body>
</html>