-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1836 lines (1651 loc) · 61.1 KB
/
script.js
File metadata and controls
1836 lines (1651 loc) · 61.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// --------------------------------------------------
// FUNÇÕES AUXILIARES
// --------------------------------------------------
/**
* @namespace utils
* @description Funções utilitárias para sanitização de entrada e formatação de números.
*/
const utils = {
/**
* Sanitiza a entrada do usuário para prevenir ataques XSS.
* @memberof utils
* @param {string} input - A entrada do usuário a ser sanitizada.
* @returns {string} A entrada sanitizada.
*/
sanitizeInput: function(input) {
return input.toString().replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
},
/**
* Formata um número para o padrão brasileiro.
* @memberof utils
* @param {number} number - O número a ser formatado.
* @returns {string} O número formatado.
*/
formatNumber: function(number) {
return number.toLocaleString('pt-BR');
}
};
/**
* @namespace Logger
* @description Funções para logging de mensagens em diferentes níveis.
*/
const Logger = {
levels: {
ERROR: 'ERROR',
INFO: 'INFO'
},
/**
* Registra uma mensagem no console.
* @memberof Logger
* @param {string} level - O nível da mensagem (ex: 'ERROR', 'INFO').
* @param {string} message - A mensagem a ser registrada.
* @param {object} data - Dados adicionais a serem registrados.
*/
log: function(level, message, data = {}) {
console.log(`[${level}] ${message}`, data);
}
};
// --------------------------------------------------
// CACHE
// --------------------------------------------------
/**
* @class Cache
* @description Implementa uma funcionalidade simples de cache para armazenar e recuperar dados temporariamente.
*/
class Cache {
constructor() {
/** @private */
this.storage = {};
}
/**
* Obtém um valor do cache usando sua chave.
* @param {string} key - A chave de identificação do valor a ser recuperado.
* @returns {*} O valor em cache se for válido e não expirado, caso contrário, retorna null.
*/
get(key) {
const item = this.storage[key];
if (item && Date.now() < item.expires) {
return item.value;
}
delete this.storage[key]; // Remove o item expirado do cache.
return null;
}
/**
* Define um valor no cache associado a uma chave, com tempo de vida (TTL) opcional.
* @param {string} key - A chave para armazenar o valor no cache.
* @param {*} value - O valor a ser armazenado no cache.
* @param {number} [ttl=3600000] - Tempo de vida (Time To Live) em milissegundos antes de expirar (padrão: 1 hora).
*/
set(key, value, ttl = 3600000) {
this.storage[key] = {
value,
expires: Date.now() + ttl // Calcula o tempo de expiração baseado no TTL fornecido e no tempo atual.
};
}
}
// --------------------------------------------------
// NOTIFICAÇÕES
// --------------------------------------------------
/**
* @class Notifications
* @description Gerencia a exibição de notificações em sequência, utilizando uma fila para controlar a ordem e tempo de exibição.
*/
class Notifications {
constructor() {
/** @private */
this.queue = [];
/** @private */
this.isDisplaying = false;
}
/**
* Adiciona uma nova notificação à fila para ser exibida.
* @param {string} message - A mensagem de texto a ser exibida na notificação.
* @param {string} [type='info'] - O tipo da notificação ('info' ou 'error'), que define o estilo visual.
*/
show(message, type = 'info') {
this.queue.push({
message,
type
});
if (!this.isDisplaying) {
this.displayNext();
}
}
/**
* @private
*/
displayNext() {
if (this.queue.length === 0) {
this.isDisplaying = false;
return;
}
this.isDisplaying = true;
const next = this.queue.shift();
const notification = document.createElement('div');
notification.className = `notification ${next.type}`;
notification.setAttribute('role', 'alert');
notification.innerHTML = `
<span class="message">${utils.sanitizeInput(next.message)}</span>
<button class="close" aria-label="Fechar">×</button>
`;
document.body.appendChild(notification);
setTimeout(() => {
notification.classList.add('fade-out');
setTimeout(() => {
notification.remove();
this.displayNext();
}, 300);
}, 5000);
notification.querySelector('.close').addEventListener('click', () => {
notification.remove();
this.displayNext();
});
}
}
// --------------------------------------------------
// JOGO DA FORCA
// --------------------------------------------------
/**
* @class Forca
* @description Gerencia a lógica do Jogo da Forca.
*/
class Forca {
constructor(contentDiv) {
this.contentDiv = contentDiv;
this.palavras = ["javascript", "html", "css", "programacao", "computador", "internet"];
this.palavraSecreta = this.escolherPalavra(); // Define a palavra a ser adivinhada
this.letrasErradas = [];
this.letrasCorretas = [];
this.maxErros = 6;
this.erros = 0;
}
/**
* @private
*/
escolherPalavra() {
return this.palavras[Math.floor(Math.random() * this.palavras.length)]; // Retorna uma palavra aleatória do array
}
/**
* Atualiza o estado do jogo na interface.
*/
atualizarJogo() {
this.contentDiv.innerHTML = `
<div id="forca-container">
<h2>Jogo da Forca</h2>
<p id="forca-palavra">${this.palavraSecreta.split('').map(letra => this.letrasCorretas.includes(letra) ? letra : '_').join(' ')}</p>
<p id="forca-letras-erradas">Letras Erradas: ${this.letrasErradas.join(', ')}</p>
<p>Erros: ${this.erros}/${this.maxErros}</p>
<input type="text" id="letra-input" maxlength="1" placeholder="Digite uma letra">
<button id="btn-adivinhar">Adivinhar</button>
<button onclick="app.voltarAoMenu()">Voltar ao Menu</button>
<p id="forca-mensagem"></p>
</div>
`;
document.getElementById('btn-adivinhar').addEventListener('click', () => this.adivinharLetra()); // Evento do botão "Adivinhar"
document.getElementById('letra-input').addEventListener('keyup', (event) => { // Evento para Enter no input
if (event.key === 'Enter') {
this.adivinharLetra();
}
});
}
/**
* @private
*/
adivinharLetra() {
const letraInput = document.getElementById('letra-input');
const letra = letraInput.value.toLowerCase();
letraInput.value = ''; // Limpa o input
if (!letra.match(/[a-z]/i)) { // Valida se é letra
document.getElementById('forca-mensagem').textContent = 'Por favor, digite uma letra válida.';
return;
}
if (this.letrasCorretas.includes(letra) || this.letrasErradas.includes(letra)) { // Verifica se letra já foi tentada
document.getElementById('forca-mensagem').textContent = 'Você já tentou essa letra. Tente outra.';
return;
}
if (this.palavraSecreta.includes(letra)) {
this.letrasCorretas.push(letra); // Acertou a letra
} else {
this.letrasErradas.push(letra); // Errou a letra
this.erros++; // Incrementa erros
}
this.atualizarJogo(); // Atualiza a tela
if (this.erros === this.maxErros) { // Perdeu o jogo
document.getElementById('forca-mensagem').textContent = `Você perdeu! A palavra era ${this.palavraSecreta}.`;
this.desabilitarJogo();
} else if (!document.getElementById('forca-palavra').textContent.includes('_')) { // Ganhou o jogo
document.getElementById('forca-mensagem').textContent = 'Parabéns! Você ganhou!';
this.desabilitarJogo();
}
}
/**
* @private
*/
desabilitarJogo() {
document.getElementById('letra-input').disabled = true; // Desabilita input
document.getElementById('btn-adivinhar').disabled = true; // Desabilita botão
}
}
// --------------------------------------------------
// JOGO DA VELHA - Inteligência Aprimorada
// --------------------------------------------------
/**
* @class JogoDaVelha
* @description Gerencia a lógica do Jogo da Velha com IA aprimorada.
*/
class JogoDaVelha {
constructor(contentDiv) {
this.contentDiv = contentDiv;
this.currentPlayer = 'X'; // Jogador humano começa
this.gameBoard = ['', '', '', '', '', '', '', '', '']; // Tabuleiro vazio
this.gameActive = true; // Jogo ativo
}
/**
* @method renderBoard
* @description Renderiza o tabuleiro do jogo e os elementos da interface.
*/
renderBoard() {
this.contentDiv.innerHTML = `
<div class="jogo-velha-container">
<h2>Jogo da Velha</h2>
<div class="grid"></div>
<div class="status"></div>
<button onclick="app.jogoDaVelha.reiniciarJogo()">Reiniciar Jogo</button>
<button onclick="app.voltarAoMenu()">Voltar ao Menu</button>
</div>
`;
const grid = document.querySelector('.grid');
for (let i = 0; i < 9; i++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.addEventListener('click', () => this.handleClick(i)); // Evento de clique na célula
grid.appendChild(cell);
}
this.updateStatus(); // Status inicial
}
/**
* @method handleClick
* @param {number} index - Índice da célula clicada.
* @description Lida com o clique em uma célula do tabuleiro.
*/
handleClick(index) {
if (this.gameBoard[index] === '' && this.gameActive) { // Célula vazia e jogo ativo?
this.gameBoard[index] = this.currentPlayer; // Marca célula com jogador atual
this.renderCell(index); // Atualiza visual da célula
if (this.checkWinner()) { // Checa vitória
this.updateStatus(); // Atualiza status de vitória
this.gameActive = false; // Jogo inativo após vitória
return;
}
if (this.isBoardFull()) { // Checa empate
this.updateStatus(); // Atualiza status de empate
this.gameActive = false; // Jogo inativo após empate
return;
}
this.togglePlayer(); // Troca jogador
this.updateStatus(); // Atualiza status do jogador da vez
if (this.currentPlayer === 'O' && this.gameActive) { // Vez do computador?
setTimeout(() => this.makeComputerMove(), 500); // IA joga após um delay
}
}
}
/**
* @method renderCell
* @param {number} index - Índice da célula a ser renderizada.
* @description Adiciona a classe do jogador ('X' ou 'O') à célula correspondente no tabuleiro visual.
*/
renderCell(index) {
const cell = document.querySelector(`.grid .cell:nth-child(${index + 1})`);
cell.classList.add(this.currentPlayer); // Adiciona classe 'X' ou 'O'
}
/**
* @method togglePlayer
* @description Alterna o jogador atual entre 'X' e 'O'.
*/
togglePlayer() {
this.currentPlayer = this.currentPlayer === 'X' ? 'O' : 'X'; // Troca 'X' por 'O' ou vice-versa
}
/**
* @method checkWinner
* @returns {boolean} - Retorna true se houver um vencedor ou empate, false caso contrário.
* @description Verifica se há um vencedor no jogo ou se o jogo empatou.
*/
checkWinner() {
const winPatterns = [ // Padrões de vitória
[0, 1, 2],
[3, 4, 5],
[6, 7, 8], // Linhas
[0, 3, 6],
[1, 4, 7],
[2, 5, 8], // Colunas
[0, 4, 8],
[2, 4, 6] // Diagonais
];
for (const pattern of winPatterns) {
const [a, b, c] = pattern;
if (this.gameBoard[a] && this.gameBoard[a] === this.gameBoard[b] && this.gameBoard[a] === this.gameBoard[c]) {
return this.gameBoard[a]; // Retorna o jogador vencedor ('X' ou 'O')
}
}
return null; // Sem vencedor ainda
}
/**
* @method isBoardFull
* @returns {boolean} - Retorna true se o tabuleiro estiver cheio (empate), false caso contrário.
* @description Verifica se todas as células do tabuleiro estão preenchidas.
*/
isBoardFull() {
return this.gameBoard.every(cell => cell !== ''); // Checa se não tem célula vazia
}
/**
* @method updateStatus
* @description Atualiza a mensagem de status do jogo na interface, exibindo o jogador da vez, o vencedor ou empate.
*/
updateStatus() {
if (!this.gameActive) return; // Jogo inativo, não atualiza
const winner = this.checkWinner(); // Verifica vencedor
const status = document.querySelector('.status'); // Elemento de status
if (winner) {
status.textContent = `Jogador ${winner} venceu!`; // Mostra vencedor
this.gameActive = false; // Desativa jogo
} else if (this.isBoardFull()) {
status.textContent = 'Empate!'; // Mostra empate
this.gameActive = false; // Desativa jogo
} else {
status.textContent = `Vez do Jogador ${this.currentPlayer}`; // Mostra jogador da vez
}
}
/**
* @method makeComputerMove
* @description Determina e executa o movimento do computador ('O') com lógica de IA (nível fácil/médio).
*/
makeComputerMove() {
if (!this.gameActive || this.currentPlayer !== 'O') return; // Jogo inativo ou não é vez do computador
let bestMoveIndex = this.getBestMove(); // IA calcula o melhor movimento
if (bestMoveIndex !== null) {
this.gameBoard[bestMoveIndex] = 'O'; // Computador faz o movimento
this.renderCell(bestMoveIndex); // Atualiza visual
if (this.checkWinner()) { // Checa se IA venceu
this.updateStatus(); // Atualiza status (IA venceu)
this.gameActive = false; // Desativa jogo
return;
}
if (this.isBoardFull()) { // Checa empate
this.updateStatus(); // Atualiza status (empate)
this.gameActive = false; // Desativa jogo
return;
}
this.togglePlayer(); // Troca para jogador humano
this.updateStatus(); // Atualiza status (vez do humano)
}
}
/**
* @method getBestMove
* @returns {number|null} - Retorna o índice do melhor movimento para o computador ou null se não houver movimentos possíveis.
* @description Implementa a lógica de IA para o computador encontrar o melhor movimento, priorizando vitória, bloqueio e jogadas estratégicas.
*/
getBestMove() {
// 1. Tenta vencer
for (let i = 0; i < 9; i++) {
if (this.gameBoard[i] === '') {
this.gameBoard[i] = 'O'; // Simula movimento IA
if (this.checkWinner() === 'O') { // Vencerá?
this.gameBoard[i] = ''; // Desfaz simulação
return i; // Retorna índice para vencer
}
this.gameBoard[i] = ''; // Desfaz simulação
}
}
// 2. Tenta bloquear
for (let i = 0; i < 9; i++) {
if (this.gameBoard[i] === '') {
this.gameBoard[i] = 'X'; // Simula movimento jogador
if (this.checkWinner() === 'X') { // Jogador venceria?
this.gameBoard[i] = ''; // Desfaz simulação
return i; // Retorna índice para bloquear
}
this.gameBoard[i] = ''; // Desfaz simulação
}
}
// 3. Movimento estratégico (centro, cantos, lados)
const strategicMoves = [4, 0, 2, 6, 8, 1, 3, 5, 7]; // Prioridades: Centro, Cantos, Lados
for (const move of strategicMoves) {
if (this.gameBoard[move] === '') {
return move; // Retorna primeiro movimento estratégico livre
}
}
// 4. Fallback (não deve acontecer em jogo normal)
return null; // ou movimento aleatório se necessário
}
/**
* @method reiniciarJogo
* @description Reinicia o jogo, resetando o tabuleiro, o jogador atual e o estado do jogo.
*/
reiniciarJogo() {
this.currentPlayer = 'X'; // Jogador 'X' sempre começa
this.gameBoard = ['', '', '', '', '', '', '', '', '']; // Limpa tabuleiro
this.gameActive = true; // Reativa jogo
this.renderBoard(); // Redesenha tabuleiro
}
}
// --------------------------------------------------
// LISTA DE TAREFAS - Inteligência Aprimorada (Refatoração e Melhorias)
// --------------------------------------------------
/**
* @class ListaDeTarefas
* @description Gerencia a lógica da Lista de Tarefas com renderização e organização melhoradas.
*/
class ListaDeTarefas {
constructor(contentDiv) {
this.contentDiv = contentDiv;
this.tasks = this.loadTasks(); // Inicializa tarefas carregando do localStorage
}
/**
* @method loadTasks
* @returns {Array<object>} - Array de tarefas do localStorage ou vazio.
* @description Carrega tarefas salvas ou inicia lista vazia.
*/
loadTasks() {
const storedTasks = localStorage.getItem('tasks');
return storedTasks ? JSON.parse(storedTasks) : []; // Retorna tarefas do storage ou array vazio
}
/**
* @method saveTasks
* @description Salva tarefas no localStorage.
*/
saveTasks() {
localStorage.setItem('tasks', JSON.stringify(this.tasks)); // Salva array de tarefas no storage
}
/**
* @method renderTasks
* @description Renderiza a lista de tarefas na tela.
*/
renderTasks() {
this.contentDiv.innerHTML = `
<div class="todo-container fade-in">
<h2>Lista de Tarefas</h2>
<div class="todo-header">
<input type="text" id="taskInput" placeholder="Adicione uma tarefa" aria-label="Nova tarefa">
<button id="addTaskBtn">Adicionar</button>
</div>
<ul class="todo-list">
${this.renderTaskListItems()}
</ul>
<button onclick="app.voltarAoMenu()">Voltar ao Menu</button>
</div>
`;
this.setupEventListeners(); // Configura eventos dos botões
}
/**
* @method renderTaskListItems
* @private
* @returns {string} - HTML para itens da lista de tarefas.
* @description Cria HTML para cada tarefa na lista.
*/
renderTaskListItems() {
return this.tasks.map((task, index) => `
<li class="todo-item">
<input type="checkbox" id="task-${index}" ${task.completed ? 'checked' : ''} aria-labelledby="task-label-${index}">
<span id="task-label-${index}" class="${task.completed ? 'completed' : ''}">${utils.sanitizeInput(task.text)}</span>
<button class="delete-btn" data-index="${index}" aria-label="Excluir tarefa ${task.text}">Excluir</button>
</li>`).join(''); // Transforma array de HTML em string
}
/**
* @method setupEventListeners
* @private
* @description Configura eventos para botões e checkboxes.
*/
setupEventListeners() {
document.getElementById('addTaskBtn').addEventListener('click', () => this.addTask()); // Evento botão Adicionar
const taskList = document.querySelector('.todo-list');
taskList.addEventListener('change', (event) => { // Evento change nos checkboxes (delegação)
if (event.target.type === 'checkbox') {
const index = parseInt(event.target.id.split('-')[1], 10); // Pega índice do checkbox
this.toggleTask(index); // Alterna tarefa
}
});
taskList.addEventListener('click', (event) => { // Evento click nos botões delete (delegação)
if (event.target.classList.contains('delete-btn')) {
const index = parseInt(event.target.dataset.index, 10); // Pega índice do botão delete
this.deleteTask(index); // Deleta tarefa
}
});
}
/**
* @method addTask
* @description Adiciona nova tarefa. Valida input, atualiza UI e localStorage.
*/
addTask() {
const taskInput = document.getElementById('taskInput');
const taskText = taskInput.value.trim(); // Pega texto da tarefa
if (!taskText) {
alert("Por favor, insira uma tarefa antes de adicionar."); // Alerta se input vazio
return; // Sai da função se não tiver texto
}
this.tasks.push({
text: taskText,
completed: false
}); // Adiciona tarefa ao array
this.saveTasks(); // Salva tarefas
taskInput.value = ''; // Limpa input
this.updateTaskListUI(); // Atualiza lista na tela
}
/**
* @method toggleTask
* @param {number} index - Índice da tarefa.
* @description Alterna status (concluída/não concluída) da tarefa. Atualiza UI e localStorage.
*/
toggleTask(index) {
if (index >= 0 && index < this.tasks.length) { // Valida índice
this.tasks[index].completed = !this.tasks[index].completed; // Inverte status da tarefa
this.saveTasks(); // Salva tarefas
this.updateTaskItemUI(index); // Atualiza item da tarefa na tela
} else {
console.error('Índice de tarefa inválido:', index); // Erro: índice inválido
}
}
/**
* @method deleteTask
* @param {number} index - Índice da tarefa.
* @description Deleta tarefa da lista. Atualiza UI e localStorage.
*/
deleteTask(index) {
if (index >= 0 && index < this.tasks.length) { // Valida índice
this.tasks.splice(index, 1); // Remove tarefa do array
this.saveTasks(); // Salva tarefas
this.updateTaskListUI(); // Atualiza lista na tela
} else {
console.error('Índice de tarefa inválido:', index); // Erro: índice inválido
}
}
/**
* @method updateTaskListUI
* @private
* @description Atualiza a lista de tarefas (UL) na tela. Renderiza novamente os itens da lista.
*/
updateTaskListUI() {
const taskList = document.querySelector('.todo-list');
if (taskList) {
taskList.innerHTML = this.renderTaskListItems(); // Atualiza conteúdo da UL
this.setupEventListenersForListItems(); // Refaz eventos dos itens (deprecated)
}
}
/**
* @method updateTaskItemUI
* @private
* @param {number} index - Índice da tarefa.
* @description Atualiza um item específico da tarefa na UI (classe 'completed', checkbox).
*/
updateTaskItemUI(index) {
const listItem = document.querySelector(`.todo-list li:nth-child(${index + 1})`);
if (listItem) {
const task = this.tasks[index];
const taskSpan = listItem.querySelector('span');
const checkbox = listItem.querySelector('input[type="checkbox"]');
if (taskSpan) taskSpan.className = task.completed ? 'completed' : ''; // Atualiza classe do span
if (checkbox) checkbox.checked = task.completed; // Atualiza checkbox
}
}
/**
* @method setupEventListenersForListItems
* @private
* @description Configura eventos para itens da lista (checkboxes/delete btns) - DEPRECATED.
* @deprecated - Delegação de eventos em `setupEventListeners` torna isto redundante.
*/
setupEventListenersForListItems() { // DEPRECATED - Delegação no setupEventListeners torna obsoleto
// Implementação de listeners para checkboxes e delete buttons em cada item, se necessário em renderização parcial.
// No modelo atual, delegação em 'setupEventListeners' torna essa função redundante, mantida por referência.
}
}
// --------------------------------------------------
// CALCULADORA
// --------------------------------------------------
/**
* @class Calculator
* @description Gerencia a lógica da Calculadora.
*/
class Calculator {
/**
* @constructor
* @param {object} i18n - Objeto de internacionalização.
* @param {object} contentDiv - Div de conteúdo.
*/
constructor(i18n, contentDiv) {
this.contentDiv = contentDiv;
this.i18n = i18n;
this.history = [];
this.cache = new Cache(); // Cache (se precisar)
this.mathParser = math; // Biblioteca math.js
}
initialize() {
this.loadHistory(); // Carrega o histórico salvo
}
/**
* @private
* @returns {string} HTML dos botões.
* @description Renderiza os botões.
*/
renderButtons() {
const buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+',
'CE', '%' // Botões extras
];
return buttons.map(button => {
let className = 'calc-button';
if (['/', '*', '-', '+', '%'].includes(button)) { // É operador?
className += ' operator';
} else if (button === '=') { // É igual?
className += ' equal';
} else if (button === 'CE') { // É Clear Entry?
className += ' clear-entry';
}
return `<button
class="${className}"
data-key="${button}"
aria-label="${button}"
>${button}</button>`;
}).join(''); // Junta tudo em HTML
}
/**
* @param {string} button - Botão clicado.
* @description Manipula o clique dos botões.
*/
handleButtonClick(button) {
const display = document.getElementById('display');
if (button === '=') { // Clicou em igual
try {
const result = this.calculate(display.value); // Calcula
display.value = result; // Mostra no display
} catch (error) {
app.notifications.show(error.message, 'error'); // Mostra erro se tiver
}
} else if (button === 'CE') { // Clicou em CE
this.clearEntry(); // Limpa a entrada
} else if (button === '%') { // Clicou em porcentagem
this.handlePercentage(); // Faz a conta de porcentagem
} else { // Clicou em número ou operador
display.value += button; // Adiciona ao que já está no display
}
}
/**
* @returns {string} HTML da calculadora.
* @description Renderiza a calculadora.
*/
render() {
return `
<div class="calculator-container" role="application">
<h2>Calculadora - Parecida com iphone</h2>
<div class="calc-display" role="textbox" aria-label="${this.i18n.t('display')}">
<input type="text" id="display" value="0" readonly>
</div>
<div class="calc-buttons" role="group">
${this.renderButtons()}
</div>
<div class="calc-history">
<h3>${this.i18n.t('history')}</h3>
<ul id="calcHistory" role="list"></ul>
<button class="clear-history" onclick="app.calculator.clearHistory()">${this.i18n.t('clearHistory') || 'Limpar Histórico'}</button>
</div>
<button
onclick="app.voltarAoMenu()"
class="secondary-button"
aria-label="${this.i18n.t('returnToMenu')}"
>${this.i18n.t('back')}
</button>
</div>
`;
}
/**
* @param {string} expression - Expressão matemática.
* @returns {number} Resultado do cálculo.
* @throws {Error} Se a expressão for inválida.
* @description Calcula a expressão.
*/
calculate(expression) {
try {
expression = expression.replace(/%/g, '/100'); // Troca % por divisão por 100
const result = this.mathParser.evaluate(expression); // Usa math.js pra calcular
if (!isFinite(result)) { // Checa se o resultado é um número válido
throw new Error(this.i18n.t('calculationError')); // Se não for, dá erro
}
this.addToHistory(expression, result); // Salva no histórico
return result; // Retorna o resultado
} catch (error) {
Logger.log(Logger.levels.ERROR, 'Erro no cálculo', { // Loga o erro
expression,
error
});
throw new Error(this.i18n.t('calculationError')); // Manda o erro pra tela
}
}
/**
* @param {string} expression - Expressão calculada.
* @param {number} result - Resultado do cálculo.
* @description Adiciona ao histórico.
*/
addToHistory(expression, result) {
const historyItem = {
expression,
result,
timestamp: new Date().toISOString() // Guarda a hora que calculou
};
this.history.unshift(historyItem); // Põe no começo da lista
this.history = this.history.slice(0, 10); // Limita a 10 itens no histórico
this.saveHistory(); // Salva o histórico
this.updateHistoryDisplay(); // Atualiza a tela do histórico
}
/**
* @description Carrega histórico.
*/
loadHistory() {
try {
const saved = localStorage.getItem('calcHistory'); // Pega do localStorage
if (saved) {
this.history = JSON.parse(saved); // Transforma de volta pra objeto
this.updateHistoryDisplay(); // Mostra na tela
}
} catch (error) {
Logger.log(Logger.levels.ERROR, 'Erro ao carregar histórico', { // Se der erro, loga
error
});
}
}
/**
* @description Salva histórico.
*/
saveHistory() {
try {
localStorage.setItem('calcHistory', JSON.stringify(this.history)); // Salva no localStorage
} catch (error) {
Logger.log(Logger.levels.ERROR, 'Erro ao salvar histórico', { // Se der erro, loga
error
});
}
}
/**
* @description Atualiza histórico na tela.
*/
updateHistoryDisplay() {
const historyList = this.contentDiv.querySelector('.calc-history ul'); // Pega a lista HTML
if (!historyList) return; // Se não tem lista, não faz nada
historyList.innerHTML = this.history.map(item => `
<li class="history-item" role="listitem">
<span class="expression">${utils.sanitizeInput(item.expression)}</span>
<span class="separator">=</span>
<span class="result">${utils.formatNumber(item.result)}</span>
<span class="timestamp">${this.formatTimestamp(item.timestamp)}</span>
</li>
`).join(''); // Cria HTML pra cada item do histórico
const lastItem = historyList.lastElementChild; // Pega o último item adicionado
if (lastItem) {
lastItem.classList.add('new-item'); // Animação visual de novo item
setTimeout(() => {
lastItem.classList.remove('new-item'); // Remove a animação depois de um tempo
}, 500); // Tempo da animação
}
}
/**
* @description Limpa o histórico.
*/
clearHistory() {
this.history = []; // Limpa o array do histórico
this.saveHistory(); // Salva histórico vazio
this.updateHistoryDisplay(); // Atualiza a tela do histórico
}
/**
* @private
* @param {string} timestamp - Timestamp ISO.
* @returns {string} Timestamp formatado.
* @description Formata a hora.
*/
formatTimestamp(timestamp) {
const date = new Date(timestamp); // Cria objeto Date
return `${date.toLocaleDateString('pt-BR')} ${date.toLocaleTimeString('pt-BR')}`; // Formata pra pt-BR
}
/**
* @description Configura eventos dos botões e teclado.
*/
setupEventListeners() {
const buttons = this.contentDiv.querySelector('.calc-buttons'); // Pega os botões
if (buttons) {
buttons.addEventListener('click', (event) => { // Evento de clique nos botões
const key = event.target.dataset.key; // Qual botão clicou?
if (key) {
this.handleButtonClick(key); // Manda pro manipulador de cliques
}
});
}
document.addEventListener('keydown', (event) => { // Evento de teclado
this.handleKeyPress(event); // Manda pro manipulador de teclado
});
}
/**
* @param {KeyboardEvent} event - Evento de teclado.
* @description Manipula teclado.
*/
handleKeyPress(event) {
const key = event.key; // Tecla que apertou
const validKeys = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '/', '*', '-', '+', '.', '=', '%']; // Teclas válidas na calculadora
if (validKeys.includes(key)) { // É tecla de número/operador?
event.preventDefault(); // Previne ação padrão da tecla
this.handleButtonClick(key === '=' ? '=' : key); // Simula clique no botão
} else if (key === 'Enter') { // É Enter?
event.preventDefault();
this.handleButtonClick('='); // Enter = Igual
} else if (key === 'Backspace') { // É Backspace?
event.preventDefault();
this.handleBackspace(); // Apaga um caractere
} else if (key === 'Escape') { // É Escape?
event.preventDefault();
this.clearDisplay(); // Limpa o display
}
}
/**
* @description Apaga um caractere do display.
*/
handleBackspace() {
const display = document.getElementById('display'); // Display da calculadora
display.value = display.value.slice(0, -1); // Remove o último char
}
/**
* @description Limpa display pra zero.
*/
clearDisplay() {
const display = document.getElementById('display'); // Display da calculadora
display.value = '0'; // Zera o display
}
/**
* @description Limpa a entrada atual.
*/
clearEntry() {
this.clearDisplay(); // CE faz a mesma coisa que Clear Display aqui
}
/**
* @description Manipula porcentagem.
*/
handlePercentage() {
const display = document.getElementById('display'); // Display da calculadora
let currentValue = parseFloat(display.value); // Valor atual no display
if (!isNaN(currentValue)) { // Se for número
display.value = currentValue / 100; // Divide por 100 (cálculo da %)
}
}
}
// --------------------------------------------------
// CLASSE ImprovedBlindEqualization (Implementação do Algoritmo de Equalização Cega)
// --------------------------------------------------
/**
* @class ImprovedBlindEqualization
* @description Implementa o algoritmo de equalização cega aprimorado.
*/
class ImprovedBlindEqualization {
/**
* @constructor
* @param {number} [stepSize=0.01] - Tamanho do passo.
* @param {number} [alpha=0.1] - Ajuste dinâmico do fator.
*/
constructor(stepSize = 0.01, alpha = 0.1) {
this.weights = []; // Pesos do equalizador
this.stepSize = stepSize;
this.alpha = alpha;
this.decisionThreshold = 1; // Limiar de decisão
}
/**
* @method initializeWeights
* @param {number} numTaps - Número de taps.
* @description Inicializa os pesos do equalizador.
*/
initializeWeights(numTaps) {