JSFiddle - React, Tailwind, and code Playground
HTML
<table id="t"></table>
<script>
const createTable = () => {
const elem = []
const t = document.getElementById('t')
for (let y = 0; y < 6; y++) {
const r = document.createElement('tr')
t.appendChild(r)
const re = []
elem.push(re)
for (let x = 0; x < 5; x++) {
const c = document.createElement('td')
c.classList.add('empty', 'cell')
r.appendChild(c)
re.push(c)
}
}
return elem
}
const randomWord = () => { return 'SMART' }
let attempt = 0
const tryWord = (w) => {
for (let i = 0; i < 5; i++) {
let style = 'miss'
if (w[i] == word[i]) style = 'correct'
else if (word.indexOf(w[i]) >= 0) style = 'exists'
const e = elem[attempt][i]
e.classList.add(style)
e.classList.remove('empty')
}
attempt++
if (w == word) return 'won'
else if (attempt >= 6) return 'lost'
}
const gameOver = (msg) => {
setTimeout(() => {
alert(msg)
window.location.reload()
}, 50)
}
const elem = createTable(), word = randomWord()
let current = ''
document.addEventListener('keydown', (e) => {
const c = e.keyCode
const l = current.length
if (c == 13 && l == 5) {
const res = tryWord(current)
if (res) gameOver(`Game over! You ${res}! The word was ${word}!`)
current = ''
} else if (c == 8 && l > 0) {
current = current.substr(0, l-1)
elem[attempt][l-1].innerText = ''
} else if (c >= 65 && c <= 90 && l < 5) {
const ch = String.fromCharCode(c)
current = current + ch
elem[attempt][l].innerText = ch
}
})
</script>
<style>
.cell {
width: 90px;
height: 90px;
color: #fff;
border: 2px solid #ccc;
font-weight: bold;
text-align: center;
text-transform: capitalize;
}
.empty { color: #000 }
.correct { background-color: #6aaa64 }
.exists { background-color: #c9b458 }
.miss { background-color: #ccc }
</style>