-
Notifications
You must be signed in to change notification settings - Fork 24
/
script2.js
681 lines (557 loc) · 19.5 KB
/
script2.js
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
const params = new URLSearchParams(window.location.search);
const id = parseInt(params.get("id"));
// console.log(id);
const colors = {
fire: "#e03a3a",
grass: "#50C878",
electric: "#fad343",
water: "#1E90FF",
ground: "#735139",
rock: "#63594f",
fairy: "#EE99AC",
poison: "#b34fb3",
bug: "#A8B820",
dragon: "#fc883a",
psychic: "#882eff",
flying: "#87CEEB",
fighting: "#bf5858",
normal: "#D2B48C",
ghost: "#7B62A3",
dark: "#414063",
steel: "#808080",
ice: "#98D8D8",
};
const main_types = Object.keys(colors);
// const getPokeApi = async (url)=>{
// await fetch(url)
// .then(
// async response => {
// let isJson = response.headers.get('content-type')?.includes('application/json');
// let data = isJson ? await response.json() : null;
// // check for error response
// if (!response.ok) {
// // get error message from body or default to response status
// const error = (data && data.message) || response.status;
// return Promise.reject(error);
// }
// // element.innerHTML = JSON.stringify(data, null, 4);
// })
// .catch(error => {
// // element.parentElement.innerHTML = `Error: ${error}`;
// console.error('There was an error!', error);
// });
// }
const getType_data = async(url)=>{
let res = await fetch(url);
let data = await res.json();
return data;
}
const fetchPokemonDetails = async () => {
const url = `https://pokeapi.co/api/v2/pokemon/${id}/`;
const url2 = `https://pokeapi.co/api/v2/pokemon-species/${id}/`;
//changing the api so that the query is pokemon specific
// const url3 = `https://pokeapi.co/api/v2/type/${id}/`;
const res = await fetch(url);
const res2 = await fetch(url2);
const data = await res.json();
const data2 = await res2.json();
// get the type of pokemon
let type_names = data.types.map((val, index)=>val.type.name)
// console.log(data.types);
let data3 = type_names.map( async (val) => {
return await getType_data(`https://pokeapi.co/api/v2/type/${val}/`)
})
// console.log(type_names);
const arr = [data, data2, data3];
await displayPokemonDetails(arr);
// console.log(arr);
};
const displayPokemonDetails = async (pokemon) => {
const name = pokemon[0].name[0].toUpperCase() + pokemon[0].name.slice(1);
const japaneseName = pokemon[1].names[0].name;
const id = pokemon[0].id.toString().padStart(3, "0");
const imageSrc = pokemon[0].sprites.other.dream_world.front_default;
const imageSrc2 = pokemon[0].sprites.other["official-artwork"].front_default;
const poke_types = pokemon[0].types.map((type) => type.type.name);
const type = main_types.find((type) => poke_types.indexOf(type) > -1);
const color = colors[type];
const hp = pokemon[0].stats[0].base_stat;
// const maxHp = hp * 2 + 204;
// const minHp = hp * 2 + 110;
const attack = pokemon[0].stats[1].base_stat;
// const maxAttack = Math.floor((attack * 2 + 99) * 1.1);
// const minAttack = Math.floor((attack * 2 + 5) * 0.9);
const spAttack = Math.floor(pokemon[0].stats[3].base_stat);
// const maxSpAttack = Math.floor((spAttack * 2 + 99) * 1.1);
// const minSpAttack = Math.floor((spAttack * 2 + 5) * 0.9);
const spDefense = Math.floor(pokemon[0].stats[4].base_stat);
// const maxSpDefense = Math.floor((spDefense * 2 + 99) * 1.1);
// const minSpDefense = Math.floor((spDefense * 2 + 5) * 0.9);
const defense = pokemon[0].stats[2].base_stat;
// const maxDefense = Math.floor((defense * 2 + 99) * 1.1);
// const minDefense = Math.floor((defense * 2 + 5) * 0.9);
const speed = pokemon[0].stats[5].base_stat;
// const maxSpeed = Math.floor((speed * 2 + 99) * 1.1);
// const minSpeed = Math.floor((speed * 2 + 5) * 0.9);
const abilities = pokemon[0].abilities.map((ability) => ability.ability.name);
const eggGroups = pokemon[1].egg_groups.map((group) => group.name);
// const moves = pokemon[0].moves.map((move) => move.move.name);
document.body.style.backgroundColor = color;
const evolutionChainUrl = pokemon[1].evolution_chain.url;
const resEvolutionChain = await fetch(evolutionChainUrl);
const evolutionChainData = await resEvolutionChain.json();
// console.log(evolutionChainData);
const varieties = pokemon[1].varieties
.map((variety) => {
if (variety.is_default === true) {
return null; // or return undefined;
}
return variety.pokemon;
})
.filter((item) => item !== null); // Remove null items from the array
// console.log(varieties);
const resVarieties = await Promise.all(
varieties.map((variety) => fetch(variety.url))
);
const varietiesData = await Promise.all(
resVarieties.map((res) => res.json())
);
// console.log(varietiesData);
let tab3 = document.getElementById("tab_3");
tab3.innerHTML = `
<div class="evolution">
</div>
<div class="varieties">
</div>
`;
const displayVarieties = (varietiesData) => {
const container = document.querySelector(".varieties");
container.innerHTML = "";
varietiesData.forEach((variety) => {
const pokemonName = variety.name;
const imgUrl = variety.sprites.other["official-artwork"].front_default;
const pokemonDiv = document.createElement("div");
pokemonDiv.classList.add("varieties__pokemon");
const nameElement = document.createElement("h1");
nameElement.textContent = pokemonName;
pokemonDiv.appendChild(nameElement);
const imageElement = document.createElement("img");
imageElement.src = imgUrl;
pokemonDiv.appendChild(imageElement);
container.appendChild(pokemonDiv);
});
};
displayVarieties(varietiesData);
const displayEvolutionChain = (evolutionChainData) => {
const container = document.querySelector(".evolution");
container.innerHTML = "";
const chain = evolutionChainData.chain;
displayEvolutionRecursive(chain, container);
};
const displayEvolutionRecursive = (chain, container) => {
try{
const pokemonName = chain.species.name;
const imgUrl = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/${getPokemonIdFromURL(
chain.species.url
)}.png`;
const EvolutionId = getPokemonIdFromURL(chain.species.url);
const pokemonDiv = document.createElement("div");
pokemonDiv.classList.add("evolution__pokemon");
const iconDiv = document.createElement("div");
const nameElement = document.createElement("h1");
nameElement.textContent = pokemonName;
pokemonDiv.appendChild(nameElement);
const imageElement = document.createElement("img");
imageElement.src = imgUrl;
pokemonDiv.appendChild(imageElement);
imageElement.addEventListener("click", () => {
window.location.href = `details.html?id=${EvolutionId}}`;
});
if (chain.evolves_to.length > 0) {
const arrowIndicator = document.createElement("i");
arrowIndicator.classList.add(
"fa-solid",
"fa-caret-right",
"fa-2x",
"fa-beat"
);
iconDiv.appendChild(arrowIndicator);
}
container.appendChild(pokemonDiv);
container.appendChild(iconDiv);
if (chain.evolves_to.length > 0) {
const evolutionData = chain.evolves_to[0];
displayEvolutionRecursive(evolutionData, container);
}
}
catch(err){
console.log(err);
}
};
function getPokemonIdFromURL(url) {
const parts = url.split("/");
return parts[parts.length - 2];
}
displayEvolutionChain(evolutionChainData);
if(pokemon[2] != null){
var weakTypesString='';
var strongTypesString='';
pokemon[2].map(async (val)=>{
val.then((res)=>{
// console.log(res);
let weakTypes=[res.damage_relations.no_damage_to.map((type)=>{
return `<img src="./Icons/${type.name}.svg" alt="test images" class="${type.name} poke_type_bg"></img>`
})]
// var weakTypesString='';
for(let i in weakTypes){
weakTypesString += weakTypes[i];
}
let strongTypes=[res.damage_relations.double_damage_to.map((type)=>{
return `<img src="./Icons/${type.name}.svg" alt="test images" class="${type.name} poke_type_bg"></img>`
})]
// var strongTypesString='';
for(let i in strongTypes){
strongTypesString += strongTypes[i];
}
let tab2 = document.getElementById("tab_2");
tab2.innerHTML = `
<div class="stats">
<div class="stat">
<div>
<span> Health:</span>
<span>${hp}</span>
</div>
<meter id="hp"
style="content: 'HP';"
min="0" max="255"
low="70" high="120" optimum="150"
value="${hp}">
</meter>
</div>
<div class="stat">
<div>
<span> Attack:</span>
<span>${attack}</span>
</div>
<meter id="attack"
min="0" max="255"
low="70" high="120" optimum="150"
value="${attack}">
</meter>
</div>
<div class="stat">
<div>
<span> Defense:</span>
<span>${defense}</span>
</div>
<meter id="defense"
min="0" max="255"
low="70" high="120" optimum="150"
value="${defense}">
</meter>
</div>
<div class="stat">
<div>
<span> Sp. Atk:</span>
<span>${spAttack}</span>
</div>
<meter id="spattack"
min="0" max="255"
low="70" high="120" optimum="150"
value="${spAttack}">
</meter>
</div>
<div class="stat">
<div>
<span> Sp. Def:</span>
<span>${spDefense}</span>
</div>
<meter id="spdefense"
min="0" max="255"
low="70" high="120" optimum="150"
value="${spDefense}">
</meter>
</div>
<div class="stat">
<div>
<span>Speed:</span>
<span>${speed}</span>
</div>
<meter id="speed"
min="0" max="255"
low="70" high="120" optimum="150"
value="${speed}">
</meter>
</div>
<div class="stat">
<div>
<span> Total:</span>
<span>${speed + hp + attack + defense + spAttack + spDefense}</span>
</div>
<meter id="total"
min="0" max="1530"
low="500" high="720" optimum="1000"
value="${speed + hp + attack + defense + spAttack + spDefense}">
</meter>
</div>
<div class="statTypes">
<div class="statTypeText">
<div>
Weak Against
</div>
</div>
<div class="statIconHolder">
${weakTypesString==""?'None':weakTypesString}
</div>
</div>
<div class="statTypes">
<div class="statTypeText">
<span>
Strong Against
</span>
</div>
<div class="statIconHolder">
${strongTypesString==""?'None':strongTypesString}
</div>
</div>
`;
})
})
// let weakTypes=[...pokemon[2].damage_relations.no_damage_to.map((type)=>{
// return `<img src="./Icons/${type.name}.svg" alt="test images" class="${type.name} poke_type_bg"></img>`
// })]
// var weakTypesString='';
// for(let i in weakTypes){
// weakTypesString=weakTypesString+weakTypes[i];
// }
// let strongTypes=[...pokemon[2].damage_relations.double_damage_to.map((type)=>{
// return `<img src="./Icons/${type.name}.svg" alt="test images" class="${type.name} poke_type_bg"></img>`
// })]
// var strongTypesString='';
// for(let i in strongTypes){
// strongTypesString=strongTypesString+strongTypes[i];
// }
// let tab2 = document.getElementById("tab_2");
// tab2.innerHTML = `
// <div class="stats">
// <div class="stat">
// <div>
// <span> Health:</span>
// <span>${hp}</span>
// </div>
// <meter id="hp"
// style="content: 'HP';"
// min="0" max="255"
// low="70" high="120" optimum="150"
// value="${hp}">
// </meter>
// </div>
// <div class="stat">
// <div>
// <span> Attack:</span>
// <span>${attack}</span>
// </div>
// <meter id="attack"
// min="0" max="255"
// low="70" high="120" optimum="150"
// value="${attack}">
// </meter>
// </div>
// <div class="stat">
// <div>
// <span> Defense:</span>
// <span>${defense}</span>
// </div>
// <meter id="defense"
// min="0" max="255"
// low="70" high="120" optimum="150"
// value="${defense}">
// </meter>
// </div>
// <div class="stat">
// <div>
// <span> Sp. Atk:</span>
// <span>${spAttack}</span>
// </div>
// <meter id="spattack"
// min="0" max="255"
// low="70" high="120" optimum="150"
// value="${spAttack}">
// </meter>
// </div>
// <div class="stat">
// <div>
// <span> Sp. Def:</span>
// <span>${spDefense}</span>
// </div>
// <meter id="spdefense"
// min="0" max="255"
// low="70" high="120" optimum="150"
// value="${spDefense}">
// </meter>
// </div>
// <div class="stat">
// <div>
// <span>Speed:</span>
// <span>${speed}</span>
// </div>
// <meter id="speed"
// min="0" max="255"
// low="70" high="120" optimum="150"
// value="${speed}">
// </meter>
// </div>
// <div class="stat">
// <div>
// <span> Total:</span>
// <span>${speed + hp + attack + defense + spAttack + spDefense}</span>
// </div>
// <meter id="total"
// min="0" max="1530"
// low="500" high="720" optimum="1000"
// value="${speed + hp + attack + defense + spAttack + spDefense}">
// </meter>
// </div>
// <div class="statTypes">
// <div class="statTypeText">
// <div>
// Weak Against
// </div>
// </div>
// <div class="statIconHolder">
// ${weakTypesString==""?'None':weakTypesString}
// </div>
// </div>
// <div class="statTypes">
// <div class="statTypeText">
// <span>
// Strong Against
// </span>
// </div>
// <div class="statIconHolder">
// ${strongTypesString==""?'None':strongTypesString}
// </div>
// </div>
// `;
}
else{
console.log(pokemon[2])
}
let pokemonDetailsEl = document.getElementById("pokemon-details");
pokemonDetailsEl.innerHTML = `
<div class="btn">
<button class="previousBtn" onclick="backButton()"><i class="fas fa-chevron-left"></i></button>
<button class="nextBtn" onclick="nextPokemon()"><i class="fas fa-chevron-right"></i></button>
</div>
<div class="names">
<div class="japaneseName">${japaneseName}</div>
<div class="name">${name}</div>
</div>
<div class="top">
<div class="image">
<img class="imgFront" src="${
imageSrc == null ? imageSrc2 : imageSrc
}" alt="${name}">
<img class="imgBack" src="./Icons/default/pokeball.svg" alt="pokeball">
</div>
</div>
`;
const desiredLanguage = "en";
let overview = "Sorry, no description available.";
let genus = "Sorry, no description available.";
for (const entry of pokemon[1].flavor_text_entries) {
if (entry.language.name === desiredLanguage) {
// Replace "\f" with a space in the flavor text
overview = entry.flavor_text.replace("\f", " ");
break; // Stop the loop once we find the English flavor text
}
}
for (const entry of pokemon[1].genera) {
if (entry.language.name === desiredLanguage) {
genus = entry.genus;
break;
}
}
const height = pokemon[0].height / 10 + "m";
const weight = pokemon[0].weight / 10 + "kg";
const genderRate = pokemon[1].gender_rate;
let male = "";
let female = "";
if (genderRate === -1) {
male = "??";
female = "??";
} else if (genderRate === 0) {
male = "100%";
female = "0%";
} else if (genderRate === 8) {
male = "0%";
female = "100%";
} else {
female = (genderRate / 8) * 100 + "%";
male = 100 - (genderRate / 8) * 100 + "%";
}
const friendship = pokemon[1].base_happiness;
const catchRate = pokemon[1].capture_rate;
let tab1 = document.getElementById("tab_1");
tab1.innerHTML = `
<div>
<div class="overview">
<p><span class="genus">${genus}</span><br>${overview}</p>
<div class="heightWeight">
<span>Height:<br><b>${height}</b></span>
<span>Weight:<br><b>${weight}</b></span>
</div>
<div class="types">
${poke_types
.map(
(type) => `
<div class="poke__type__bg ${type}">
<img src="Icons/${type}.svg" alt="Type">
</div>
`
)
.join("")}
</div>
</div>
<div class="about">
<div>Id: <b class="id">#${id}</b></div>
<div>Gender: <b><i class="fa-solid fa-mars" style="color: #1f71ff;"></i>${male} <i class="fa-solid fa-venus" style="color: #ff5c74;"></i>${female}</b></div>
<span>Abilities: <b>${abilities.join(", ")}</b></span>
<span>Catch Rate: <b>${catchRate} (${((catchRate / 255) * 100).toFixed(
2
)}% chance)</b></span>
<span>Base Friendship: <b>${friendship} (${
friendship < 50 ? "lower" : friendship < 100 ? "normal" : "higher"
})</b></span>
<span>Base Exp: <b>${pokemon[0].base_experience}</b></span>
<span>Growth Rate: <b>${pokemon[1].growth_rate.name}</b></span>
<span>Egg Groups: <b>${eggGroups.join(", ")}</b></span>
</div>
`;
};
const tabs = document.querySelectorAll("[data-tab-value]");
const tabsContainer = document.querySelector(".tabs");
const tabInfos = document.querySelectorAll("[data-tab-info]");
tabs.forEach((tab) => {
tab.addEventListener("click", () => {
const target = document.querySelector(tab.dataset.tabValue);
tabInfos.forEach((tabInfo) => {
tabInfo.classList.remove("active");
});
target.classList.add("active");
target.scrollIntoView({ behavior: "smooth" });
});
});
const nextPokemon = (e) => {
window.location.href = `details.html?id=${id + 1}`;
e.preventDefault();
};
const backButton = (e) => {
window.history.back();
e.preventDefault();
};
fetchPokemonDetails();
//preloader
window.addEventListener("load", function () {
document.querySelector("body").classList.add("loaded");
});