write-ups-challenges-2021-2022/rng_farm/frontend/index.js

50 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

2021-12-02 23:33:26 +00:00
const webSocket = new WebSocket('ws://localhost:3006')
const waitForOpenConnection = () => {
return new Promise((resolve, reject) => {
const maxNumberOfAttempts = 10
const intervalTime = 200 //ms
let currentAttempt = 0
const interval = setInterval(() => {
if (currentAttempt > maxNumberOfAttempts - 1) {
clearInterval(interval)
reject(new Error('Maximum number of attempts exceeded'))
} else if (webSocket.readyState === webSocket.OPEN) {
clearInterval(interval)
resolve()
}
currentAttempt++
}, intervalTime)
})
}
async function send() {
await waitForOpenConnection();
webSocket.send({})
}
webSocket.onmessage = evt => {
const root = document.getElementById("root");
const magic = JSON.parse(evt.data)
root.innerHTML = ''
magic
.map(x => parseInt(x.join(''), 2))
.forEach(x => {
const img = document.createElement("img")
img.setAttribute("src", `./public/${x}.png`)
img.setAttribute("height", "80")
img.setAttribute("width", "80")
root.append(img)
})
}
async function getHarvest() {
await send()
}