console
const score = document.querySelector('.score');
const time = document.querySelector('.time');
const main = document.querySelector('.main');
const optionArray = document.querySelectorAll('.options');
const colorArray = ['red', 'yellow', 'blue', 'green', 'purple'];
const textArray = ['红', '黄', '蓝', '绿', '紫'];
const matchObj = {
red: '红',
yellow: '黄',
blue: '蓝',
green: '绿',
purple: '紫',
}
let timer;
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
const randomSortArray = arr => arr.sort((a, b) => randomNum(0, 1) - 0.5)
const randomTextAndColor = () => {
main.innerHTML = textArray[randomNum(0, textArray.length - 1)];
main.style.color = colorArray[randomNum(0, colorArray.length - 1)];
randomSortArray(colorArray);
randomSortArray(textArray)
for (let i = 0; i < optionArray.length; i++) {
optionArray[i].innerHTML = textArray[i]
optionArray[i].style.color = colorArray[i]
}
}
const countDown = () => {
timer = setInterval(() => {
time.innerHTML -= 1;
if (time.innerHTML == 0) {
clearInterval(timer);
}
}, 1000)
}
const start = () => {
for (let i = 0; i < optionArray.length; i++) {
optionArray[i].onclick = function () {
if (matchObj[main.style.color] === this.innerHTML) {
score.innerHTML = score.innerHTML - 0 + 1;
if (score.innerHTML == 1) {
countDown();
}
if (time.innerHTML <1) {
this.onclick = null;
}
randomTextAndColor();
}
}
}
}
const restart = () => {
score.innerHTML = 0;
time.innerHTML = 30;
start()
}
start()
randomTextAndColor()
<h1>选字游戏</h1>
<div class="root">
<header class="header">
<ul>
<li>
分数: <span class="score">0</span>
</li>
<li>
时间: <span class="time">30</span>s
</li>
</ul>
</header>
<main class="main"></main>
<footer class="footer">
<ul>
<li class="options"></li>
<li class="options"></li>
<li class="options"></li>
<li class="options"></li>
<li class="options"></li>
</ul>
</footer>
</div>
*{
margin: 0;
padding: 0;
user-select: none;
}
h1{
text-align: center;
}
ul{
list-style: none;
}
.root{
width: 350px;
height: 400px;
background-color: white;
margin: 40px auto;
border: 1px solid lightcoral;
position: relative;
}
.header ul{
height: 70px;
line-height: 70px;
font-size: 20px;
display: flex;
justify-content: space-around;
}
.main{
height: 250px;
line-height: 250px;
text-align: center;
font-size: 100px;
}
.footer ul{
height: 80px;
line-height: 80px;
display: flex;
justify-content: space-around;
font-size: 40px;
text-align: center;
}
.footer ul li{
cursor: pointer;
}
.over{
width: 100%;
background-color: rgb(222, 232, 247);
text-align: center;
font-size: 20px;
height: 120px;
position: absolute;
left: 0;
top: 150px;
display: none;
}