// Обеспечение работоспособности меню
var menuBtn = document.querySelector('.menu-btn');
var nav = document.querySelector('nav');
var lineOne = document.querySelector('nav .menu-btn .line--1');
var lineTwo = document.querySelector('nav .menu-btn .line--2');
var lineThree = document.querySelector('nav .menu-btn .line--3');
var link = document.querySelector('nav .nav-links');
$('.menu-btn').click(function() {
nav.classList.toggle('nav-open');
lineOne.classList.toggle('line-cross');
lineTwo.classList.toggle('line-fade-out');
lineThree.classList.toggle('line-cross');
link.classList.toggle('fade-in');
})
// Добавление метода remove для удаления элемента из массива по значению
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
return this;
}
}
}
// Получение списка слов для игры
var words = [];
$.get('/words.txt', function(d){
words = d.split('\n');
});
allLetters = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
// Создание объекта со свойствами буква: цена
lettersPrice = {}
allLetters.split('').forEach(function(letter){
if ('оеаинтсрвикмдпу'.split('').includes(letter))
var price = 1
else if ('яыьгзбгйхл'.split('').includes(letter))
var price = 2
else if ('жшюцч'.split('').includes(letter))
var price = 3
else if ('щэфъё'.split('').includes(letter))
var price = 4
lettersPrice[letter] = price;
});
// Функция для сохранения данных в localStorage
function save(){
var currentLetters = [];
$('.letter-button').each(function(index, el) {
// currentLetters.push($(this).text().toLowerCase());
currentLetters.push(allLetters.split('')[index]);
});
localStorage.setItem('letters', currentLetters);
localStorage.setItem('score', score);
localStorage.setItem('hints', hints);
}
// Функция для загрузки данных из localStorage
function load(){
if (typeof localStorage.letters != 'undefined' && localStorage.letters != 'undefined')
letters = localStorage.letters.split(',');
else
letters = undefined;
if (typeof localStorage.score != 'undefined' && localStorage.score != 'undefined')
score = localStorage.score;
else
score = undefined;
if (typeof localStorage.hints != 'undefined' && localStorage.hints != 'undefined')
hints = localStorage.hints;
else
hints = undefined;
return {
'letters': letters,
'score': score,
'hints': hints,
}
}
// Функция для получения случайного числа в диапазоне от 0 до max
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
// Функция проверяет, можно ли составить хотя бы одно слово из букв находящихся на игровом поле. Возвращает false или самое длиннное слово из тех, которые можно составить
function checkWords(){
var currentLetters = [];
$('.letter-button').each(function(index, el) {
currentLetters.push($(this).text().toLowerCase());
});
result = [];
words.forEach(function (word){
var playerLetters = currentLetters.slice();
word = word.split('');
var find = true;
// console.log('Word: ' + word);
word.forEach(function (letter) {
// console.log('Letter ' + letter + '. Player letters: ' + playerLetters)
// console.log(typeof letter, playerLetters[0])
if (!playerLetters.includes(letter) || !find){
find = false;
} else {
playerLetters.remove(letter);
}
});
if (find){
// console.log('Find: ' + word);
result.push(word.join(''));
}
});
if (result.length > 0){
result.sort(function(a, b){
// ASC -> a.length - b.length
// DESC -> b.length - a.length
return b.length - a.length;
});
return result[0];
} else {
return false
}
}
// Функция для показа подсказки, то есть подсвечивания зелёным следующей буквы самого длинного слова, которое можно составить из текущих букв
function showNextHint(){
word = checkWords();
hintLetters = [];
$('.letter-button').each(function(index, el) {
if ($(this).hasClass('hint')){
hintLetters.push($(this).text().toLowerCase())
}
});
nextIndex = -1;
word.split('').forEach(function (letter, index){
// console.log(index)
if (hintLetters.includes(letter))
hintLetters.remove(letter)
else if (nextIndex == -1)
nextIndex = index;
});
letter = word.split('')[nextIndex];
$('.letter-button').each(function(index, el) {
if ($(this).text().toLowerCase() == letter){
$(this).addClass('hint');
return false;
}
});
if (nextIndex == -1){
alert('Слово уже составлено!');
}
}
// Загрузка данных из localStorage
data = load();
// Применение данных
if (typeof data.letters != 'undefined'){
$('.letter-button').each(function(index, el) {
letter = data.letters[index].toUpperCase();
$(this).text(letter);
});
} else {
do {
$('.letter-button').each(function(index, el) {
$(this).text(allLetters[getRandomInt(allLetters.length)].toUpperCase());
});
} while (!checkWords());
}
if (typeof data.score != 'undefined')
score = +data.score;
else
score = 0;
if (typeof data.hints != 'undefined')
hints = +data.hints;
else
hints = 0;
$('.score').text(score);
$('.hints').text(hints);
// Обработка нажатия кнопки с буквой
$('.letter-button').click(function(event) {
$('.erase').removeAttr('disabled');
$('.mix').attr('disabled', '');
if ($('.word').html() == ' ')
$('.word').html('')
$('.word').text($('.word').text() + $(this).text())
if (words.includes($('.word').text().toLowerCase()))
$('.makeUp').removeAttr('disabled');
else
$('.makeUp').attr('disabled', '');
$(this).attr('disabled', '');
});
// Обработка нажатия кнопки "Стереть"
$('.erase').click(function(event) {
$('.erase').attr('disabled', '');
$('.letter-button').each(function(index, el) {
$(this).removeAttr('disabled');
});
$('.word').html(' ')
$('.makeUp').attr('disabled', '');
$('.mix').removeAttr('disabled');
});
// Обработка нажатия кнопки "Перемешать"
$('.mix').click(function(event) {
$('.loading').removeClass('hide');
sleepFor(setTimeout(function(){
do {
$('.letter-button').each(function(index, el) {
$(this).removeClass('hint');
$(this).text(allLetters[getRandomInt(allLetters.length)].toUpperCase());
});
} while (!checkWords());
$('.loading').addClass('hide');
}, 10))
});
// Обработка нажатия кнопки "Составить слово"
$('.makeUp').click(function(event) {
$('.loading').removeClass('hide');
sleepFor(setTimeout(function(){
var wordPrice = 0;
$('.word').text().split('').forEach(function (letter){
wordPrice += lettersPrice[letter.toLowerCase()];
// console.log(letter, lettersPrice[letter.toLowerCase()])
});
wordLengthCoefficient = 0;
if ($('.word').text().length == 2)
wordLengthCoefficient = 0.5;
else if ($('.word').text().length == 3)
wordLengthCoefficient = 0.6;
else if ($('.word').text().length == 4)
wordLengthCoefficient = 0.7;
else if ($('.word').text().length == 5)
wordLengthCoefficient = 0.9;
else if ($('.word').text().length == 6)
wordLengthCoefficient = 1;
else if ($('.word').text().length == 7)
wordLengthCoefficient = 1.2;
else
wordLengthCoefficient = 1.5;
// console.log(wordLengthCoefficient)
score += Math.round(wordLengthCoefficient * wordPrice);
$('.score').text(score);
$('.word').html(' ');
$('.erase').attr('disabled');
$('.letter-button').each(function(index, el) {
$(this).removeClass('hint');
});
$('.letter-button').each(function(index, el) {
if (typeof $(this).attr('disabled') != 'undefined'){
var i = 0;
do {
if (i > 3){
alert("Из этих букв нельзя составить ни одного слова. Перемешивание...");
$('.letter-button').each(function(index, el) {
$(this).text(allLetters[getRandomInt(allLetters.length)].toUpperCase());
});
}
$(this).text(allLetters[getRandomInt(allLetters.length)].toUpperCase());
$(this).removeAttr('disabled');
i++;
} while (!checkWords());
}
});
$('.makeUp').attr('disabled', '');
$('.loading').addClass('hide');
}, 10))
});
// Обработка нажатия кнопки "Использовать подсказку"
$('.showHint').click(function(event) {
$('.loading').removeClass('hide');
sleepFor(setTimeout(function(){
showNextHint();
$('.loading').addClass('hide');
}, 10))
});
// Сохранение данных перед закрытием страницы
window.onbeforeunload = function (){
save()
}
// Отключение спиннера загрузки при загрузке страницы
window.onload = function () {
$('.loading').addClass('hide');
}