phaser-game-bs/src/pages/cross/v3.astro

566 lines
26 KiB
Plaintext

---
import Layout from "../../layouts/Layout.astro";
---
<Layout title="">
<!-- bg-[url('/assets/customBG.jpg')] bg-cover bg-center -->
<main>
<div class="">
<section class="bg-white bg-center bg-no-repeat bg-cover h-screen">
<div class="shadow-md">
<div class="container mx-auto px-4 flex flex-row place-content-between pt-6">
<div>
<img src="/assets/top_logo.svg" alt="" draggable="false" class="select-none">
</div>
<div class="flex flex-row space-x-1 pb-2">
<button onclick="audioPlayAndPause()"><img src="/assets/svg/mute.svg" alt=""></button>
<button onclick="retryGame()"><img src="/assets/svg/reset.svg" alt=""></button>
<button onclick="saveUserData();"><img src="/assets/svg/tick2.svg" alt=""></button>
<button onclick="history.back();"><img src="/assets/svg/cancel.svg" alt=""></button>
</div>
</div>
<!-- <input onclick="saveUserData();" class="bg-blue-700 px-8 py-2 rounded-lg shadow-lg font-bold text-white cursor-pointer" type="submit" value="Submit"> -->
</div>
<div class="container mx-auto px-4" id="snapshotDiv">
<div class="flex flex-col">
<p class="sm:text-2xl md:text-3xl lg:text-4xl text-center font-[600] text-[#60C6CB] my-4 select-none" id="gameDescription"></p>
<!-- <p id="LearningSubArea"></p> -->
</div>
<div class="flex flex-col justify-center place-items-center ">
<img class="sm:w-[70%] md:w-[30%] lg:w-[30%]" draggable="false" id="descImage" src="" alt="" />
<p class="text-2xl lg:text-4xl text-center font-[600] text-[#7c4c23] mb-0 select-none " id="gameLabel"></p>
</div>
<form id="contactForm" class="">
<div id="itemForm" class="">
<div class="flex flex-row gap-4 place-content-between">
<div class="flex flex-col place-items-center">
<label for="a1" class="round-checkbox-label">
<img id="image1" src="" alt="" draggable="false" class="select-none" style="width: 170px;"/>
<p id="label1"></p>
</label>
<input onclick="checkResult2('image1');" type="checkbox" id="a1" class="round-checkbox-input myCheckbox largerCheckbox" value="a1"/>
</div>
<div class="flex flex-col place-items-center">
<label for="a2" class="round-checkbox-label">
<img id="image2" src="" alt="" draggable="false" class="select-none" style="width: 170px;"/>
<p id="label2"></p>
</label>
<input onclick="checkResult2('image2');" type="checkbox" id="a2" class="round-checkbox-input myCheckbox largerCheckbox" value="a2"/>
</div>
<div class="flex flex-col place-items-center">
<label for="a3" class="round-checkbox-label">
<img id="image3" src="" alt="" draggable="false" class="select-none" style="width: 170px;"/>
<p id="label3"></p>
</label>
<input onclick="checkResult2('image3');" type="checkbox" id="a3" class="round-checkbox-input myCheckbox largerCheckbox" value="a3"/>
</div>
</div>
</div>
<div class="flex flex-col place-items-center justify-center pt-4">
<p class="text-[20px] font-[600] text-[#FFFFFF] bg-[#004aad] px-[20px] py-[10px]" style="display: none;" id="savedMessage"></p>
<!-- <input onclick="saveUserData();" class="bg-blue-700 px-8 py-2 rounded-lg shadow-lg font-bold text-white cursor-pointer" type="submit" value="Submit"> -->
</div>
</form>
</div>
</section>
</div>
<div class="absolute inset-0" style="display: none;" id="allParentDiv">
<div id="loadingMainContainer" class="w-full h-screen bg-[#00000070] absolute" style="display: none;">
<div id="loadingState" style="display: none;" class="bg-white flex text-[#000] absolute left-1/2 top-1/2 -translate-y-1/2 -translate-x-1/2 max-w-lg flex-col rounded-[8px] items-center space-y-2 w-full px-6 py-16">
</div>
</div>
<div id="scoreBoard" class=" w-full h-screen bg-[#00000070] absolute" style="display: none;">
<div class="flex absolute left-1/2 top-1/2 -translate-y-1/2 -translate-x-1/2 max-w-lg flex-col rounded-[8px] bg-white space-y-2 w-full p-6" >
<div class="flex flex-row space-x-4 items-center justify-center">
<div id="star-container" class="relative inline-flex items-center justify-center">
<img src="/assets/bg-star.svg" alt="" class="block" />
<p id="get-star-value" class="absolute inset-0 flex items-center justify-center text-[#E76408] text-[40px] font-[900]"></p>
</div>
</div>
<div class="flex flex-row" style="margin-top: 15px; margin-bottom: 15px;">
<img class="z-10" src="/assets/clip-art.svg" alt="" />
<p id="starFeedbackMessage" class="text-[#0348A8] text-[12px] font-[700] p-6 rounded-[10px] -ml-[10px]" style="background: linear-gradient(270.05deg, #FFFFFF 4.67%, #DAEAFF 99.61%);"></p>
</div>
<div class="flex flex-col w-full max-w-sm items-center justify-center mx-auto gap-3">
<button onclick="history.back();" class="rounded-[4px] bg-[#0348A8] text-[#FFF] text-[12px] font-[700] p-2.5 w-full border-[1px] border-[#0348A8]">Wow, Lets Go</button>
<button onclick="retryGame()" class="border-[1px] border-[#0348A8] p-2.5 rounded-[4px] text-[#0348A8] w-full">Try Again</button>
</div>
</div>
</div>
<div class="clip-art-container absolute bottom-0 right-0 hidden">
<img src="/assets/svg/clip-art2.svg" alt="Clip Art" class="clip-art">
</div>
</div>
<div>
<audio id="audioPlayer" controls class="hidden">
<source id="instrucAudio1" src="" type="audio/ogg">
<source id="instrucAudio2" src="" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</div>
</main>
</Layout>
<script is:inline src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script is:inline>
let isPlaying = false;
function audioPlayAndPause(){
if(isPlaying === false){
document.getElementById('audioPlayer').play();
isPlaying = true;
}else if(isPlaying === true){
document.getElementById('audioPlayer').pause();
document.getElementById('audioPlayer').currentTime = 0;
isPlaying = false;
}
}
function retryGame(){
window.location.reload();
}
const params = new URLSearchParams(window.location.search);
const gameId = params.get('id');
const userId = params.get('studentId');
const gameName = params.get('gameName');
const assignmentId = params.get('assignmentId');
const worksheetId = params.get('worksheetId');
let startTime = Date.now();
let gameData = null;
let totalPoints = 0;
let wrongCount = 0;
let url = window.location.href;
let urlSplit = url.split('/');
// let gameName = urlSplit[3] + '-' + urlSplit[4].split('?')[0];
let progress = 0;
const progressBar = document.createElement('div');
let totalCorrectFromApi = 0;
fetch(`https://game-du.teachertrainingkolkata.in/items/game_cross_varient3/${encodeURIComponent(gameId)}?filter[status][_eq]=published`)
.then(res => res.json())
.then(data => {
gameData = data.data;
let audioLink = `https://game-du.teachertrainingkolkata.in/assets/${gameData.instruction}.mp3`;
document.getElementById('instrucAudio1').src = audioLink;
document.getElementById('instrucAudio2').src = audioLink;
document.querySelector('audio').load();
// console.log(gameData)
document.getElementById("gameLabel").innerHTML = gameData.label;
document.getElementById("gameDescription").innerHTML = gameData.description;
if(gameData.label1, gameData.label2, gameData.label3){
document.getElementById("label1").innerHTML = gameData.label1;
document.getElementById("label2").innerHTML = gameData.label2;
document.getElementById("label3").innerHTML = gameData.label3;
}
const assetsURL = 'https://game-du.teachertrainingkolkata.in/assets/';
document.getElementById('descImage').src = assetsURL + gameData.descript_img;
for (let i = 1; i <= 3; i++) {
const imageId = `image${i}`;
if(gameData[imageId]){
document.getElementById(imageId).src = assetsURL + gameData[imageId];
}
}
});
function showClipArt() {
const clipArtContainer = document.querySelector('.clip-art-container');
clipArtContainer.classList.remove('hidden');
clipArtContainer.classList.add('slide-in');
}
function addStarScalingStyles() {
const style = document.createElement('style');
style.innerHTML = `
@keyframes scaleUp {
0% {
transform: scale(1.5);
}
100% {
transform: scale(1);
}
}
.star {
display: inline-block;
transform-origin: center;
transform: scale(0); /* Initial state before animation */
opacity: 0; /* Initial opacity */
animation: scaleUp 0.5s ease forwards;
}
`;
document.head.appendChild(style);
}
function progressIncrement() {
const interval = setInterval(() => {
if (progress >= 100) {
clearInterval(interval);
} else {
progress += 10;
progressBar.style.width = `${progress}%`;
}
}, 100);
}
function checkResult2(id) {
const checkbox = document.getElementById('a' + id.slice(-1));
const element = document.getElementById(id);
if (checkbox.checked) {
if (gameData[id.replace('image', 'a')] === true) {
element.classList.add('redBorder');
} else {
element.classList.add('greenBorder');
wrongCount += 1;
}
} else {
wrongCount -= 1;
element.classList.remove('redBorder', 'greenBorder');
}
}
function saveUserData() {
document.getElementById('allParentDiv').style.display = 'block';
const endTime = Date.now();
const timeDifference = endTime - startTime;
const timeDifferenceInSeconds = timeDifference / 1000;
// Get checkbox values and corresponding elements
const checkboxes = ['a1', 'a2', 'a3'];
const checkboxValues = checkboxes.map(id => {
const checkbox = document.getElementById(id);
const element = document.getElementById('image' + id.slice(-1));
return {
id: id,
checked: checkbox.checked,
element: element
};
});
// Count points based on checkbox values and "greenBorder" class
checkboxValues.forEach(checkbox => {
if (checkbox.checked && checkbox.element.classList.contains('redBorder')) {
totalPoints += 1;
}
});
const answersList = ['a1', 'a2', 'a3'];
answersList.forEach((answer) => {
if (gameData[answer] === true) {
totalCorrectFromApi++;
}
});
let afterNegative = totalPoints - wrongCount;
let percentage = Math.round((afterNegative / totalCorrectFromApi ) * 10);
if(percentage <= 3){
percentage = 3
}
let feedbackMessage = '';
if (percentage >= 1 && percentage <= 3) {
feedbackMessage = "You're making progress! Let's keep going!";
} else if (percentage >= 4 && percentage <= 6) {
feedbackMessage = "Nice work! You're improving every day!";
} else if (percentage >= 7 && percentage <= 8) {
feedbackMessage = "Amazing work! Keep it up!";
} else if (percentage >= 9 && percentage <= 10) {
feedbackMessage = "Outstanding! You're a true superstar!";
} else {
feedbackMessage = "Invalid star value.";
}
progressIncrement();
addStarScalingStyles();
showClipArt();
const starContainer = document.getElementById('star-container');
let scoreBoard = document.getElementById('scoreBoard');
let loadingMainContainer = document.getElementById('loadingMainContainer');
loadingMainContainer.style.display = 'flex';
const loadingDiv = document.getElementById('loadingState');
loadingDiv.style.display = 'flex';
const containerDiv = document.createElement('div');
containerDiv.classList.add('w-full');
containerDiv.style.display = 'flex';
containerDiv.style.flexDirection = 'column';
containerDiv.style.justifyContent = 'center';
containerDiv.style.alignItems = 'center';
const paragraph = document.createElement('p');
paragraph.textContent = 'HOLD ON.';
paragraph.style.fontSize = '16px';
paragraph.style.fontWeight = '600';
paragraph.style.color = 'rgba(0, 0, 0, 0.38)';
containerDiv.appendChild(paragraph);
const progressBarContainer = document.createElement('div');
progressBarContainer.style.position = 'relative';
progressBarContainer.style.display = 'flex';
progressBarContainer.style.alignItems = 'center';
progressBarContainer.style.border = '1px solid #AFB8E6';
progressBarContainer.style.height = '10px';
progressBarContainer.style.width = '100%';
progressBarContainer.style.marginTop = '30px';
progressBarContainer.style.marginBottom = '30px';
containerDiv.appendChild(progressBarContainer);
progressBar.style.height = '10px';
progressBar.style.backgroundColor = '#D7DCF2';
progressBar.style.width = '0%';
progressBarContainer.appendChild(progressBar);
loadingDiv.appendChild(containerDiv);
const calculationText = document.createElement('p');
calculationText.textContent = 'Your stars are being calculated...';
calculationText.style.fontSize = '14px';
calculationText.style.fontWeight = '600';
calculationText.style.color = 'rgba(0, 0, 0, 0.38)';
containerDiv.appendChild(calculationText);
let snapImage = '';
const div = document.getElementById("snapshotDiv");
const images = div.getElementsByTagName('img');
let loadedImagesCount = 0;
for (let img of images) {
if (img.complete) {
loadedImagesCount++;
} else {
img.onload = () => {
loadedImagesCount++;
if (loadedImagesCount === images.length) {
takeSnapshot();
}
};
}
}
if (loadedImagesCount === images.length) {
takeSnapshot();
}
async function takeSnapshot() {
try {
const canvas = await html2canvas(div, {
useCORS: true,
allowTaint: true,
});
snapImage = canvas.toDataURL("image/jpeg");
await saveScreenshot(snapImage);
} catch (error) {
console.error('Error in takeSnapshot:', error.message || error);
}
}
async function saveScreenshot(snapImage) {
const saveUserDataForScreenshot = {
gameName: gameName,
gameID: gameId,
screenShot: snapImage,
userId: userId,
gameTime: timeDifferenceInSeconds
};
try {
const saveResponse = await fetch('https://api.teachertrainingkolkata.in/api/saveGalleryImage', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(saveUserDataForScreenshot),
});
if (!saveResponse.ok) {
const errorDetails = await saveResponse.text();
console.error(`SaveGalleryImage failed: ${saveResponse.status} ${saveResponse.statusText}`);
console.error('Response Body:', errorDetails);
throw new Error(`Failed to save screenshot: ${saveResponse.statusText}`);
}
const saveResult = await saveResponse.json();
if (saveResult.screenshotUrl) {
let userData = {
'gameName': gameName,
'gameID': gameId,
'userId': userId,
'gameTime': timeDifferenceInSeconds,
'score': totalPoints,
'gameStar': percentage
};
fetch(`https://api.teachertrainingkolkata.in/api/saveGameScore2`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(userData)
})
.then(response => {
if (response.ok) {
setTimeout(() => {
if (response.ok) {
if (response.status == 200) {
document.getElementById('allParentDiv').style.display = 'block';
loadingMainContainer.style.display = 'none';
loadingDiv.style.display = 'none';
starContainer.style.display = 'flex';
starContainer.style.flexDirection = 'row';
document.getElementById('starFeedbackMessage').innerHTML = feedbackMessage;
document.getElementById('get-star-value').innerHTML = percentage;
scoreBoard.style.display = 'flex';
}
} else {
console.log('Something went wrong', response);
}
}, 100);
} else {
// console.log('Something Wrong', response);
}
})
.catch(error => {
console.error('An error occurred', error);
});
const userAnotherData = {
assignmentId: assignmentId,
worksheetId: worksheetId,
studentId: userId,
submissionFile: saveResult.screenshotUrl,
};
const authToken = 'Bearer eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkZW50aXR5SWQiOiI2NjNjNGMzNjRiNmYzZjU0YmExZjcxMTUiLCJfaWQiOiI2NjNjNGMzNjBiOWYyZDk5MGQyNWYwYjMiLCJ0eXBlIjoiQUtBREVNWSIsImRldmljZUlkIjoiMDBqNXJtODl5b3BvNjh1a2Yyb2c5cTdoIn0sImlhdCI6MTczNjM5ODkwNCwiZXhwIjoxNzM3MDAzNzA0LCJpc3MiOiJidXp6T25lIn0.vhH0zTkVisnbK6n5aPgV3RrtmpP095Gtz6ayUc29XerEV-XPVhYwg06JQnm2FWGPtadEJ2Ea5z6_YNp5Kz9DENL9LxpYYuXRUOGvMEaVM5YZOYQ88viqxM7SIvxElIsc8cQeJr5v-4ov4MyOuXws7R5MDDO2PuzYdwaA52GXbQ0LO3aFGOQL7nWPKVYqFWCQe_T-1JphbsGStHivcmUy8_DAdjs0VpXFJKiQm6jcWQO3j3uOUJSi14af4ZvrUPkjIT92OOHiZTL7CUbbFt4yktnw3Gm2Fv6lS5pamSJpVJnGJQ6ebjd70IXnE49Mn9IK9AssnjTBh2DaNeVc0C1z9Q'; // Your token
try {
const submitResponse = await fetch('https://preschool-curriculum.in/api/one/v1/akademy/worksheet/submissions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': authToken,
},
body: JSON.stringify(userAnotherData),
});
if (!submitResponse.ok) {
const errorDetails = await submitResponse.text();
console.error(`SubmitWorksheet failed: ${submitResponse.status} ${submitResponse.statusText}`);
console.error('Response Body:', errorDetails);
throw new Error(`Failed to submit worksheet: ${submitResponse.statusText}`);
}
const submitResult = await submitResponse.json();
// console.log('SubmitWorksheet API success:', submitResult);
} catch (error) {
console.error('Error in SubmitWorksheet API call:', error.message || error);
}
} else {
console.error('SaveGalleryImage did not return a valid screenshotUrl:', saveResult);
}
} catch (error) {
console.error('Error in saveScreenshot:', error.message || error);
throw error;
}
}
}
document.addEventListener('DOMContentLoaded', function () {
const contactForm = document.getElementById('contactForm');
contactForm.addEventListener('submit', async function (event) {
event.preventDefault();
});
});
</script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Lobster&family=Quicksand:wght@500;700&display=swap');
input[type="checkbox"]{
-webkit-appearance: initial;
appearance: initial;
border: 1px solid gray;
border-radius: 5px;
/* background: gray; */
width: 40px;
height: 40px;
position: relative;
}
input[type="checkbox"]:checked {
background: #FF0000;
}
input[type="checkbox"]:checked:after {
border: none;
content: "X";
color: #fff;
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%,-50%);
-moz-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
/*
* If you want to fully change the check appearance, use the following:
* content: " ";
* width: 100%;
* height: 100%;
* background: blue;
* top: 0;
* left: 0;
*/
}
body{
font-family: Quicksand;
}
input.largerCheckbox {
/* width: 40px; */
height: 40px;
cursor: pointer;
}
.greenBorder{
border: 4px solid #008000;
border-radius: 10%;
transition: border 0.5s, border-color 0.3s, transform 6s;
}
.redBorder{
border: 4px solid red;
border-radius: 10%;
transition: border 0.5s, border-color 0.3s, transform 6s;
}
#image1, #image2, #image3, #image4, #image5, #image6{
width: 250px;
}
#label1, #label2, #label3, #label4, #label5, #label6{
text-align: center;
font-weight: bold;
color: #7C4C23;
padding-top: 10px;
}
#LearningArea, #LearningSubArea{
font-size: 20px;
color: #7C4C23;
font-weight: bold;
}
.round-checkbox-label {
display: inline-block;
cursor: pointer;
position: relative;
transition: background-color 0.3s, border-color 0.3s, transform 0.3s;
}
.round-checkbox-input:checked + .round-checkbox-label {
border-radius: 30%;
}
.round-checkbox-input:checked + .round-checkbox-label::after {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 40px;
display: block;
}
.hidden {
display: none;
transform: translateX(100%);
}
.slide-in {
display: block;
animation: slideIn 0.5s forwards;
}
@keyframes slideIn {
0% {
transform: translateX(100%);
opacity: 0;
}
100% {
transform: translateX(0);
opacity: 1;
}
}
</style>