Files
quiz-ius/js/controllers.js
2026-04-03 10:51:51 -03:00

481 lines
17 KiB
JavaScript
Executable File

function randomizeCubes() {
var cubes = document.querySelectorAll('.cube');
cubes.forEach(function(cube) {
// Definindo uma faixa de valores ao redor do centro da tela
var centerX = 45; // centro horizontal aproximado da tela (45vw)
var centerY = 40; // centro vertical aproximado da tela (40vh)
// Randomizando valores para left e top dentro da faixa definida
var randomLeft = centerX + Math.floor(Math.random() * 90) - 50; // Variação de -5 a +5
var randomTop = centerY + Math.floor(Math.random() * 90) - 50; // Variação de -5 a +5
var randomDelay = Math.floor(Math.random() * 10); // Randomiza delay de 0 a 10
cube.style.left = randomLeft + 'vh';
cube.style.top = randomTop + 'vw';
cube.style.animationDelay = randomDelay + 's';
});
}
// Chamando a função para randomizar os elementos ao carregar a página, por exemplo
window.onload = function() {
randomizeCubes();
};
angular.module('app.controllers', [])
.controller('pageCtrl', ['$scope', '$stateParams', '$timeout', '$http',
function ($scope, $stateParams, $timeout, $http) {
S = $scope
S.toggleCursor = function(state) {
if (typeof state !== 'undefined') {
if (state) document.body.classList.add('show-cursor');
else document.body.classList.remove('show-cursor');
} else {
document.body.classList.toggle('show-cursor');
}
};
// Carregar os dados de parametrização global e aplicar ao tema
$http.get('dados/config.json').then(function (response) {
S.themeConfig = response.data;
console.log(S.themeConfig)
if (S.themeConfig.debug) {
S.debugMode = true; // Para uso no HTML
//document.documentElement.classList.add('debug-mode');
document.documentElement.classList.remove('play');
S.toggleCursor(true);
console.log("debug-mode on")
// Adicionar valor aleatorio nos links de arquivos carregados (evita cache de CSS)
var randomVal = new Date().getTime();
document.querySelectorAll('link[rel="stylesheet"]').forEach(function(link) {
var href = link.getAttribute('href');
if (href) {
link.href = href + (href.indexOf('?') === -1 ? '?' : '&') + 'v=' + randomVal;
}
});
// Lógica de Live-Reload nativo para Apache (checa a cada 2 segundos)
if (!window.liveReloadAtivo) {
window.liveReloadAtivo = true;
let lastModified = null;
setInterval(() => {
fetch(window.location.href, { method: 'HEAD', cache: 'no-store' })
.then(res => {
const currentModified = res.headers.get('Last-Modified');
if (lastModified && lastModified !== currentModified) {
console.log('Alteração detectada! Recarregando...');
window.location.reload();
}
lastModified = currentModified;
}).catch(() => {});
}, 2000);
}
} else {
S.debugMode = false;
document.documentElement.classList.remove('debug-mode');
document.documentElement.classList.add('play');
S.toggleCursor(false);
}
// Aplicar as variáveis de cor dinamicamente na raiz do documento
const rootNode = document.documentElement;
rootNode.style.setProperty('--cor-fundo-principal', S.themeConfig.cores.fundoPrincipal);
rootNode.style.setProperty('--cor-fundo-escuro', S.themeConfig.cores.fundoEscuro);
rootNode.style.setProperty('--cor-texto-principal', S.themeConfig.cores.textoPrincipal);
rootNode.style.setProperty('--cor-texto-secundario', S.themeConfig.cores.textoSecundario);
rootNode.style.setProperty('--cor-titulos', S.themeConfig.cores.tituloCor);
rootNode.style.setProperty('--cor-iniciar-bg', S.themeConfig.cores.btnIniciarFundo);
rootNode.style.setProperty('--cor-iniciar-texto', S.themeConfig.cores.btnIniciarTexto);
rootNode.style.setProperty('--cor-acerto', S.themeConfig.cores.corAcerto);
rootNode.style.setProperty('--cor-erro', S.themeConfig.cores.corErro);
rootNode.style.setProperty('--cor-fundo-resultado', S.themeConfig.cores.corFundoResultado);
Object.keys(S.themeConfig.cores.alternativas).forEach(key => {
rootNode.style.setProperty(`--cor-alt-${key.toLowerCase()}`, S.themeConfig.cores.alternativas[key]);
});
}).catch(function(err) {
console.error("Erro ao carregar configurações de tema:", err);
});
S.jogos = 0;
S.acertos = 0;
S.erros = 0;
S.vitorias = 0;
S.derrotas = 0;
S.lastCorrect = ""
S.lastWrong = ""
S.botoesAtivos = true
S.qtdItensBackdrop = 18
S.victory = false
S.v5by5 = false
S.showStart = true
// Função para embaralhar array
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
console.log(array[i], array[j])
}
for (var i = 0; i < array.length; i++) {
array[i].letra = String.fromCharCode(65 + i);
console.log(array[i])
}
}
$http.get('dados/perguntas.json').then(function (response) {
// Atribuir os dados ao escopo
$scope.quizDataOriginal = response.data;
});
// Função para garantir que os números aleatórios não se repitam
S.generateNonRepeatingRandomNumbers = (max, quantity) => {
if (quantity > max) {
console.error("Quantidade desejada maior que o intervalo possível.");
return [];
}
var result = [];
while (result.length < quantity) {
var randomNumber = Math.floor(Math.random() * max) + 1;
if (!result.includes(randomNumber)) {
result.push(randomNumber);
}
}
return result;
}
S.startGame = () => {
console.log("Iniciando jogo")
S.showStart = false;
shuffleArray($scope.quizData);
// Embaralhar as respostas de cada pergunta
$scope.quizData.forEach(function (pergunta) {
shuffleArray(pergunta.respostas);
});
S.correctList = S.generateNonRepeatingRandomNumbers(5, 5)
S.wrongList = S.generateNonRepeatingRandomNumbers(5, 5)
S.showGame = true
S.setupTransitionOut(S.start)
S.play('startgame', 0)
}
// Função para configurar a transição de entrada
S.setupTransitionIn = function (el = S.transition) {
var inList = [
"in:circle:center", "in:circle:top-left", "in:circle:top-right", "in:circle:bottom-left", "in:circle:bottom-right", "in:circle:hesitate",
"in:square:center", "in:square:top-left", "in:square:top-right", "in:square:bottom-left", "in:square:bottom-right", "in:square:hesitate",
"in:wipe:down", "in:wipe:up", "in:wipe:right", "in:wipe:left", "in:wipe:cinematic",
"in:diamond:center", "in:diamond:hesitate", "in:polygon:opposing-corners"
];
var i = Math.floor(Math.random() * inList.length);
el.attr('transition-style', inList[i]);
}
// Função para configurar a transição de saída
S.setupTransitionOut = function (el = S.transition) {
var outList = [
"out:circle:center", "out:circle:top-left", "out:circle:top-right", "out:circle:bottom-left", "out:circle:bottom-right", "out:circle:hesitate",
"out:square:center", "out:square:top-left", "out:square:top-right", "out:square:bottom-left", "out:square:bottom-right", "out:square:hesitate",
"out:wipe:down", "out:wipe:up", "out:wipe:right", "out:wipe:left", "out:wipe:cinematic",
"out:diamond:center", "out:diamond:hesitate", "out:polygon:opposing-corners"
];
var i = Math.floor(Math.random() * outList.length);
el.attr('transition-style', outList[i]);
S.botoesAtivos = true;
}
S.transition = angular.element(document.getElementById("transition"))
S.initTransition = angular.element(document.getElementById("initTransition"))
S.start = angular.element(document.getElementById("start"))
console.log(S.initTransition)
S.voltarInicio = function () {
S.iniciarNovoJogo()
$timeout(_ => {
S.setupTransitionIn(S.start)
}, 2000)
}
// Função para iniciar um novo jogo
$scope.iniciarNovoJogo = function () {
randomizeCubes()
S.jogos++
S.criarListaDinamica(S.qtdItensBackdrop)
$timeout(_ => {
S.setupTransitionIn(S.initTransition)
}, 200)
$timeout(_ => {
S.showStart = true
S.setupTransitionOut(S.initTransition)
}, 2500)
$timeout(_ => {
S.victory = false
S.lose = false
S.showGame = false
$timeout(() => {
S.$apply()
}, 10)
S.v5by5 = false
// Atribuir os dados ao escopo
$scope.quizData = $scope.quizDataOriginal
shuffleArray($scope.quizData);
// Embaralhar as respostas de cada pergunta
$scope.quizData.forEach(function (pergunta) {
shuffleArray(pergunta.respostas);
});
// Inicializa o objeto de quiz
$scope.quiz = {
perguntas: S.quizData,
perguntaAtual: 0, // Índice da pergunta atual
perguntasRespondidas: 1,
pontuacao: 0
};
}, 2000)
}
S.chamaResultado = function () {
if ($scope.quiz.pontuacao >= 3) {
$timeout(() => {
S.vitorias++
S.salvarDadosJogos();
S.victory = true
S.showGame = false
if (S.quiz.pontuacao === 5) {
S.v5by5 = true
S.play("success2", 1)
} else {
S.play("success1", 1)
S.v5by5 = false
}
}, 3000)
} else {
$timeout(_ => {
S.derrotas++
S.salvarDadosJogos();
S.criarListaDinamica(10, '.circles2')
S.victory = false
S.showGame = false
S.lose = true
S.play('wawawa', 0.5)
}, 3000)
// Adicione aqui qualquer outra lógica que você queira executar quando o jogador perder.
}
};
S.checarAlturaResposta = ()=> {
// Usando jQuery para encontrar o elemento
var respostaTextoElement = document.querySelectorAll('.right-side .resposta-texto');
respostaTextoElement.forEach(el=> {
// Verificando se o elemento tem mais de uma linha
if (el.scrollHeight > el.clientHeight + 10) {
// O texto tem mais de uma linha
console.log("O texto tem mais de uma linha.");
el.style.marginTop = "-0.90em"
} else {
// O texto tem apenas uma linha
console.log("O texto tem uma linha ou menos.");
}
})
}
S.destacarRespostaCorreta = function () {
// Obtém o índice da pergunta atual
var indicePergunta = S.quiz.perguntaAtual;
// Obtém o índice da resposta correta
var indiceRespostaCorreta = S.quizData[indicePergunta].respostas.findIndex(function (resposta) {
return resposta.correta;
});
// Adiciona a classe 'resposta-correta' à opção correta
var respostaCorretaElement = document.querySelector('#button-' + indiceRespostaCorreta);
if (respostaCorretaElement) {
respostaCorretaElement.classList.add('resposta-correta');
}
};
// Adicione a função para responder a uma pergunta
$scope.responder = function ($evento, indiceResposta) {
if (!S.botoesAtivos) return;
var pontuacaoDaResposta = 1
S.showStart = false
S.botoesAtivos = false
S.respostaAtual = $scope.quiz.perguntas[$scope.quiz.perguntaAtual].respostas[indiceResposta];
S.botaoClicado = angular.element($evento.currentTarget);
S.transition.removeClass('resposta-correta').removeClass('resposta-incorreta')
// Verifica se a resposta está correta
if (S.respostaAtual.correta) {
// Se a resposta estiver correta, altera a classe para verde
S.acertos++
var pontuacaoDaResposta = 1
S.play('correct')
S.botaoClicado.addClass('resposta-correta');
S.transition.addClass('resposta-correta')
} else {
// Se a resposta estiver incorreta, altera a classe para vermelha
S.play('wrong')
S.botaoClicado.addClass('resposta-incorreta');
S.destacarRespostaCorreta()
S.erros++
S.transition.addClass('resposta-incorreta')
var pontuacaoDaResposta = 0
}
$scope.quiz.pontuacao += pontuacaoDaResposta;
if ($scope.quiz.perguntasRespondidas === 5) {
S.chamaResultado()
}
// Aguarda 4 segundos antes de passar para a próxima pergunta
$timeout(function () {
// Remove a classe para garantir que ela seja aplicada corretamente na próxima vez
S.botaoClicado.removeClass('resposta-correta').removeClass('resposta-incorreta');
// Atualizar pontuação
// Passa para a próxima pergunta
$scope.quiz.perguntaAtual++;
$scope.quiz.perguntasRespondidas++;
}, 3000);
$timeout(()=>{
S.checarAlturaResposta()
},3100)
$timeout(() => S.setupTransitionIn(), 2000);
$timeout(() => S.setupTransitionOut(), 3250);
};
// Função para reproduzir o áudio
$scope.play = function (track, dl = 0) {
if (track == "correct") {
track = "correct" + (Math.floor(Math.random() * 3) + 1)
S.imagemURL = "correct" + S.correctList[S.quiz.perguntasRespondidas - 1]
}
if (track == "success") {
track = "success" + (Math.floor(Math.random() * 2) + 1)
// S.imagemURL = "correct" + (Math.floor(Math.random() * 5) + 1) + ".gif"
}
if (track == "wrong") {
// track = "wrong" + (Math.floor(Math.random() * 2) + 1)
S.imagemURL = "wrong" + S.wrongList[S.quiz.perguntasRespondidas - 1]
}
console.log(track, S.imagemURL)
var audioElement = document.getElementById(track);
$timeout(e => {
audioElement.play();
}, dl * 1000)
};
// S.criarListaDinamica = (quantidade, el = '.circles') => {
// // Seleciona o elemento ul com a classe 'circles'
// var ulElement = document.querySelector(el);
// // Garante que a quantidade seja um número positivo
// quantidade = Math.max(0, parseInt(quantidade) || 0);
// // Remove os elementos existentes dentro da lista
// ulElement.innerHTML = '';
// // Cria dinamicamente os elementos li e os adiciona à lista
// for (var i = 0; i < quantidade; i++) {
// var liElement = document.createElement('li');
// liElement.textContent = String.fromCharCode(65 + (i % 4)); // A, B, C, D
// ulElement.appendChild(liElement);
// }
// S.randomizeFloating()
// }
S.criarListaDinamica = (quantidade, el = '.circles') => {
// Obsoleto - removido devido ao novo layout whitelabel
}
S.randomizeFloating = function () {
// Obsoleto - removido devido ao novo layout whitelabel
}
S.randomizeFloating()
console.log(S.initTransition)
S.iniciarNovoJogo()
S.dadosJogos = function () {
// Tenta recuperar os dados do localStorage
var dadosSalvos = localStorage.getItem('quiz_dadosjogos');
if (dadosSalvos) {
try {
var dadosJogos = JSON.parse(dadosSalvos);
S.jogos = dadosJogos.jogos || 0;
S.acertos = dadosJogos.acertos || 0;
S.erros = dadosJogos.erros || 0;
S.vitorias = dadosJogos.vitorias || 0;
S.derrotas = dadosJogos.derrotas || 0;
} catch (e) {
console.error('Erro ao fazer parse dos dados do localStorage', e);
}
} else {
// Se não houver dados, inicializa variáveis locais como 0
S.jogos = 0;
S.acertos = 0;
S.erros = 0;
S.vitorias = 0;
S.derrotas = 0;
}
};
S.dadosJogos()
S.salvarDadosJogos = function () {
const dadosJogosObj = {
jogos: S.jogos,
acertos: S.acertos,
erros: S.erros,
vitorias: S.vitorias,
derrotas: S.derrotas
};
try {
localStorage.setItem('quiz_dadosjogos', JSON.stringify(dadosJogosObj));
console.log('Dados do jogo salvos com sucesso no LocalStorage!');
} catch (err) {
console.error('Erro ao salvar os dados no LocalStorage:', err);
}
};
}
])