<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>English Word Battle</title>
</head>
<body>
<h1>English Word Battle</h1>
<div id="game">
<p id="instructions">Type the correct English translation of the given word before time runs out!</p>
<p id="word"></p>
<input type="text" id="input" autofocus>
<p id="score">Score: 0</p>
<p id="time">Time left: 60</p>
<p id="right">恭喜你答对了</p>
<p id="error">很遗憾答案错误</p>
</div>
<script>
// Define an array of English words and their Chinese translations
const words = [
{ english: "hello", chinese: "你好" },
{ english: "goodbye", chinese: "再见" },
{ english: "apple", chinese: "苹果" },
{ english: "banana", chinese: "香蕉" },
{ english: "cat", chinese: "猫" },
{ english: "dog", chinese: "狗" },
{ english: "bird", chinese: "鸟" },
{ english: "fish", chinese: "鱼" },
{ english: "computer", chinese: "电脑" },
{ english: "phone", chinese: "手机" }
];
let score = 0;
let timeLeft = 60;
// Get random word from the array and display it on the screen
function getRandomWord() {
let wordIndex = Math.floor(Math.random() * words.length);
let word = words[wordIndex].english;
document.getElementById("word").textContent = word;
}
// Check if user's input is correct and update the score
function checkInput() {
let inputElement = document.getElementById("input");
let input = inputElement.value.trim().toLowerCase();
let currentWord = document.getElementById("word").textContent.toLowerCase();
if (input === words.find(w => w.english === currentWord).chinese.toLowerCase()) {
score++;
document.getElementById("score").textContent = `Score: ${score}`;
document.getElementById("right").style.display='block';
document.getElementById("error").style.display='none';
inputElement.value = "";
getRandomWord();
}else if(input != words.find(w => w.english === currentWord).chinese.toLowerCase()){
document.getElementById("right").style.display='none';
document.getElementById("error").style.display='block';
}
}
// Update the time left every second and end the game when time runs out
function updateTime() {
timeLeft--;
document.getElementById("time").textContent = `Time left: ${timeLeft}`;
if (timeLeft === 0) {
clearInterval(intervalId);
alert(`Game over! Your final score is ${score}.`);
document.getElementById("game").remove();
}
}
getRandomWord();
// Start the game loop
let intervalId = setInterval(updateTime, 1000);
// Add event listeners to the input field to check user's input
let inputElement = document.getElementById("input");
inputElement.addEventListener("input", checkInput);
inputElement.addEventListener("keydown", e => {
if (e.key === "Enter") {
checkInput();
}
});
</script>
</body>
</html>
<style>
#right {
display: none;
color: green;
font-size: 14px;
}
#error {
display: none;
color: red;
font-size: 14px;
}
</style>
运行效果: