Создание полноценного клавиатурного тренажера для веб-сайта — это сложная задача, требующая значительного объема кода и усилий. Однако, я могу предоставить базовый пример на JavaScript, HTML и CSS, который даст вам отправную точку. Этот пример будет включать в себя:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Клавиатурный тренажер</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Клавиатурный тренажер</h1>
<p id="text-to-type"></p>
<input type="text" id="user-input" autofocus>
<div id="result"></div>
</div>
<script src="script.js"></script>
</body>
</html>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f0f0;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
text-align: center;
}
input[type="text"] {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
}
input[type="text"]:focus {
outline: none;
border-color: #5cb85c;
}
#result {
margin-top: 20px;
font-weight: bold;
}
const textToType = document.getElementById('text-to-type');
const userInput = document.getElementById('user-input');
const result = document.getElementById('result');
const texts = [
"Это простой пример клавиатурного тренажера.",
"Практикуйтесь каждый день, чтобы улучшить свои навыки.",
"Быстрая печать важна для продуктивности."
];
let currentText = '';
let startTime;
function startGame() {
const randomIndex = Math.floor(Math.random() * texts.length);
currentText = texts[randomIndex];
textToType.textContent = currentText;
userInput.value = '';
startTime = new Date().getTime();
result.textContent = '';
}
function checkInput() {
const inputText = userInput.value;
if (inputText === currentText) {
const endTime = new Date().getTime();
const timeTaken = (endTime - startTime) / 1000;
const words = currentText.split(' ').length;
const wpm = Math.round(words / timeTaken * 60);
result.textContent = `Отлично! Ваша скорость: ${wpm} слов в минуту.`;
startGame();
}
}
userInput.addEventListener('input', checkInput);
startGame();
startGame() выбирает случайный текст из массива, отображает его, очищает поле ввода и запускает таймер.checkInput() сравнивает введенный текст с текущим текстом и, если они совпадают, вычисляет скорость печати и отображает результат.checkInput() при каждом изменении ввода.startGame() для начала игры при загрузке страницы.index.html, style.css и script.js.index.html в браузере.Этот пример предоставляет базовую функциональность. Для создания более сложного и функционального тренажера, вам потребуется добавить:
Ассистент: Чтобы сделать клавиатурный тренажер более продвинутым и полезным, можно добавить следующие функции:
function calculateWPM(text, timeInSeconds) {
const words = text.split(' ').length;
return Math.round(words / timeInSeconds * 60);
}
function calculateAccuracy(text, inputText) {
let correctChars = 0;
for (let i = 0; i < Math.min(text.length, inputText.length); i++) {
if (text[i] === inputText[i]) {
correctChars++;
}
}
return Math.round((correctChars / text.length) * 100);
}
function adaptDifficulty(wpm, accuracy) {
if (wpm < 20 && accuracy < 80) {
return "easy";
} else if (wpm < 40 && accuracy < 90) {
return "medium";
} else {
return "hard";
}
}
Эти функции помогут создать более привлекательный, эффективный и персонализированный клавиатурный тренажер, который будет мотивировать пользователей к улучшению своих навыков печати.
Ассистент: Для реализации системы достижений и наград в клавиатурном тренажере можно использовать JavaScript. Вот примеры кода, демонстрирующие основные компоненты такой системы:
const achievements = [
{
id: "speed-1",
name: "Новичок скорости",
description: "Достигните скорости 20 слов в минуту.",
condition: (wpm) => wpm >= 20,
reward: "Золотая медаль",
},
{
id: "accuracy-1",
name: "Точность - наше все",
description: "Достигните точности 95% и выше.",
condition: (wpm) => wpm >= 95,
reward: "Серебряная медаль",
},
{
id: "marathon-1",
name: "Марафонец",
description: "Продержитесь в режиме марафона 10 минут.",
condition: (duration) => duration >= 600, // 600 секунд = 10 минут
reward: "Бронзовая медаль",
},
];
function checkAchievements(stats) {
const earnedAchievements = [];
achievements.forEach((achievement) => {
if (
!localStorage.getItem(`achievement-${achievement.id}`) &&
achievement.condition(stats)
) {
earnedAchievements.push(achievement);
localStorage.setItem(`achievement-${achievement.id}`, "true"); // Отмечаем, что достижение получено
}
});
return earnedAchievements;
}
function displayAchievements(achievements) {
const achievementList = document.getElementById("achievement-list");
achievements.forEach((achievement) => {
const listItem = document.createElement("li");
listItem.innerHTML = `
<strong>${achievement.name}</strong> - ${achievement.description}
<br>
Награда: ${achievement.reward}
`;
achievementList.appendChild(listItem);
});
}
// Пример статистики пользователя
const userStats = {
wpm: 25,
accuracy: 96,
duration: 605,
};
// Проверяем достижения
const newAchievements = checkAchievements(userStats);
// Отображаем полученные достижения
if (newAchievements.length > 0) {
displayAchievements(newAchievements);
alert("Поздравляем! Вы получили новые достижения!");
}
achievements — массив объектов, где каждый объект представляет собой достижение.id — уникальный идентификатор достижения.name — название достижения.description — описание достижения.condition — функция, которая принимает статистику пользователя и возвращает true, если условие достижения выполнено.reward — награда за достижение.checkAchievements(stats) — принимает статистику пользователя (stats) в качестве аргумента.achievements.localStorage.earnedAchievements и сохраняет информацию о получении в localStorage.displayAchievements(achievements) — принимает массив полученных достижений в качестве аргумента.achievement-list в HTML.li и добавляет информацию о достижении в этот элемент.li в список достижений.userStats с примером статистики пользователя.checkAchievements() для проверки достижений.displayAchievements() для отображения их на странице и выводится сообщение с поздравлением.Ассистент: Интеграция системы достижений с профилем пользователя включает в себя несколько шагов:
Для хранения данных можно использовать различные подходы:
// Функция для сохранения данных пользователя и его достижений
function saveUserProfile(userId, username, achievements) {
const userProfile = {
userId: userId,
username: username,
achievements: achievements,
};
localStorage.setItem("userProfile", JSON.stringify(userProfile));
}
// Пример использования
const userId = "user123";
const username = "JohnDoe";
const achievements = [
{ id: "speed-1", name: "Новичок скорости", reward: "Золотая медаль" },
{ id: "accuracy-1", name: "Точность - наше все", reward: "Серебряная медаль" },
];
saveUserProfile(userId, username, achievements);
// Предположим, что у вас есть модель пользователя в MongoDB
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
userId: { type: String, unique: true, required: true },
username: { type: String, required: true },
achievements: [
{
id: { type: String, required: true },
name: { type: String, required: true },
reward: { type: String, required: true },
},
],
});
const User = mongoose.model("User", userSchema);
// Функция для сохранения данных пользователя и его достижений
async function saveUserProfile(userId, username, achievements) {
try {
const user = await User.findOneAndUpdate(
{ userId: userId },
{ username: username, achievements: achievements },
{ upsert: true, new: true }
);
console.log("User profile saved:", user);
} catch (error) {
console.error("Error saving user profile:", error);
}
}
// Пример использования
const userId = "user123";
const username = "JohnDoe";
const achievements = [
{ id: "speed-1", name: "Новичок скорости", reward: "Золотая медаль" },
{ id: "accuracy-1", name: "Точность - наше все", reward: "Серебряная медаль" },
];
saveUserProfile(userId, username, achievements);
// Функция для получения данных пользователя из localStorage
function getUserProfile() {
const userProfile = localStorage.getItem("userProfile");
return userProfile ? JSON.parse(userProfile) : null;
}
// Пример использования
const userProfile = getUserProfile();
if (userProfile) {
console.log("User profile:", userProfile);
const { userId, username, achievements } = userProfile;
console.log("User ID:", userId);
console.log("Username:", username);
console.log("Achievements:", achievements);
} else {
console.log("User profile not found.");
}
// Функция для получения данных пользователя из базы данных
async function getUserProfile(userId) {
try {
const user = await User.findOne({ userId: userId });
return user;
} catch (error) {
console.error("Error getting user profile:", error);
return null;
}
}
// Пример использования
async function displayUserProfile(userId) {
const userProfile = await getUserProfile(userId);
if (userProfile) {
console.log("User profile:", userProfile);
const { userId, username, achievements } = userProfile;
console.log("User ID:", userId);
console.log("Username:", username);
console.log("Achievements:", achievements);
} else {
console.log("User profile not found.");
}
}
displayUserProfile("user123");
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Профиль пользователя</title>
</head>
<body>
<h1>Профиль пользователя</h1>
<div id="user-profile">
<h2 id="username"></h2>
<h3>Достижения:</h3>
<ul id="achievement-list"></ul>
</div>
<script>
// Функция для отображения профиля пользователя
function displayUserProfile(userProfile) {
const usernameElement = document.getElementById("username");
const achievementListElement = document.getElementById("achievement-list");
usernameElement.textContent = `Имя пользователя: ${userProfile.username}`;
// Очищаем список достижений
achievementListElement.innerHTML = "";
// Отображаем достижения
userProfile.achievements.forEach(achievement => {
const listItem = document.createElement("li");
listItem.textContent = `${achievement.name} - ${achievement.reward}`;
achievementListElement.appendChild(listItem);
});
}
// Пример использования (с localStorage)
const userProfileData = JSON.parse(localStorage.getItem("userProfile"));
if (userProfileData) {
displayUserProfile(userProfileData);
} else {
document.getElementById("user-profile").textContent = "Профиль пользователя не найден.";
}
// Пример использования (с MongoDB - асинхронно)
// async function loadAndDisplayUserProfile(userId) {
// const userProfileData = await getUserProfile(userId);
// if (userProfileData) {
// displayUserProfile(userProfileData);
// } else {
// document.getElementById("user-profile").textContent = "Профиль пользователя не найден.";
// }
// }
// loadAndDisplayUserProfile("user123");
</script>
</body>
</html>
displayUserProfile(userProfile) принимает объект профиля пользователя и отображает его данные на странице.li и добавляет его в список достижений.localStorage и отобразить их на странице.MongoDB, который требует асинхронного вызова функции getUserProfile().
Используйте Homiwork как обычное приложение. Это удобно!
Добавить на главный экранSafari:
1. Нажмите кнопку «Поделиться»
2. Выберите «На экран Домой»
Chrome / Edge:
Нажмите значок установки в адресной строке
Добавить Homiwork на главный экран
1. \u041d\u0430\u0436\u043c\u0438\u0442\u0435 \u043a\u043d\u043e\u043f\u043a\u0443 \u00ab\u041f\u043e\u0434\u0435\u043b\u0438\u0442\u044c\u0441\u044f\u00bb
2. \u0412\u044b\u0431\u0435\u0440\u0438\u0442\u0435 \u00ab\u041d\u0430 \u044d\u043a\u0440\u0430\u043d \u0414\u043e\u043c\u043e\u0439\u00bb
3. \u041d\u0430\u0436\u043c\u0438\u0442\u0435 \u00ab\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c\u00bb
Эта функция доступна только для пользователей с Прайм статусом
Высококачественные решения от нейросети с подробными объяснениями и визуализациями доступны эксклюзивно для пользователей с Прайм статусом.
Начав пользоваться сервисом, вы принимаете: Условия использования, Политика конфиденциальности, Политика возвратов