Skip to content

Commit aef68ed

Browse files
authored
Merge pull request #132 from YuStudy-Inc/GamePage
Game page
2 parents 5d9b2a4 + 1e33ae1 commit aef68ed

File tree

8 files changed

+93
-19
lines changed

8 files changed

+93
-19
lines changed

Backend/config/DatabaseConnection.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import mongoose from 'mongoose';
22
// Uses path of first file to import (should be server.js)
3-
//import dotenv from 'dotenv';
3+
// import dotenv from 'dotenv';
4+
// dotenv.config();
45
//dotenv.config({path: 'Backend/.env'});
56

67
// const DatabaseConnection = async () => {

Backend/controllers/userController.js

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ const passwordMatch = (async(passwordFromUser, savedPasswordFromDB) => {
2121
// const active = user.isOnline;
2222
// return await User.findOneAndUpdate({ username: user.username }, { isOnline: !active })
2323
// })
24-
2524
export const getUser = async(req, res) => {
2625
try {
2726
const userId = req.session.userID;
@@ -577,4 +576,22 @@ export const updateUsersCoins = async (req, res) => {
577576
catch (e) {
578577
res.status(500).json({error: "error fetching user's coins"})
579578
}
579+
}
580+
export const updateUserMonstersSlain = async(req, res) =>{
581+
try{
582+
const userId = req.params.id;
583+
const monstersSlain = req.body.monstersSlain;
584+
const user = await User.findById(userId).select("monstersSlain");
585+
if (!user) {
586+
res.status(404).json({error: "user doesn't exist"})
587+
return
588+
}
589+
const adjust = user.monstersSlain + monstersSlain;
590+
const updatedUsers = await User.findByIdAndUpdate(userId, { monstersSlain : adjust }, { new: true }).select("monstersSlain")
591+
await updatedUsers.save();
592+
res.status(200).json({ monstersSlain: updatedUsers.monstersSlain })
593+
}
594+
catch(e){
595+
res.status(500).json({error: "error updating user's monsters slain"});
596+
}
580597
}

Backend/routes/userRoutes.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ import express from 'express';
22
import { createUser, loginUser, editUser, editUserPassword, deleteUser, getUser, getUsername, getDescription,
33
getActiveFriends, getFriends, getCharacterList, getInventory, getTop10,
44
getFriendRequests, acceptFriendRequest, rejectFriendRequest, sendFriendRequest, updateSelections,
5-
getAICreations, increaseAICreations, getUsersCoins, updateUsersCoins, addCharacterToList, addItemToInventory } from '../controllers/userController.js';
5+
getAICreations, increaseAICreations, getUsersCoins, updateUsersCoins, addCharacterToList, addItemToInventory,
6+
updateUserMonstersSlain} from '../controllers/userController.js';
67

78
const router = express.Router();
89
router.post('/createUser', createUser);
@@ -29,6 +30,7 @@ router.get('/getUsersCoins/:id', getUsersCoins)
2930
router.put('/updateCoins/:id', updateUsersCoins)
3031
router.put('/addCharacter/:id', addCharacterToList)
3132
router.put('/addItem/:id', addItemToInventory)
33+
router.put('/updateMonstersSlain/:id', updateUserMonstersSlain)
3234

3335
/* router.get('/getFriends/:id', getFriendsFromUserID) */
3436
router.get('/', (req, res) => {

Frontend/.env.development

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1-
# VITE_APP_URI=https://00qy8vpnab.execute-api.us-east-1.amazonaws.com/
2-
VITE_APP_URI=http://localhost:3000/
3-
VITE_GAME_URI=https://quizslayergame.s3.us-east-1.amazonaws.com/QuizSlayerBuild/index.html?sessionId
1+
VITE_APP_URI=https://00qy8vpnab.execute-api.us-east-1.amazonaws.com/
2+
VITE_GAME_URI=https://quizslayergame.s3.us-east-1.amazonaws.com/index.html
3+
4+

Frontend/src/Components/Quizzes/QuizCard.jsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ const QuizCard = ({ id, title, url, editThatQuiz, deleteThatQuiz }) => {
66
const navigate = useNavigate();
77

88
const handlePlayClick = () => {
9-
window.location.href = url; // Redirects to external links
9+
localStorage.setItem('quizId', id);
10+
window.location.href = url; // Redirects to external links
1011
};
1112

1213
const handleViewQuiz = () => {

Frontend/src/Pages/GamePage.jsx

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,19 @@ import "../Styles/Pages/GamePage.css";
22
import { useEffect, useState } from "react";
33
import Alert from "../Components/Alert";
44
import UserData from "../UserData";
5+
import axios from "axios"
56
const GAME_URI = import.meta.env.VITE_GAME_URI || ''; // Get the game URI from environment variables
6-
const userId = JSON.parse(localStorage.getItem('id')); // Retrieve user ID from localStorage
7+
const quizId = localStorage.getItem('quizId'); // Retrieve user ID from localStorage
78
const user = JSON.parse(localStorage.getItem('user'));
8-
console.log(user);
9+
import { useNavigate } from "react-router-dom";
910
const GamePage = () => {
11+
const URI = import.meta.env.VITE_APP_URI || '';
12+
const navigate = useNavigate();
1013
const character = user.selectedCharacter;
1114
const weapon = user.selectedWeapon;
1215
const hat = user.selectedHat;
16+
const userId = JSON.parse(localStorage.getItem('id'));
17+
console.log(`${GAME_URI}?sessionId=${quizId}&character=${character}&weapon=${weapon}&hat=${hat}`);
1318
const [showAlert, setShowAlert] = useState(true)
1419
const [alertText, setAlertText] = useState('')
1520
const [gameFinished, setGameFinished] = useState(false);
@@ -23,9 +28,41 @@ const GamePage = () => {
2328
try {
2429
const data = JSON.parse(event.data);
2530
setScore(data.payload.monstersSlain);
26-
setAlertText("Monsters Slain: ", score);
31+
// setAlertText("Monsters Slain: ", score);
32+
localStorage.setItem('results',score )
2733
setShowAlert(true);
2834
setGameFinished(true);
35+
axios({
36+
method: "put",
37+
url: `${URI}users/updateMonstersSlain/${userId}`,
38+
data: {
39+
"monsterSlain": score
40+
},
41+
headers: {
42+
"Content-Type": "application/json"
43+
}
44+
})
45+
.then((response) => {
46+
console.log("Update Success:", response.data);
47+
48+
// Update local storage or UI with new user data if needed
49+
localStorage.setItem('user', JSON.stringify(response.data));
50+
})
51+
.catch((error) => {
52+
const response = error.response;
53+
// alert("It did not work")
54+
if (response) {
55+
console.log(response.data);
56+
console.log(response.status);
57+
console.log(response.headers);
58+
} else if (error.request) {
59+
console.log(error.request);
60+
} else {
61+
console.log("Error", error.message);
62+
}
63+
});
64+
navigate('/results');
65+
2966
// console.log("Data: ", data.payload.monstersSlain);
3067
} catch (err) {
3168
console.warn("Invalid message received:", event.data);
@@ -50,17 +87,17 @@ const GamePage = () => {
5087
<div className="game-page-container">
5188
{!gameFinished && (
5289
<iframe
53-
src={`${GAME_URI}?sessionId=${userId}&character=${character}&weapon=${weapon}&hat=${hat}`}
90+
src={`${GAME_URI}?sessionId=${quizId}&character=${character}&weapon=${weapon}&hat=${hat}`}
5491
style={{ width: "100%", height: "100vh", border: "none" }}
5592
title="My Game"
5693
/>
5794
)}
5895
</div>
59-
{score !== null && (
96+
{/* {score !== null && (
6097
<div className="score-display">
6198
🎉 Final Score: {score}
6299
</div>
63-
)}
100+
)} */}
64101
</>
65102
);
66103
};

Frontend/src/Pages/MainMenu/Quizzes.jsx

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,10 @@ const Quizzes = () => {
3333
const editThatQuiz = (id) => {
3434
navigate(`/editquiz/${id}`)
3535
}
36-
36+
const playThatQuiz = async (quizId) =>{
37+
console.log(quizId);
38+
localStorage.setItem('quizId', quizId);
39+
}
3740
const deleteThatQuiz = async (quizId) => {
3841
console.log(quizId)
3942
try {
@@ -64,15 +67,27 @@ const Quizzes = () => {
6467
<h1 className="todo-quizzes quiz-progress-titles">Todo</h1>
6568
<div className="quizCards">
6669
{quizzes.map((quiz) => !quiz.completed ? (
67-
<QuizCard key={quiz._id} id={quiz._id} userId={userId} title={quiz.title} url="/" editThatQuiz={() => editThatQuiz(quiz._id)} deleteThatQuiz={() => {deleteThatQuiz(quiz._id)}}/>
70+
<QuizCard key={quiz._id}
71+
id={quiz._id} userId={userId}
72+
title={quiz.title}
73+
url="/gamePage"
74+
editThatQuiz={() => editThatQuiz(quiz._id)}
75+
deleteThatQuiz={() => {deleteThatQuiz(quiz._id)}}
76+
/>
6877
) : null )}
6978
</div>
7079
</div>
7180
<div className="container-for-quiz-card">
7281
<h1 className="finished-quizzes quiz-progress-titles">Finished</h1>
7382
<div className="quizCards">
7483
{quizzes.map((quiz) => quiz.completed ? (
75-
<QuizCard key={quiz._id} id={quiz._id} userId={userId} title={quiz.title} url="/" editThatQuiz={() => editThatQuiz(quiz._id)} deleteThatQuiz={() => {deleteThatQuiz(quiz._id)}}/>
84+
<QuizCard key={quiz._id}
85+
id={quiz._id} userId={userId}
86+
title={quiz.title}
87+
url="/gamePage"
88+
editThatQuiz={() => editThatQuiz(quiz._id)}
89+
deleteThatQuiz={() => {deleteThatQuiz(quiz._id)}}
90+
/>
7691
) : null )}
7792
</div>
7893
</div>

Frontend/src/Pages/Results/Results.jsx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,20 @@ import { Podium, ResultCard } from "../../Components/Components"
55
const Results = ({didWin, }) => {
66
const win = "You beat the Quiz!"
77
const lose = "Better luck next time..."
8-
8+
const monstersSlain = localStorage.getItem('score') || 0;
99
return(
1010
<>
1111
<div className="results-container">
1212
<div className="results-title">
13-
<h1>{didWin ? win : lose}</h1>
13+
<h1>{monstersSlain>=2 ? win : lose}</h1>
1414
</div>
1515
<div className="show-results">
1616
<div className="container-for-cards-and-character">
1717
<div className="container-for-podium-results-page">
1818
<Podium />
1919
</div>
2020
<div className="container-for-result-card">
21-
<ResultCard didWin={true} coins={"27"} monsters={"3"} xp={"87"} lvl={"9"}/>
21+
<ResultCard didWin={true} coins={"27"} monsters={monstersSlain} xp={"87"} lvl={"9"}/>
2222
</div>
2323
</div>
2424
</div>

0 commit comments

Comments
 (0)