From f3d3ef6fe3fc966737b50c33418feb621f1e2ea9 Mon Sep 17 00:00:00 2001 From: Pablo Barrero Cruz Date: Wed, 17 Apr 2024 11:51:25 +0200 Subject: [PATCH 001/132] Added New Questions --- questions/utils/question.json | 350 ++++++++++++++++++++++++++++++++++ 1 file changed, 350 insertions(+) diff --git a/questions/utils/question.json b/questions/utils/question.json index 8027df5d..2d8241d6 100644 --- a/questions/utils/question.json +++ b/questions/utils/question.json @@ -94,5 +94,355 @@ "category": ["Geography"] } ] + }, + { + "name": "art", + "instance": "Q3305213", + "properties": [ + { + "property": "P170", + "template": + [{ + "lang": "es", + "question": "Quien es el autor de x" + }, + { + "lang": "en", + "question": "Who is the author of x" + }], + "category": ["Art"] + }, + { + "property": "P571", + "template": [{ + "lang": "es", + "question": "Cual es el año de creacion de x" + }, + { + "lang": "en", + "question": "What is the year of creation of x" + }], + "category": ["Art"] + }, + { + "property": "P136", + "template": + [{ + "lang": "es", + "question": "Cual es el estilo artistico de x" + }, + { + "lang": "en", + "question": "What is the artistic style of x" + }], + "category": ["Art"] + } + ] + }, + { + "name": "science", + "instance": "Q11028", + "properties": [ + { + "property": "P61", + "template": + [{ + "lang": "es", + "question": "Quien es el inventor de x" + }, + { + "lang": "en", + "question": "Who is the inventor of x" + }], + "category": ["Science"] + }, + { + "property": "P575", + "template": + [{ + "lang": "es", + "question": "En que año se inventó x" + }, + { + "lang": "en", + "question": "What was the year of invention of x" + }], + "category": ["Science"] + } + ] + }, + { + "name": "mountains", + "instance": "Q8502", + "properties": [ + { + "property": "P2044", + "template": + [{ + "lang": "es", + "question": "Cual es la altitud mxima del x" + }, + { + "lang": "en", + "question": "What is the maximum altitude of x" + }], + "category": ["Geography"] + } + ] + }, + { + "name": "literature", + "instance": "Q571", + "properties": [ + { + "property": "P50", + "template": + [{ + "lang": "es", + "question": "Quien es el autor de x" + }, + { + "lang": "en", + "question": "Who is the author of x" + }], + "category": ["Entertainment"] + }, + { + "property": "P577", + "template": [{ + "lang": "es", + "question": "Cual es el año de publicacion de x" + }, + { + "lang": "en", + "question": "What is the year of publication of x" + }], + "category": ["Entertainment"] + }, + { + "property": "P136", + "template": + [{ + "lang": "es", + "question": "Cual es el genero de x" + }, + { + "lang": "en", + "question": "What is the genre of x" + }], + "category": ["Entertainment"] + } + ] + }, + { + "name": "cars", + "instance": "Q42889", + "properties": [ + { + "property": "P176", + "template": + [{ + "lang": "es", + "question": "Quien es el fabricante de x" + }, + { + "lang": "en", + "question": "Who is the manufacturer of x" + }], + "category": ["Cars"] + }, + { + "property": "P3032", + "template": [{ + "lang": "es", + "question": "Cuál es la velocidad máxima de x" + }, + { + "lang": "en", + "question": "What is the maximum speed of x" + }], + "category": ["Cars"] + }, + { + "property": "P571", + "template": + [{ + "lang": "es", + "question": "En qué año fue introducido x al mercado" + }, + { + "lang": "en", + "question": "In what year was x introduced to the market" + }], + "category": ["Cars"] + } + ] + }, + { + "name": "food", + "instance": "Q746549", + "properties": [ + { + "property": "P527", + "template": + [{ + "lang": "es", + "question": "Cuál es el ingrediente principal de x" + }, + { + "lang": "en", + "question": "What is the main ingredient of x" + }], + "category": ["Food"] + }, + { + "property": "P495", + "template": [{ + "lang": "es", + "question": "De qué región es originario x" + }, + { + "lang": "en", + "question": "What region is x originally from?" + }], + "category": ["Food"] + } + ] + }, + { + "name": "architecture", + "instance": "Q41176", + "properties": [ + { + "property": "P84", + "template": + [{ + "lang": "es", + "question": "Quién fue el arquitecto de x" + }, + { + "lang": "en", + "question": "Who was the architect of x" + }], + "category": ["Art"] + }, + { + "property": "P571", + "template": [{ + "lang": "es", + "question": "En qué año se completó x" + }, + { + "lang": "en", + "question": "In what year was it completed x" + }], + "category": ["Art"] + }, + { + "property": "P149", + "template": [{ + "lang": "es", + "question": "Cuál es el estilo arquitectónico de x" + }, + { + "lang": "en", + "question": "What is the architectural style of x" + }], + "category": ["Art"] + } + ] + }, + { + "name": "series", + "instance": "Q5398426", + "properties": [ + { + "property": "P178", + "template": + [{ + "lang": "es", + "question": "Quién es el creador de la serie x" + }, + { + "lang": "en", + "question": "Who is the creator of the series x" + }], + "category": ["Entertainment"] + }, + { + "property": "P2437", + "template": [{ + "lang": "es", + "question": "Cuántas temporadas tiene la serie x" + }, + { + "lang": "en", + "question": "How many seasons does the series x have?" + }], + "category": ["Entertainment"] + } + ] + }, + { + "name": "software", + "instance": "Q7397", + "properties": [ + { + "property": "P178", + "template": + [{ + "lang": "es", + "question": "Quién desarrolló el software x" + }, + { + "lang": "en", + "question": "Who developed the software x" + }], + "category": ["Technology"] + }, + { + "property": "P277", + "template": [{ + "lang": "es", + "question": "En qué lenguaje de programación está escrito x" + }, + { + "lang": "en", + "question": "What programming language is x written in?" + }], + "category": ["Technology"] + } + ] + }, + { + "name": "sport", + "instance": "Q2066131", + "properties": [ + { + "property": "P641", + "template": + [{ + "lang": "es", + "question": "En qué deporte compite x" + }, + { + "lang": "en", + "question": "Who developed the software x" + }], + "category": ["Sport"] + }, + { + "property": "P27", + "template": [{ + "lang": "es", + "question": "Cuál es la nacionalidad del atleta x" + }, + { + "lang": "en", + "question": "What is the nationality of the athlete x" + }], + "category": ["Sport"] + } + ] } ] \ No newline at end of file From bc864fa9585dbad52b4845ef80ec65eb030cc23e Mon Sep 17 00:00:00 2001 From: Pablo Barrero Cruz Date: Wed, 17 Apr 2024 11:58:59 +0200 Subject: [PATCH 002/132] Restored Questions --- questions/utils/question.json | 350 ---------------------------------- 1 file changed, 350 deletions(-) diff --git a/questions/utils/question.json b/questions/utils/question.json index 2d8241d6..8027df5d 100644 --- a/questions/utils/question.json +++ b/questions/utils/question.json @@ -94,355 +94,5 @@ "category": ["Geography"] } ] - }, - { - "name": "art", - "instance": "Q3305213", - "properties": [ - { - "property": "P170", - "template": - [{ - "lang": "es", - "question": "Quien es el autor de x" - }, - { - "lang": "en", - "question": "Who is the author of x" - }], - "category": ["Art"] - }, - { - "property": "P571", - "template": [{ - "lang": "es", - "question": "Cual es el año de creacion de x" - }, - { - "lang": "en", - "question": "What is the year of creation of x" - }], - "category": ["Art"] - }, - { - "property": "P136", - "template": - [{ - "lang": "es", - "question": "Cual es el estilo artistico de x" - }, - { - "lang": "en", - "question": "What is the artistic style of x" - }], - "category": ["Art"] - } - ] - }, - { - "name": "science", - "instance": "Q11028", - "properties": [ - { - "property": "P61", - "template": - [{ - "lang": "es", - "question": "Quien es el inventor de x" - }, - { - "lang": "en", - "question": "Who is the inventor of x" - }], - "category": ["Science"] - }, - { - "property": "P575", - "template": - [{ - "lang": "es", - "question": "En que año se inventó x" - }, - { - "lang": "en", - "question": "What was the year of invention of x" - }], - "category": ["Science"] - } - ] - }, - { - "name": "mountains", - "instance": "Q8502", - "properties": [ - { - "property": "P2044", - "template": - [{ - "lang": "es", - "question": "Cual es la altitud mxima del x" - }, - { - "lang": "en", - "question": "What is the maximum altitude of x" - }], - "category": ["Geography"] - } - ] - }, - { - "name": "literature", - "instance": "Q571", - "properties": [ - { - "property": "P50", - "template": - [{ - "lang": "es", - "question": "Quien es el autor de x" - }, - { - "lang": "en", - "question": "Who is the author of x" - }], - "category": ["Entertainment"] - }, - { - "property": "P577", - "template": [{ - "lang": "es", - "question": "Cual es el año de publicacion de x" - }, - { - "lang": "en", - "question": "What is the year of publication of x" - }], - "category": ["Entertainment"] - }, - { - "property": "P136", - "template": - [{ - "lang": "es", - "question": "Cual es el genero de x" - }, - { - "lang": "en", - "question": "What is the genre of x" - }], - "category": ["Entertainment"] - } - ] - }, - { - "name": "cars", - "instance": "Q42889", - "properties": [ - { - "property": "P176", - "template": - [{ - "lang": "es", - "question": "Quien es el fabricante de x" - }, - { - "lang": "en", - "question": "Who is the manufacturer of x" - }], - "category": ["Cars"] - }, - { - "property": "P3032", - "template": [{ - "lang": "es", - "question": "Cuál es la velocidad máxima de x" - }, - { - "lang": "en", - "question": "What is the maximum speed of x" - }], - "category": ["Cars"] - }, - { - "property": "P571", - "template": - [{ - "lang": "es", - "question": "En qué año fue introducido x al mercado" - }, - { - "lang": "en", - "question": "In what year was x introduced to the market" - }], - "category": ["Cars"] - } - ] - }, - { - "name": "food", - "instance": "Q746549", - "properties": [ - { - "property": "P527", - "template": - [{ - "lang": "es", - "question": "Cuál es el ingrediente principal de x" - }, - { - "lang": "en", - "question": "What is the main ingredient of x" - }], - "category": ["Food"] - }, - { - "property": "P495", - "template": [{ - "lang": "es", - "question": "De qué región es originario x" - }, - { - "lang": "en", - "question": "What region is x originally from?" - }], - "category": ["Food"] - } - ] - }, - { - "name": "architecture", - "instance": "Q41176", - "properties": [ - { - "property": "P84", - "template": - [{ - "lang": "es", - "question": "Quién fue el arquitecto de x" - }, - { - "lang": "en", - "question": "Who was the architect of x" - }], - "category": ["Art"] - }, - { - "property": "P571", - "template": [{ - "lang": "es", - "question": "En qué año se completó x" - }, - { - "lang": "en", - "question": "In what year was it completed x" - }], - "category": ["Art"] - }, - { - "property": "P149", - "template": [{ - "lang": "es", - "question": "Cuál es el estilo arquitectónico de x" - }, - { - "lang": "en", - "question": "What is the architectural style of x" - }], - "category": ["Art"] - } - ] - }, - { - "name": "series", - "instance": "Q5398426", - "properties": [ - { - "property": "P178", - "template": - [{ - "lang": "es", - "question": "Quién es el creador de la serie x" - }, - { - "lang": "en", - "question": "Who is the creator of the series x" - }], - "category": ["Entertainment"] - }, - { - "property": "P2437", - "template": [{ - "lang": "es", - "question": "Cuántas temporadas tiene la serie x" - }, - { - "lang": "en", - "question": "How many seasons does the series x have?" - }], - "category": ["Entertainment"] - } - ] - }, - { - "name": "software", - "instance": "Q7397", - "properties": [ - { - "property": "P178", - "template": - [{ - "lang": "es", - "question": "Quién desarrolló el software x" - }, - { - "lang": "en", - "question": "Who developed the software x" - }], - "category": ["Technology"] - }, - { - "property": "P277", - "template": [{ - "lang": "es", - "question": "En qué lenguaje de programación está escrito x" - }, - { - "lang": "en", - "question": "What programming language is x written in?" - }], - "category": ["Technology"] - } - ] - }, - { - "name": "sport", - "instance": "Q2066131", - "properties": [ - { - "property": "P641", - "template": - [{ - "lang": "es", - "question": "En qué deporte compite x" - }, - { - "lang": "en", - "question": "Who developed the software x" - }], - "category": ["Sport"] - }, - { - "property": "P27", - "template": [{ - "lang": "es", - "question": "Cuál es la nacionalidad del atleta x" - }, - { - "lang": "en", - "question": "What is the nationality of the athlete x" - }], - "category": ["Sport"] - } - ] } ] \ No newline at end of file From c6ca347d931145e1f185b3ede5d0473210aa0b40 Mon Sep 17 00:00:00 2001 From: teresagg Date: Sat, 20 Apr 2024 19:15:35 +0200 Subject: [PATCH 003/132] Improving question generation coverage --- .../__tests/services/question-generation-service.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/questions/__tests/services/question-generation-service.test.js b/questions/__tests/services/question-generation-service.test.js index 2024e0dd..a999966c 100644 --- a/questions/__tests/services/question-generation-service.test.js +++ b/questions/__tests/services/question-generation-service.test.js @@ -52,7 +52,7 @@ describe('Question generation', function() { dbService.addQuestion.mockResolvedValue(); // Llama a la función que deseas probar - await generator.generateQuestions(1); + await generator.generateQuestions(1,"en","Geography"); // Verifica que la función haya realizado las operaciones esperadas expect(dbService.addQuestion).toHaveBeenCalledTimes(1); @@ -76,7 +76,7 @@ describe('Question generation', function() { console.error = jest.fn(); // Llama a la función que deseas probar - await generator.generateQuestions(1); + await generator.generateQuestions(1,"en"); // Verifica que la función haya realizado las operaciones esperadas expect(dbService.addQuestion).toHaveBeenCalledTimes(0); From c1a721f4bf282a74638c7bffbd25c8e866c1302b Mon Sep 17 00:00:00 2001 From: teresagg Date: Sat, 20 Apr 2024 20:34:52 +0200 Subject: [PATCH 004/132] Tested more questions routes --- .../__tests/routes/question-routes.test.js | 69 ++++++++++++++++--- questions/routes/question-routes.js | 41 ++++++++++- questions/services/question-data-service.js | 2 +- 3 files changed, 98 insertions(+), 14 deletions(-) diff --git a/questions/__tests/routes/question-routes.test.js b/questions/__tests/routes/question-routes.test.js index 6baea678..124c7308 100644 --- a/questions/__tests/routes/question-routes.test.js +++ b/questions/__tests/routes/question-routes.test.js @@ -5,9 +5,13 @@ const mongoose = require('mongoose'); const express = require('express'); const bodyParser = require('body-parser'); + + let mongoServer; let questionFunctions; let questionRoutes; +let generateQuestionsService; + //let mongoServer; let app = express(); @@ -21,11 +25,11 @@ const questionData1 = { }; const questionData2 = { - question: "Which is the capital of UK?", + question: "Which is the capital of Spain?", options: ["Madrid", "Barcelona", "Paris", "London"], correctAnswer: "London", categories: ["Geography"], - language: "es" + language: "en" }; async function addingQuestion(questionData) { @@ -40,6 +44,12 @@ async function addingQuestion(questionData) { await questionFunctions.addQuestion(newQuestion); } +async function addingQuestions() { + for(var i = 0; i < 24; i++) { + await addingQuestion(questionData1); + await addingQuestion(questionData2); + } +} beforeAll(async () => { mongoServer = await MongoMemoryServer.create(); @@ -48,19 +58,17 @@ beforeAll(async () => { await mongoose.connect(mongoURI); questionFunctions = require('../../services/question-data-service'); questionRoutes = require('../../routes/question-routes.js'); + generateQuestionsService = require('../../services/generate-questions-service'); + jest.mock('../../services/generate-questions-service'); app.use(bodyParser.json()); app.use('/questions', questionRoutes); - }); beforeEach(async () => { //Load database with initial conditions //await mongoose.connection.dropDatabase(); await Question.deleteMany({}); - for(var i = 0; i < 100; i++) { - await addingQuestion(questionData1); - await addingQuestion(questionData2); - } + await addingQuestions(); }); afterAll(async () => { @@ -71,12 +79,48 @@ beforeEach(async () => { describe('Question routes', function() { - it('It should get a question from the database', async function() { + + describe('Get a question from the database', function() { + it('get question when 0 questions', async function() { + await Question.deleteMany({}); + await generateQuestionsService.generateQuestions.mockResolvedValue({"response":{"status":"200"}}); + const response = await request(app).get('/questions/es'); + await expect(response.status).toBe(200); + await expect(response.body.question).toBe(undefined); + }); + + it('get question when less than 50 questions', async function() { + await generateQuestionsService.generateQuestions.mockResolvedValue({"response":{"status":"200"}}); const response = await request(app).get('/questions/en'); await expect(response.status).toBe(200); await expect(response.body.question).toBe('Which is the capital of Spain?'); }); - + + it('get question when less than 100 questions', async function() { + await addingQuestions(); + await generateQuestionsService.generateQuestions.mockResolvedValue({"response":{"status":"200"}}); + const response = await request(app).get('/questions/en'); + await expect(response.status).toBe(200); + await expect(response.body.question).toBe('Which is the capital of Spain?'); + }); + + it('get question when more than 100 questions', async function() { + await addingQuestions(); + await addingQuestions(); + await generateQuestionsService.generateQuestions.mockResolvedValue({"response":{"status":"200"}}); + const response = await request(app).get('/questions/en'); + await expect(response.status).toBe(200); + await expect(response.body.question).toBe('Which is the capital of Spain?'); + }); + }); + describe('Get n questions from the database', function() { + + it('It should get n questions from the database', async function() { + await generateQuestionsService.generateQuestions.mockResolvedValue({"response":{"status":"200"}}); + const response = await request(app).get('/questions/getQuestionsFromDb/3/en'); + await expect(response.status).toBe(200); + await expect(response.body.length).toBe(3); + }); it('It should get n questions from the database', async function() { const response = await request(app).get('/questions/getQuestionsFromDb/3/en'); @@ -88,7 +132,9 @@ describe('Question routes', function() { const response = await request(app).get('/questions/getQuestionsFromDb/-1/en'); await expect(response.status).toBe(400); }); - + }); + describe('Question routes', function() { + it('It should get n questions of certain category from the database', async function() { const response = await request(app).get('/questions/getQuestionsFromDb/2/Geography/en'); await expect(response.status).toBe(200); @@ -106,4 +152,5 @@ describe('Question routes', function() { it('should connect to the MongoDB server in memory', async () => { expect(mongoose.connection.readyState).toBe(1); // 1 means connected }); - }); \ No newline at end of file + }); + }); \ No newline at end of file diff --git a/questions/routes/question-routes.js b/questions/routes/question-routes.js index 28b36f58..8a930697 100644 --- a/questions/routes/question-routes.js +++ b/questions/routes/question-routes.js @@ -68,13 +68,14 @@ router.get('/getQuestionsFromDb/:n/:category/:lang', async(_req, res) => { const n = parseInt(_req.params.n, 10); const category = _req.params.category; const language = _req.params.lang; + const questionCount = await dbService.getQuestionCountByCategory(category, language); //Verify is n is a correct number if (isNaN(n) || n <= 0) { return res.status(400).json({ error: 'Parameter "n" must be > 0.' }); } - if (await dbService.getQuestionCountByCategory(category, language) < n) { + /*if (await dbService.getQuestionCountByCategory(category, language) < n) { //Must generate n questions (n because some can fail at generation at the moment 18/04) await generateQuestionsService.generateQuestions(n + 2, language, category); //Do not wait to generate the others @@ -86,8 +87,44 @@ router.get('/getQuestionsFromDb/:n/:category/:lang', async(_req, res) => { dbService.deleteQuestionById(questions[i]._id); } } - res.json(questions); + res.json(questions);*/ + + // 0: Await till it creates 2, creates 50 async and do not delete + if (questionCount == 0) { + await generateQuestionsService.generateQuestions(2, language, category); + generateQuestionsService.generateQuestions(50, language, category); + questions = await dbService.getRandomQuestionsByCategory(n, category, language); + res.json(questions); + + // < 50: async creates 10 and do not delete + } else if (questionCount < 50) { + //Do not wait to generate the others + generateQuestionsService.generateQuestions(10, language, category); + questions = await dbService.getRandomQuestionsByCategory(n, category, language); + res.json(questions); + + // < 100: async creates 5 and delete + } else if (questionCount < 100) { + generateQuestionsService.generateQuestions(10, language, category); + questions = await dbService.getRandomQuestionsByCategory(n, category, language); + res.json(questions); + if(questions != null) { + for(var i = 0; i < questions.length; i++) { + dbService.deleteQuestionById(questions[i]._id); + } + } + + // >= 100: do not create and delete + } else { + questions = await dbService.getRandomQuestionsByCategory(n, category, language); + res.json(questions); + if(questions != null) { + for(var i = 0; i < questions.length; i++) { + dbService.deleteQuestionById(questions[i]._id); + } + } + } }); module.exports = router; \ No newline at end of file diff --git a/questions/services/question-data-service.js b/questions/services/question-data-service.js index 9eb956d5..ef6a054e 100644 --- a/questions/services/question-data-service.js +++ b/questions/services/question-data-service.js @@ -103,7 +103,7 @@ module.exports = { }, - // Get random questions TODO: refactor to use common code with get questions by category + // Get random questions getRandomQuestions : async function(n, wantedLanguage) { try { // Obtain total number of questions in database From 2d9a7f16b9dec20d1459a0fd0f6a5d8ac1074286 Mon Sep 17 00:00:00 2001 From: teresagg Date: Sun, 21 Apr 2024 09:05:12 +0200 Subject: [PATCH 005/132] Trying to fix e2e tests --- .../e2e/steps/discoveringCitiesGame.steps.js | 15 ++++++++++- webapp/e2e/steps/game.steps.js | 24 +++++++++++++---- webapp/e2e/steps/wiseMenStackGame.steps.js | 16 +++++++++++- webapp/package-lock.json | 26 ++++++++++--------- webapp/src/data/gameInfo.json | 2 +- 5 files changed, 63 insertions(+), 20 deletions(-) diff --git a/webapp/e2e/steps/discoveringCitiesGame.steps.js b/webapp/e2e/steps/discoveringCitiesGame.steps.js index 88b01198..7038ac95 100644 --- a/webapp/e2e/steps/discoveringCitiesGame.steps.js +++ b/webapp/e2e/steps/discoveringCitiesGame.steps.js @@ -6,6 +6,14 @@ const feature = loadFeature('./features/discoveringCitiesGame.feature'); let page; let browser; +async function loginUser(username, password) { + clickLink('//*[@id="root"]/div/header/div/a[2]'); + + await expect(page).toFill('input[name="username"]', username); + await expect(page).toFill('input[name="password"]', password); + await expect(page).toClick('button', { text: /Log in/i }); +} + defineFeature(feature, test => { beforeAll(async () => { @@ -39,7 +47,12 @@ defineFeature(feature, test => { }); //Way of setting up the timeout setDefaultOptions({ timeout: 10000 }) - + await page + .goto("http://localhost:3000", { + waitUntil: "networkidle0", + }) + .catch(() => {}); + await loginUser("prueba14","123456789Ab=11"); }); diff --git a/webapp/e2e/steps/game.steps.js b/webapp/e2e/steps/game.steps.js index 60b23883..22d6609a 100644 --- a/webapp/e2e/steps/game.steps.js +++ b/webapp/e2e/steps/game.steps.js @@ -6,6 +6,15 @@ const feature = loadFeature('./features/game.feature'); let page; let browser; + +async function loginUser(username, password) { + clickLink('//*[@id="root"]/div/header/div/a[2]'); + + await expect(page).toFill('input[name="username"]', username); + await expect(page).toFill('input[name="password"]', password); + await expect(page).toClick('button', { text: /Log in/i }); +} + defineFeature(feature, test => { beforeAll(async () => { @@ -36,11 +45,16 @@ defineFeature(feature, test => { } else { req.continue(); } - }); - //Way of setting up the timeout - setDefaultOptions({ timeout: 10000 }) - - + }); + setDefaultOptions({ timeout: 10000 }) + await page + .goto("http://localhost:3000", { + waitUntil: "networkidle0", + }) + .catch(() => {}); + await loginUser("prueba14","123456789Ab=11"); + + //Way of setting up the timeout }); beforeEach(async () => { diff --git a/webapp/e2e/steps/wiseMenStackGame.steps.js b/webapp/e2e/steps/wiseMenStackGame.steps.js index 3b1939f2..7a1d929c 100644 --- a/webapp/e2e/steps/wiseMenStackGame.steps.js +++ b/webapp/e2e/steps/wiseMenStackGame.steps.js @@ -6,6 +6,14 @@ const feature = loadFeature('./features/wiseMenStackGame.feature'); let page; let browser; +async function loginUser(username, password) { + clickLink('//*[@id="root"]/div/header/div/a[2]'); + + await expect(page).toFill('input[name="username"]', username); + await expect(page).toFill('input[name="password"]', password); + await expect(page).toClick('button', { text: /Log in/i }); +} + defineFeature(feature, test => { beforeAll(async () => { @@ -39,7 +47,13 @@ defineFeature(feature, test => { }); //Way of setting up the timeout setDefaultOptions({ timeout: 10000 }) - + await page + .goto("http://localhost:3000", { + waitUntil: "networkidle0", + }) + .catch(() => {}); + await loginUser("prueba14","123456789Ab=11"); + }); diff --git a/webapp/package-lock.json b/webapp/package-lock.json index 89a173a8..5ea4ee68 100644 --- a/webapp/package-lock.json +++ b/webapp/package-lock.json @@ -5,6 +5,7 @@ "requires": true, "packages": { "": { + "name": "webapp", "version": "0.1.0", "dependencies": { "@babel/plugin-proposal-private-property-in-object": "^7.21.11", @@ -677,6 +678,7 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.11.tgz", "integrity": "sha512-0QZ8qP/3RLDVBwBFoWAwCtgcDZJVwA5LUJRZU8x2YFfKNuFq161wK3cuGrALu5yiPu+vzwTAg/sMWVNeWeNyaw==", "deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-private-property-in-object instead.", + "dev": true, "dependencies": { "@babel/helper-annotate-as-pure": "^7.18.6", "@babel/helper-create-class-features-plugin": "^7.21.0", @@ -5643,6 +5645,7 @@ "version": "14.2.2", "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-14.2.2.tgz", "integrity": "sha512-SOUuM2ysCvjUWBXTNfQ/ztmnKDmqaiPV3SvoIuyxMUca45rbSWWAT/qB8CUs/JQ/ux/8JFs9DNdFQ3f6jH3crA==", + "dev": true, "dependencies": { "@babel/runtime": "^7.12.5", "@testing-library/dom": "^9.0.0", @@ -6012,6 +6015,7 @@ "version": "18.2.18", "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.2.18.tgz", "integrity": "sha512-TJxDm6OfAX2KJWJdMEVTwWke5Sc/E/RlnPGvGfS0W7+6ocy2xhDVQVh/KvC2Uf7kACs+gDytdusDSdWfWkaNzw==", + "dev": true, "dependencies": { "@types/react": "*" } @@ -6698,8 +6702,6 @@ "version": "8.12.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", - "optional": true, - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -6714,9 +6716,7 @@ "node_modules/ajv-formats/node_modules/json-schema-traverse": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "optional": true, - "peer": true + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==" }, "node_modules/ajv-keywords": { "version": "3.5.2", @@ -29729,6 +29729,7 @@ "version": "7.21.11", "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.11.tgz", "integrity": "sha512-0QZ8qP/3RLDVBwBFoWAwCtgcDZJVwA5LUJRZU8x2YFfKNuFq161wK3cuGrALu5yiPu+vzwTAg/sMWVNeWeNyaw==", + "dev": true, "requires": { "@babel/helper-annotate-as-pure": "^7.18.6", "@babel/helper-create-class-features-plugin": "^7.21.0", @@ -33177,6 +33178,7 @@ "version": "14.2.2", "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-14.2.2.tgz", "integrity": "sha512-SOUuM2ysCvjUWBXTNfQ/ztmnKDmqaiPV3SvoIuyxMUca45rbSWWAT/qB8CUs/JQ/ux/8JFs9DNdFQ3f6jH3crA==", + "dev": true, "requires": { "@babel/runtime": "^7.12.5", "@testing-library/dom": "^9.0.0", @@ -33522,6 +33524,7 @@ "version": "18.2.18", "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.2.18.tgz", "integrity": "sha512-TJxDm6OfAX2KJWJdMEVTwWke5Sc/E/RlnPGvGfS0W7+6ocy2xhDVQVh/KvC2Uf7kACs+gDytdusDSdWfWkaNzw==", + "dev": true, "requires": { "@types/react": "*" } @@ -34049,13 +34052,14 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz", "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", - "requires": {}, + "requires": { + "ajv": "^8.0.0" + }, "dependencies": { "ajv": { - "version": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", + "version": "8.12.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", - "optional": true, - "peer": true, "requires": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -34066,9 +34070,7 @@ "json-schema-traverse": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "optional": true, - "peer": true + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==" } } }, diff --git a/webapp/src/data/gameInfo.json b/webapp/src/data/gameInfo.json index 27a8397e..388ef71f 100644 --- a/webapp/src/data/gameInfo.json +++ b/webapp/src/data/gameInfo.json @@ -9,7 +9,7 @@ }, { "nombre": "WARM QUESTION", - "descripcion": "It consists of ten topics of varied themes. For each correct answer, €100 is earned, and €10 are lost if the contestant passes, does not respond, or answers incorrectly.", + "descripcion": "It consists of ten topics of varied themes. For each correct answer, 100 points are earned, and 10 are lost if the contestant passes, does not respond, or answers incorrectly.", "foto": "../instructions/foto1.jpg", "card":"It consists of ten topics of varied themes.", "cardFoto": "../homePage/foto1.jpg" From 3c59bce6957ff8412153577a1ff69dde709a6496 Mon Sep 17 00:00:00 2001 From: teresagg Date: Sun, 21 Apr 2024 09:17:38 +0200 Subject: [PATCH 006/132] changing xpath --- webapp/e2e/steps/discoveringCitiesGame.steps.js | 11 ++++++++++- webapp/e2e/steps/game.steps.js | 10 ++++++++++ webapp/e2e/steps/wiseMenStackGame.steps.js | 10 ++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/webapp/e2e/steps/discoveringCitiesGame.steps.js b/webapp/e2e/steps/discoveringCitiesGame.steps.js index 7038ac95..65442b62 100644 --- a/webapp/e2e/steps/discoveringCitiesGame.steps.js +++ b/webapp/e2e/steps/discoveringCitiesGame.steps.js @@ -7,13 +7,22 @@ let page; let browser; async function loginUser(username, password) { - clickLink('//*[@id="root"]/div/header/div/a[2]'); + clickLink('//button[text()="PLAY"]'); await expect(page).toFill('input[name="username"]', username); await expect(page).toFill('input[name="password"]', password); await expect(page).toClick('button', { text: /Log in/i }); } +async function clickLink(linkXPath) { + const [link] = await page.$x(linkXPath); + if (link) { + await link.click(); + } else { + throw new Error(`Cannot find link "${link}"`); + } + } + defineFeature(feature, test => { beforeAll(async () => { diff --git a/webapp/e2e/steps/game.steps.js b/webapp/e2e/steps/game.steps.js index 22d6609a..0cd98fe2 100644 --- a/webapp/e2e/steps/game.steps.js +++ b/webapp/e2e/steps/game.steps.js @@ -15,6 +15,16 @@ async function loginUser(username, password) { await expect(page).toClick('button', { text: /Log in/i }); } +async function clickLink(linkXPath) { + const [link] = await page.$x(linkXPath); + if (link) { + await link.click(); + } else { + throw new Error(`Cannot find link "${link}"`); + } + } + + defineFeature(feature, test => { beforeAll(async () => { diff --git a/webapp/e2e/steps/wiseMenStackGame.steps.js b/webapp/e2e/steps/wiseMenStackGame.steps.js index 7a1d929c..c85a9c42 100644 --- a/webapp/e2e/steps/wiseMenStackGame.steps.js +++ b/webapp/e2e/steps/wiseMenStackGame.steps.js @@ -14,6 +14,16 @@ async function loginUser(username, password) { await expect(page).toClick('button', { text: /Log in/i }); } +async function clickLink(linkXPath) { + const [link] = await page.$x(linkXPath); + if (link) { + await link.click(); + } else { + throw new Error(`Cannot find link "${link}"`); + } + } + + defineFeature(feature, test => { beforeAll(async () => { From c6b6f1e7765927202da5ef0e0746ee4781fe7e33 Mon Sep 17 00:00:00 2001 From: teresagg Date: Sun, 21 Apr 2024 09:36:51 +0200 Subject: [PATCH 007/132] Trying e2e --- webapp/e2e/steps/discoveringCitiesGame.steps.js | 4 ++-- webapp/e2e/steps/game.steps.js | 2 +- webapp/e2e/steps/wiseMenStackGame.steps.js | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/webapp/e2e/steps/discoveringCitiesGame.steps.js b/webapp/e2e/steps/discoveringCitiesGame.steps.js index 65442b62..2cec47da 100644 --- a/webapp/e2e/steps/discoveringCitiesGame.steps.js +++ b/webapp/e2e/steps/discoveringCitiesGame.steps.js @@ -9,8 +9,8 @@ let browser; async function loginUser(username, password) { clickLink('//button[text()="PLAY"]'); - await expect(page).toFill('input[name="username"]', username); - await expect(page).toFill('input[name="password"]', password); + await expect(page).toFill('input[name()="username"]', username); + await expect(page).toFill('input[name()="password"]', password); await expect(page).toClick('button', { text: /Log in/i }); } diff --git a/webapp/e2e/steps/game.steps.js b/webapp/e2e/steps/game.steps.js index 0cd98fe2..dcb25641 100644 --- a/webapp/e2e/steps/game.steps.js +++ b/webapp/e2e/steps/game.steps.js @@ -8,7 +8,7 @@ let browser; async function loginUser(username, password) { - clickLink('//*[@id="root"]/div/header/div/a[2]'); + clickLink('//button[text()="PLAY"]'); await expect(page).toFill('input[name="username"]', username); await expect(page).toFill('input[name="password"]', password); diff --git a/webapp/e2e/steps/wiseMenStackGame.steps.js b/webapp/e2e/steps/wiseMenStackGame.steps.js index c85a9c42..4de2835f 100644 --- a/webapp/e2e/steps/wiseMenStackGame.steps.js +++ b/webapp/e2e/steps/wiseMenStackGame.steps.js @@ -7,7 +7,7 @@ let page; let browser; async function loginUser(username, password) { - clickLink('//*[@id="root"]/div/header/div/a[2]'); + clickLink('//button[text()="PLAY"]'); await expect(page).toFill('input[name="username"]', username); await expect(page).toFill('input[name="password"]', password); From c3003ed75c4c05d64b13f20d6d5e9ab47e0c4662 Mon Sep 17 00:00:00 2001 From: teresagg Date: Mon, 22 Apr 2024 08:27:09 +0200 Subject: [PATCH 008/132] Discovering cities e2e tests --- .../e2e/steps/discoveringCitiesGame.steps.js | 18 ++++++++++++++---- webapp/e2e/steps/game.steps.js | 17 ++++++++++++++--- webapp/package-lock.json | 13 +++---------- webapp/package.json | 1 + 4 files changed, 32 insertions(+), 17 deletions(-) diff --git a/webapp/e2e/steps/discoveringCitiesGame.steps.js b/webapp/e2e/steps/discoveringCitiesGame.steps.js index 2cec47da..05866025 100644 --- a/webapp/e2e/steps/discoveringCitiesGame.steps.js +++ b/webapp/e2e/steps/discoveringCitiesGame.steps.js @@ -6,12 +6,22 @@ const feature = loadFeature('./features/discoveringCitiesGame.feature'); let page; let browser; -async function loginUser(username, password) { +async function loginUser(username, password, name, surname) { clickLink('//button[text()="PLAY"]'); await expect(page).toFill('input[name()="username"]', username); await expect(page).toFill('input[name()="password"]', password); await expect(page).toClick('button', { text: /Log in/i }); + + if(await expect(page).toBe('button', { text: /Log in/i })) { + await expect(page).toClick("a", { text: "Don't have an account? Register here." }); + await expect(page).toFill('input[name="username"]', username); + await expect(page).toFill('input[name="password"]', password); + await expect(page).toFill('input[name="name"]', name); + await expect(page).toFill('input[name="surname"]', surname); + await expect(page).toClick('button', { text: /Sign Up/i }) + + } } async function clickLink(linkXPath) { @@ -35,7 +45,7 @@ defineFeature(feature, test => { await page.setRequestInterception(true); page.on('request', (req) => { - if(req.url().endsWith('/Geography')) { + if(req.url().endsWith('/Cities')) { req.respond({ status: 200, headers: { @@ -46,7 +56,7 @@ defineFeature(feature, test => { question: 'Which is the capital of Spain?', options: ['Madrid', 'Barcelona', 'Paris', 'London'], correctAnswer: 'Madrid', - categories: ['Geography'], + categories: ['Cities'], language: 'en' }]) }); @@ -61,7 +71,7 @@ defineFeature(feature, test => { waitUntil: "networkidle0", }) .catch(() => {}); - await loginUser("prueba14","123456789Ab=11"); + await loginUser("prueba14","123456789Ab=11", "pr","prueba"); }); diff --git a/webapp/e2e/steps/game.steps.js b/webapp/e2e/steps/game.steps.js index dcb25641..6351bb5f 100644 --- a/webapp/e2e/steps/game.steps.js +++ b/webapp/e2e/steps/game.steps.js @@ -1,5 +1,6 @@ const puppeteer = require('puppeteer'); const { defineFeature, loadFeature }=require('jest-cucumber'); +const { expect } = require('expect-puppeteer'); const setDefaultOptions = require('expect-puppeteer').setDefaultOptions const feature = loadFeature('./features/game.feature'); @@ -7,12 +8,22 @@ let page; let browser; -async function loginUser(username, password) { +async function loginUser(username, password, name, surname) { clickLink('//button[text()="PLAY"]'); await expect(page).toFill('input[name="username"]', username); await expect(page).toFill('input[name="password"]', password); await expect(page).toClick('button', { text: /Log in/i }); + + if(await expect(page).toBe('button', { text: /Log in/i })) { + await expect(page).toClick("a", { text: "Don't have an account? Register here." }); + await expect(page).toFill('input[name="username"]', username); + await expect(page).toFill('input[name="password"]', password); + await expect(page).toFill('input[name="name"]', name); + await expect(page).toFill('input[name="surname"]', surname); + await expect(page).toClick('button', { text: /Sign Up/i }) + + } } async function clickLink(linkXPath) { @@ -37,7 +48,7 @@ defineFeature(feature, test => { await page.setRequestInterception(true); page.on('request', (req) => { - if(req.url().endsWith('/questions')) { + if(req.url().endsWith('/questions/en')) { req.respond({ status: 200, headers: { @@ -62,7 +73,7 @@ defineFeature(feature, test => { waitUntil: "networkidle0", }) .catch(() => {}); - await loginUser("prueba14","123456789Ab=11"); + await loginUser("prueba14","123456789Ab=11", "pr","prueba"); //Way of setting up the timeout }); diff --git a/webapp/package-lock.json b/webapp/package-lock.json index 5ea4ee68..c5cb7fa6 100644 --- a/webapp/package-lock.json +++ b/webapp/package-lock.json @@ -20,6 +20,7 @@ "babel": "^6.23.0", "cross-env": "^7.0.3", "express": "^4.19.2", + "get-uri": "^6.0.3", "i18next": "^23.11.0", "pupeteer": "^0.0.1", "react": "^18.2.0", @@ -7563,7 +7564,6 @@ "version": "5.0.5", "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.0.5.tgz", "integrity": "sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==", - "dev": true, "engines": { "node": ">=10.0.0" } @@ -9412,7 +9412,6 @@ "version": "6.0.2", "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz", "integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==", - "dev": true, "engines": { "node": ">= 14" } @@ -12188,7 +12187,6 @@ "version": "6.0.3", "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.3.tgz", "integrity": "sha512-BzUrJBS9EcUb4cFol8r4W3v1cPsSyajLSthNkz5BxbpDcHN5tIrM10E2eNvfnvBn3DaT3DUgx0OpsBKkaOpanw==", - "dev": true, "dependencies": { "basic-ftp": "^5.0.2", "data-uri-to-buffer": "^6.0.2", @@ -12203,7 +12201,6 @@ "version": "11.2.0", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.2.0.tgz", "integrity": "sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==", - "dev": true, "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", @@ -34679,8 +34676,7 @@ "basic-ftp": { "version": "5.0.5", "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.0.5.tgz", - "integrity": "sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==", - "dev": true + "integrity": "sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==" }, "batch": { "version": "0.6.1", @@ -35999,8 +35995,7 @@ "data-uri-to-buffer": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz", - "integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==", - "dev": true + "integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==" }, "data-urls": { "version": "2.0.0", @@ -38057,7 +38052,6 @@ "version": "6.0.3", "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.3.tgz", "integrity": "sha512-BzUrJBS9EcUb4cFol8r4W3v1cPsSyajLSthNkz5BxbpDcHN5tIrM10E2eNvfnvBn3DaT3DUgx0OpsBKkaOpanw==", - "dev": true, "requires": { "basic-ftp": "^5.0.2", "data-uri-to-buffer": "^6.0.2", @@ -38069,7 +38063,6 @@ "version": "11.2.0", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.2.0.tgz", "integrity": "sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw==", - "dev": true, "requires": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", diff --git a/webapp/package.json b/webapp/package.json index 4b23fa31..1a674c46 100644 --- a/webapp/package.json +++ b/webapp/package.json @@ -15,6 +15,7 @@ "babel": "^6.23.0", "cross-env": "^7.0.3", "express": "^4.19.2", + "get-uri": "^6.0.3", "i18next": "^23.11.0", "pupeteer": "^0.0.1", "react": "^18.2.0", From 0c9c3886bb4c50a07cecabefc2c3dd5cfc6ebd85 Mon Sep 17 00:00:00 2001 From: teresagg Date: Mon, 22 Apr 2024 08:47:34 +0200 Subject: [PATCH 009/132] Changed login link in e2e --- webapp/e2e/steps/discoveringCitiesGame.steps.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/webapp/e2e/steps/discoveringCitiesGame.steps.js b/webapp/e2e/steps/discoveringCitiesGame.steps.js index 05866025..0441656a 100644 --- a/webapp/e2e/steps/discoveringCitiesGame.steps.js +++ b/webapp/e2e/steps/discoveringCitiesGame.steps.js @@ -7,7 +7,9 @@ let page; let browser; async function loginUser(username, password, name, surname) { - clickLink('//button[text()="PLAY"]'); + const [loginLink] = await page.$x('//*[@id="root"]/div/header/div/a[2]'); + await loginLink.click(); + //clickLink('//button[text()="PLAY"]'); await expect(page).toFill('input[name()="username"]', username); await expect(page).toFill('input[name()="password"]', password); From 2e3b4122b739aa92288d072eb4c085d6d4340c1b Mon Sep 17 00:00:00 2001 From: uo289689 Date: Tue, 23 Apr 2024 13:42:15 +0200 Subject: [PATCH 010/132] Updated The Challange Game look and feel --- webapp/src/pages/TheChallengeGame.js | 213 ++++++++++++++------------- 1 file changed, 108 insertions(+), 105 deletions(-) diff --git a/webapp/src/pages/TheChallengeGame.js b/webapp/src/pages/TheChallengeGame.js index 9a5126e2..9e357e67 100644 --- a/webapp/src/pages/TheChallengeGame.js +++ b/webapp/src/pages/TheChallengeGame.js @@ -10,9 +10,9 @@ import { useContext } from 'react'; import Confetti from 'react-confetti'; import { CountdownCircleTimer } from "react-countdown-circle-timer"; import Card from '@mui/material/Card'; -import CardContent from '@mui/material/CardContent'; import { useTranslation } from 'react-i18next'; import i18n from '../localize/i18n'; +import { PlayArrow, Pause } from '@mui/icons-material'; const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000'; @@ -51,6 +51,8 @@ const Game = () => { const [questionCountdownRunning, setQuestionCountdownRunning] = React.useState(false); //property to start and stop question timer const [userResponses, setUserResponses] = React.useState([]); const [language, setCurrentLanguage] = React.useState(i18n.language); + const [paused, setPaused] = React.useState(false); + const [passNewRound, setPassNewRound] = React.useState(false); const [questionHistorial, setQuestionHistorial] = React.useState(Array(numRounds).fill(null)); @@ -89,16 +91,25 @@ const Game = () => { setShowConfetti(false); } }, [correctlyAnsweredQuestions, incorrectlyAnsweredQuestions]); + + React.useEffect(() => { + if (passNewRound && !paused) { + setRound(prevRound => { + return prevRound + 1; + }); + setButtonStates([]); + } + }, [paused, passNewRound]); const startGame = () => { setConfigModalOpen(false); startNewRound(); }; - - // gets a random question from the database and initializes button states to null + const startNewRound = async () => { setAnswered(false); + setPassNewRound(false); // It works deploying using git repo from machine with: axios.get(`http://20.80.235.188:8000/questions`) setCurrentLanguage(i18n.language); axios.get(`${apiEndpoint}/questions/${language}/${category}`) @@ -211,28 +222,11 @@ const Game = () => { setButtonStates(newButtonStates); setTimeout(async() => { - setRound(round + 1); - setButtonStates([]); + setPassNewRound(true); setCurrentLanguage(i18n.language); }, 4000); }; - const questionHistorialBar = () => { - return questionHistorial.map((isCorrect, index) => ( - - {index + 1} - - )); - }; - // Render the configuration window before starting the game if (configModalOpen) { @@ -287,6 +281,22 @@ const Game = () => { ); } + const questionHistorialBar = () => { + return questionHistorial.map((isCorrect, index) => ( + + + )); + }; + + const togglePause = () => { + setTimerRunning(!timerRunning); + setPaused(!paused); + } + // circular loading if (!questionData) { @@ -307,9 +317,9 @@ const Game = () => { ); } - // redirect to / if game over -if (shouldRedirect) { - // Redirect after 3 seconds + // redirect to / if game over + if (shouldRedirect) { + // Redirect after 4 seconds setTimeout(() => { navigate('/homepage'); }, 4000); @@ -317,109 +327,96 @@ if (shouldRedirect) { return ( - incorrectlyAnsweredQuestions ? 'green' : 'red', - fontSize: '4rem', // Tamaño de fuente - marginTop: '20px', // Espaciado superior - marginBottom: '50px', // Espaciado inferior - }} - > - {correctlyAnsweredQuestions > incorrectlyAnsweredQuestions ? "Great Job!" : "Game Over"} - -
- Correct Answers: {correctlyAnsweredQuestions} - Incorrect Answers: {incorrectlyAnsweredQuestions} - Total money: {totalScore} - Game time: {totalTimePlayed} seconds -
+ incorrectlyAnsweredQuestions ? theme.palette.success.main : theme.palette.error.main }}> + {correctlyAnsweredQuestions > incorrectlyAnsweredQuestions ? t("Game.win_msg") : t("Game.lose_msg") } + + + { t("Game.correct") }: {correctlyAnsweredQuestions} + { t("Game.incorrect") }: {incorrectlyAnsweredQuestions} + { t("Game.money") }: {totalScore} + { t("Game.time") }: {totalTimePlayed} + {showConfetti && }
); } - return ( - - - - - {questionHistorialBar()} - - - - - {round} / {numRounds} - - - {questionData.question} +return ( + + + + + { answered ? + // Pausa + + : + // Cronómetro selectResponse(0, "FAILED")} //when time ends always fail question - > - {({ remainingTime }) => { - return ( -
-
{remainingTime}
-
- ); - }} + data-testid="circleTimer" + key={questionCountdownKey} + isPlaying = {questionCountdownRunning} + duration={timerConfig} + colors={[theme.palette.success.main, "#F7B801", "#f50707", theme.palette.error.main]} + size={100} + colorsTime={[10, 6, 3, 0]} + onComplete={() => selectResponse(-1, "FAILED")} //when time ends always fail question + > + {({ remainingTime }) => { + return ( +
+
{remainingTime}
+
+ ); + }}
+ } +
+ + + + {questionData.question.toUpperCase()} {questionData.options.map((option, index) => ( {renderStatistics()} @@ -307,7 +307,7 @@ const Statistics = () => { variant="contained" sx={{ marginBottom: '0.5em', marginTop: '0.5em', backgroundColor: 'green', color: theme.palette.secondary.main, borderColor: theme.palette.primary.main, '&:hover': { backgroundColor: theme.palette.secondary.main, color: theme.palette.primary.main, borderColor: theme.palette.primary.main } }} > - {showQuestionsRecord ? 'Hide Questions Record' : 'Show Questions Record'} + {showQuestionsRecord ? t("Statistics.button.hide_record") : t("Statistics.button.show_record")} {renderQuestions()} From 78e0ac588a695a8fb0a300b6b5a52a7d0d65d5be Mon Sep 17 00:00:00 2001 From: uo289689 Date: Tue, 23 Apr 2024 17:26:18 +0200 Subject: [PATCH 015/132] Internacionalized view of homePage --- webapp/src/pages/Homepage.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/webapp/src/pages/Homepage.js b/webapp/src/pages/Homepage.js index ee5b0f6f..79915623 100644 --- a/webapp/src/pages/Homepage.js +++ b/webapp/src/pages/Homepage.js @@ -3,10 +3,12 @@ import { Button, Box, Grid, Typography } from '@mui/material'; import data from "../data/gameInfo.json"; import CardComponent from "../components/CardComponent.js"; import useMediaQuery from '@mui/material/useMediaQuery'; +import { useTranslation } from 'react-i18next'; const Homepage = () => { const xxl = useMediaQuery('(min-width:1920px)'); + const { t } = useTranslation(); const styles = React.useMemo(() => ({ cardButton:{ @@ -175,7 +177,7 @@ const Homepage = () => { GAME MODES {games} - + ); }; From 6050d482c7f6530c65386a733b64922a41b1a327 Mon Sep 17 00:00:00 2001 From: uo289689 Date: Tue, 23 Apr 2024 17:36:25 +0200 Subject: [PATCH 016/132] Internacionalized view of instrucctions --- webapp/src/data/gameInfo.json | 10 +++++----- webapp/src/localize/en.json | 5 ----- webapp/src/localize/es.json | 14 +++++--------- webapp/src/localize/fr.json | 14 +++++--------- webapp/src/pages/Homepage.js | 12 ++++++------ webapp/src/pages/Instructions.js | 5 ++++- webapp/src/pages/Statistics.js | 4 ++-- 7 files changed, 27 insertions(+), 37 deletions(-) diff --git a/webapp/src/data/gameInfo.json b/webapp/src/data/gameInfo.json index 27a8397e..89053297 100644 --- a/webapp/src/data/gameInfo.json +++ b/webapp/src/data/gameInfo.json @@ -1,6 +1,6 @@ [ { - "nombre": "WISE MEN STACK", + "nombre": "Wise Men Stack", "descripcion": "The player chooses a topic from five available options and must answer a battery of questions related to it within 60 seconds. For each question, the host provides two options. If the contestant guesses correctly, they move on to the next question.", "foto": "../instructions/foto0.png", @@ -8,21 +8,21 @@ "cardFoto": "../homePage/foto0.png" }, { - "nombre": "WARM QUESTION", + "nombre": "Warm Question", "descripcion": "It consists of ten topics of varied themes. For each correct answer, €100 is earned, and €10 are lost if the contestant passes, does not respond, or answers incorrectly.", "foto": "../instructions/foto1.jpg", "card":"It consists of ten topics of varied themes.", "cardFoto": "../homePage/foto1.jpg" }, { - "nombre": "DISCOVERING CITIES", + "nombre": "Discovering Cities", "descripcion": "In the 'Discovering Cities' game mode, the contestant will face a challenge where they will be repeatedly asked questions referring to different cities around the world. To successfully overcome the challenge, the contestant must answer as many questions as possible correctly throughout the test..", "foto": "../instructions/foto2.png", "card":"The contestant will face a challenge where they will be repeatedly asked questions referring to different cities around the world.", "cardFoto": "../homePage/foto2.png" }, { - "nombre": "THE CHALLENGE", + "nombre": "Challenge", "descripcion": "The 'Challenge' game mode is the quintessential game mode, as it allows you to customize the match to your liking. This game mode is tailored for those who wish to practice certain game formats before engaging in our various other game modes.", "foto": "../instructions/foto3.jpg", "card":"The 'Challenge' game mode is the quintessential game mode, as it allows you to customize the match to your liking.", @@ -30,7 +30,7 @@ }, { - "nombre": "MULTIPLAYER MODE", + "nombre": "Multiplayer", "descripcion": "Create a room and share the room code with other players to play. It also has a room chat.", "foto": "../instructions/online-photo.jpg", "card":"Create a room and share the room code with other players to play. It also has a room chat.", diff --git a/webapp/src/localize/en.json b/webapp/src/localize/en.json index 9c3d8b1a..4d511c5c 100644 --- a/webapp/src/localize/en.json +++ b/webapp/src/localize/en.json @@ -44,12 +44,7 @@ "multiplayer": { "name": "Multiplayer", "desc": "Create a room for other player to join and play 1vs1" - }, - "online": { - "name": "Online Game", - "desc": "" } - }, "Game": { diff --git a/webapp/src/localize/es.json b/webapp/src/localize/es.json index 25171e73..5af8d516 100644 --- a/webapp/src/localize/es.json +++ b/webapp/src/localize/es.json @@ -26,28 +26,24 @@ "Games": { "wise_men": { - "name": "Hombres Sabiondos", + "name": "Wise Men Stack", "desc": "El jugador elige un tema entre cinco opciones disponibles y debe responder una batería de preguntas relacionadas con él en un plazo de 60 segundos. Para cada pregunta, el presentador proporciona dos opciones. Si el concursante acierta, gana €20; de lo contrario, pasa a la siguiente pregunta (ya que la respuesta correcta sería la otra opción). Si el tiempo se agota antes de que se formule por completo la pregunta y se proporcionen ambas posibles respuestas, el concursante aún puede responderla; sin embargo, si la afirmación no se ha completado (o las opciones no se proporcionaron), no pueden responder." }, "warm_quest": { - "name": "Pregunta Calentorra", + "name": "Warm Question", "desc": "Consta de diez temas de diferentes temáticas. Por cada respuesta correcta, se ganan €100, y se pierden €10 si el concursante pasa, no responde o responde incorrectamente." }, "discover": { - "name": "Descubriendo Ciudades", + "name": "Discovering Cities", "desc": "En el modo de juego 'Descubriendo Ciudades', el concursante enfrentará un desafío donde se le harán preguntas repetidas referentes a diferentes ciudades de todo el mundo. Para superar con éxito el desafío, el concursante debe responder tantas preguntas como sea posible correctamente a lo largo de la prueba." }, "challenge": { - "name": "Desafío", + "name": "Challenge", "desc": "El modo de juego 'Desafío' es el modo de juego por excelencia, ya que te permite personalizar el enfrentamiento a tu gusto. Este modo de juego está diseñado para aquellos que deseen practicar ciertos formatos de juego antes de participar en nuestros diversos otros modos de juego." }, "multiplayer": { - "name": "Multijugador", + "name": "Multiplayer", "desc": "Crea una sala para que otros jugadores se unan y jueguen 1 contra 1." - }, - "online": { - "name": "Partida en línea", - "desc": "" } }, diff --git a/webapp/src/localize/fr.json b/webapp/src/localize/fr.json index e940adb8..2b75edcf 100644 --- a/webapp/src/localize/fr.json +++ b/webapp/src/localize/fr.json @@ -26,28 +26,24 @@ "Games": { "wise_men": { - "name": "Pile de Sages", + "name": "Wise Men Stack", "desc": "Le joueur choisit un sujet parmi cinq options disponibles et doit répondre à une batterie de questions qui y sont liées dans un délai de 60 secondes. Pour chaque question, l'hôte fournit deux options. Si le participant devine correctement, il gagne 20 € ; sinon, il passe à la question suivante (car la bonne réponse serait l'autre option). Si le temps s'écoule avant que la question ne soit entièrement posée et que les deux réponses possibles soient fournies, le participant peut toujours y répondre ; cependant, si l'énoncé n'a pas été complété (ou si les options n'ont pas été fournies), il ne peut pas répondre." }, "warm_quest": { - "name": "Question Chaleureuse", + "name": "Warm Question", "desc": "Il se compose de dix sujets de thèmes variés. Pour chaque réponse correcte, 100 € sont gagnés, et 10 € sont perdus si le participant passe, ne répond pas ou répond incorrectement." }, "discover": { - "name": "Découverte des Villes", + "name": "Discovering Cities", "desc": "Dans le mode de jeu 'Découverte des Villes', le participant sera confronté à un défi où il lui sera posé à plusieurs reprises des questions se référant à différentes villes du monde entier. Pour surmonter avec succès le défi, le participant doit répondre correctement à autant de questions que possible tout au long du test." }, "challenge": { - "name": "Défi", + "name": "Challenge", "desc": "Le mode de jeu 'Défi' est le mode de jeu par excellence, car il vous permet de personnaliser le match à votre guise. Ce mode de jeu est adapté à ceux qui souhaitent s'entraîner à certains formats de jeu avant de s'engager dans nos divers autres modes de jeu." }, "multiplayer": { - "name": "Multijoueur", + "name": "Multiplayer", "desc": "Créez une salle pour que d'autres joueurs se joignent et jouent en 1 contre 1." - }, - "online": { - "name": "Jeu en ligne", - "desc": "" } }, diff --git a/webapp/src/pages/Homepage.js b/webapp/src/pages/Homepage.js index 79915623..6df790e9 100644 --- a/webapp/src/pages/Homepage.js +++ b/webapp/src/pages/Homepage.js @@ -108,19 +108,19 @@ const Homepage = () => { //if online mode -> change link to go to online room const changeGameLink = React.useCallback((index) => { switch (info[index].nombre) { - case "WISE MEN STACK": + case "Wise Men Stack": setGameLink("/wiseMenStackGame"); break; - case "WARM QUESTION": + case "Warm Question": setGameLink("/warmQuestionGame"); break; - case "DISCOVERING CITIES": + case "Discovering Cities": setGameLink("/discoveringCitiesGame"); break; - case "THE CHALLENGE": + case "Challenge": setGameLink("/theChallengeGame"); break; - case "MULTIPLAYER MODE": + case "Multiplayer": setGameLink("/multiplayerRoom"); break; default: @@ -177,7 +177,7 @@ const Homepage = () => { GAME MODES {games} - + ); }; diff --git a/webapp/src/pages/Instructions.js b/webapp/src/pages/Instructions.js index 7143217e..e416610f 100644 --- a/webapp/src/pages/Instructions.js +++ b/webapp/src/pages/Instructions.js @@ -1,10 +1,12 @@ import * as React from "react"; import { Button, Typography, Grid, Box , CssBaseline, useMediaQuery } from "@mui/material"; import data from "../data/gameInfo.json"; +import { useTranslation } from 'react-i18next'; const Instructions = () => { const lg = useMediaQuery('(min-width: 1200px)'); + const { t } = useTranslation(); const styles = { @@ -143,7 +145,8 @@ const Instructions = () => { Foto del minijuego {info[index].nombre} - {info[index].descripcion} + {t("Games." + + info[index].nombre +".desc")} ); diff --git a/webapp/src/pages/Statistics.js b/webapp/src/pages/Statistics.js index 3fa49f9c..adac2491 100644 --- a/webapp/src/pages/Statistics.js +++ b/webapp/src/pages/Statistics.js @@ -228,7 +228,7 @@ const Statistics = () => { {currentItems.map((record, index) => (
- t("Statistics.game") {formatCreatedAt(record.createdAt)} + {t("Statistics.game")} {formatCreatedAt(record.createdAt)} @@ -298,7 +298,7 @@ const Statistics = () => { { t("Games.discover.name") }
{renderStatistics()} From ba2e452516806dd8a5e414dee5d791f3f42374aa Mon Sep 17 00:00:00 2001 From: uo289689 Date: Tue, 23 Apr 2024 17:38:07 +0200 Subject: [PATCH 017/132] Internacionalized view of home --- webapp/src/pages/Home.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/webapp/src/pages/Home.js b/webapp/src/pages/Home.js index 381a6c74..fcfa9336 100644 --- a/webapp/src/pages/Home.js +++ b/webapp/src/pages/Home.js @@ -1,10 +1,11 @@ import * as React from "react"; import {Box, Button} from "@mui/material"; import useMediaQuery from '@mui/material/useMediaQuery'; - +import { useTranslation } from 'react-i18next'; const Home = () => { const xxl = useMediaQuery('(min-width:1920px)'); + const { t } = useTranslation(); const styles = { logo:{ @@ -96,7 +97,7 @@ const Home = () => { Logo - +
+ ); + } // redirect to / if game over if (shouldRedirect) { From ce1862b9a6b5a339d46d4139809753c508748c8f Mon Sep 17 00:00:00 2001 From: Pablo Date: Wed, 24 Apr 2024 22:11:13 +0200 Subject: [PATCH 055/132] Solved problem to display initial form with npm start --- webapp/src/pages/WiseMenStackGame.js | 171 +++++++++++++-------------- 1 file changed, 85 insertions(+), 86 deletions(-) diff --git a/webapp/src/pages/WiseMenStackGame.js b/webapp/src/pages/WiseMenStackGame.js index fe5e8c12..70a3113f 100644 --- a/webapp/src/pages/WiseMenStackGame.js +++ b/webapp/src/pages/WiseMenStackGame.js @@ -227,8 +227,52 @@ const WiseMenStackGame = () => { {index + 1} )); - }; - + }; + + if(!isConfigured) { + return ( + + Wise Men Stack + {t("Wise_Men.instructions")} + + {/* Dropdown for selecting category */} +
+ + +
+ + +
+ ); + } // circular loading if (!questionData) { @@ -247,95 +291,50 @@ const WiseMenStackGame = () => {
); - } - - if(!isConfigured) { - return ( - - Wise Men Stack - {t("Wise_Men.instructions")} - - {/* Dropdown for selecting category */} -
- - -
- - -
- ); } // redirect to / if game over -if (shouldRedirect) { - // Redirect after 3 seconds - setTimeout(() => { - navigate('/homepage'); - }, 4000); + if (shouldRedirect) { + // Redirect after 3 seconds + setTimeout(() => { + navigate('/homepage'); + }, 4000); + return ( + + + incorrectlyAnsweredQuestions ? 'green' : 'red', + fontSize: '4rem', // Tamaño de fuente + marginTop: '20px', // Espaciado superior + marginBottom: '50px', // Espaciado inferior + }} + > + {correctlyAnsweredQuestions > incorrectlyAnsweredQuestions ? t("Game.win_msg") : t("Game.lose_msg") } + +
+ { t("Game.correct") }: {correctlyAnsweredQuestions} + { t("Game.incorrect") }: {incorrectlyAnsweredQuestions} + { t("Game.money") }: {totalScore} + { t("Game.time") }: {totalTimePlayed} +
+ {showConfetti && } +
+ ); + } - return ( - - - incorrectlyAnsweredQuestions ? 'green' : 'red', - fontSize: '4rem', // Tamaño de fuente - marginTop: '20px', // Espaciado superior - marginBottom: '50px', // Espaciado inferior - }} - > - {correctlyAnsweredQuestions > incorrectlyAnsweredQuestions ? t("Game.win_msg") : t("Game.lose_msg") } - -
- { t("Game.correct") }: {correctlyAnsweredQuestions} - { t("Game.incorrect") }: {incorrectlyAnsweredQuestions} - { t("Game.money") }: {totalScore} - { t("Game.time") }: {totalTimePlayed} -
- {showConfetti && } -
- ); -} return ( Date: Wed, 24 Apr 2024 22:11:35 +0200 Subject: [PATCH 056/132] Changing all the Discovering Cities game style. --- webapp/src/pages/DiscoveringCitiesGame.js | 294 ++++++++++------------ 1 file changed, 132 insertions(+), 162 deletions(-) diff --git a/webapp/src/pages/DiscoveringCitiesGame.js b/webapp/src/pages/DiscoveringCitiesGame.js index 7575ff67..d0b6b712 100644 --- a/webapp/src/pages/DiscoveringCitiesGame.js +++ b/webapp/src/pages/DiscoveringCitiesGame.js @@ -1,6 +1,6 @@ import * as React from 'react'; import axios from 'axios'; -import { Container, Button, CssBaseline, Grid, Typography, CircularProgress, Card, CardContent } from '@mui/material'; +import { useTheme, Container, Button, CssBaseline, Grid, Typography, CircularProgress, Card } from '@mui/material'; import { PlayArrow, Pause } from '@mui/icons-material'; import CheckIcon from '@mui/icons-material/Check'; import ClearIcon from '@mui/icons-material/Clear'; @@ -23,9 +23,11 @@ const DiscovertingCitiesGame = () => { //sesion information const {username} = useContext(SessionContext); - // Traductions + // Translations const { t } = useTranslation(); + const theme = useTheme(); + // state initialization const [round, setRound] = React.useState(1); const [questionData, setQuestionData] = React.useState(null); @@ -41,8 +43,11 @@ const DiscovertingCitiesGame = () => { const [questionCountdownKey, setQuestionCountdownKey] = React.useState(15); //key to update question timer const [questionCountdownRunning, setQuestionCountdownRunning] = React.useState(false); //property to start and stop question timer const [userResponses, setUserResponses] = React.useState([]); + const [paused, setPaused] = React.useState(false); + const [passNewRound, setPassNewRound] = React.useState(false); const [language, setCurrentLanguage] = React.useState(i18n.language); + const [questionHistorial, setQuestionHistorial] = React.useState(Array(MAX_ROUNDS).fill(null)); React.useEffect(() => { @@ -74,28 +79,33 @@ const DiscovertingCitiesGame = () => { // stablish if the confetti must show or not React.useEffect(() => { - if (correctlyAnsweredQuestions > incorrectlyAnsweredQuestions) { - setShowConfetti(true); - } else { - setShowConfetti(false); + correctlyAnsweredQuestions > incorrectlyAnsweredQuestions ? setShowConfetti(true) : setShowConfetti(false); + }, [correctlyAnsweredQuestions, incorrectlyAnsweredQuestions]); + + React.useEffect(() => { + if (passNewRound && !paused) { + setRound(prevRound => { + return prevRound + 1; + }); + setButtonStates([]); } - }, [correctlyAnsweredQuestions, incorrectlyAnsweredQuestions]); - + }, [paused, passNewRound]); // gets a random question from the database and initializes button states to null const startNewRound = async () => { setAnswered(false); - // It works deploying using git repo from machine with: axios.get(`http://20.80.235.188:8000/questions`) + setPassNewRound(false); + // Updates current language setCurrentLanguage(i18n.language); axios.get(`${apiEndpoint}/questions/${language}/Cities`) .then(quest => { // every new round it gets a new question from db - setQuestionData(quest.data[0]); + setQuestionData(quest.data[0]); setButtonStates(new Array(quest.data[0].options.length).fill(null)); }).catch(error => { console.error(error); - }); + }); }; const updateStatistics = async() => { @@ -125,6 +135,7 @@ const DiscovertingCitiesGame = () => { online_incorrectly_answered_questions: 0, online_total_time_played: 0, online_games_played: 0, + online_games_won: 0 }); } catch (error) { console.error("Error:", error); @@ -197,53 +208,37 @@ const DiscovertingCitiesGame = () => { setButtonStates(newButtonStates); setTimeout(async() => { - setRound(round + 1); - setButtonStates([]); + setPassNewRound(true); setCurrentLanguage(i18n.language); - }, 4000); }; const questionHistorialBar = () => { return questionHistorial.map((isCorrect, index) => ( - - {index + 1} - + + )); - }; + }; const togglePause = () => { setTimerRunning(!timerRunning); - setQuestionCountdownRunning(!timerRunning); - if (timerRunning) { - // Si el juego estaba en marcha y se pausa, deshabilitar los botones - setButtonStates(new Array(questionData.options.length).fill(true)); - } else { - // Si el juego estaba pausado y se reanuda, habilitar los botones - setButtonStates(new Array(questionData.options.length).fill(null)); - } + setPaused(!paused); } - // circular loading if (!questionData) { return ( @@ -253,135 +248,110 @@ const DiscovertingCitiesGame = () => { } // redirect to / if game over -if (shouldRedirect) { - // Redirect after 3 seconds - setTimeout(() => { - navigate('/homepage'); - }, 4000); + if (shouldRedirect) { + // Redirect after 4 seconds + setTimeout(() => { + navigate('/homepage'); + }, 4000); + return ( + + + incorrectlyAnsweredQuestions ? theme.palette.success.main : theme.palette.error.main }}> + {correctlyAnsweredQuestions > incorrectlyAnsweredQuestions ? t("Game.win_msg") : t("Game.lose_msg") } + + + { t("Game.correct") }: {correctlyAnsweredQuestions} + { t("Game.incorrect") }: {incorrectlyAnsweredQuestions} + { t("Game.money") }: {totalScore} + { t("Game.time") }: {totalTimePlayed} + + {showConfetti && } + + ); + } + return ( - - - incorrectlyAnsweredQuestions ? 'green' : 'red', - fontSize: '4rem', // Tamaño de fuente - marginTop: '20px', // Espaciado superior - marginBottom: '50px', // Espaciado inferior - }} - > - {correctlyAnsweredQuestions > incorrectlyAnsweredQuestions ? t("Game.win_msg") : t("Game.lose_msg") } - -
- { t("Game.correct") }: {correctlyAnsweredQuestions} - { t("Game.incorrect") }: {incorrectlyAnsweredQuestions} - { t("Game.money") }: {totalScore} - { t("Game.time") }: {totalTimePlayed} -
- {showConfetti && } -
- ); -} - return ( - + - + + { answered ? + // Pausa + + : + // Cronómetro + selectResponse(-1, "FAILED")} //when time ends always fail question + > + {({ remainingTime }) => { + return ( +
+
{remainingTime}
+
+ ); + }} +
+ } +
- - - {questionHistorialBar()} - + + + {questionData.question.toUpperCase()} + + + + {questionData.options.map((option, index) => ( + + + + ))} + - - {round} / {MAX_ROUNDS} - - - {questionData.question} - selectResponse(0, "FAILED")} //when time ends always fail question - > - {({ remainingTime }) => { - return ( -
-
{remainingTime}
-
- ); - }} -
-
- - - {questionData.options.map((option, index) => ( - - - - ))} - + {/* Progress Cards */} + + {questionHistorialBar()} +
); }; From 5c2619274a5dc95b2033608425ba288d572162d8 Mon Sep 17 00:00:00 2001 From: uo288245 Date: Wed, 24 Apr 2024 22:19:00 +0200 Subject: [PATCH 057/132] Improved the code in the Discovering CIties game. --- webapp/src/pages/DiscoveringCitiesGame.js | 70 +++++------------------ 1 file changed, 13 insertions(+), 57 deletions(-) diff --git a/webapp/src/pages/DiscoveringCitiesGame.js b/webapp/src/pages/DiscoveringCitiesGame.js index d0b6b712..c8c632a2 100644 --- a/webapp/src/pages/DiscoveringCitiesGame.js +++ b/webapp/src/pages/DiscoveringCitiesGame.js @@ -38,10 +38,10 @@ const DiscovertingCitiesGame = () => { const [correctlyAnsweredQuestions, setCorrectlyAnsweredQuestions] = React.useState(0); const [incorrectlyAnsweredQuestions, setIncorrectlyAnsweredQuestions] = React.useState(0); const [totalTimePlayed, setTotalTimePlayed] = React.useState(0); - const [timerRunning, setTimerRunning] = React.useState(true); // indicate if the timer is working - const [showConfetti, setShowConfetti] = React.useState(false); //indicates if the confetti must appear - const [questionCountdownKey, setQuestionCountdownKey] = React.useState(15); //key to update question timer - const [questionCountdownRunning, setQuestionCountdownRunning] = React.useState(false); //property to start and stop question timer + const [timerRunning, setTimerRunning] = React.useState(true); + const [showConfetti, setShowConfetti] = React.useState(false); + const [questionCountdownKey, setQuestionCountdownKey] = React.useState(15); + const [questionCountdownRunning, setQuestionCountdownRunning] = React.useState(false); const [userResponses, setUserResponses] = React.useState([]); const [paused, setPaused] = React.useState(false); const [passNewRound, setPassNewRound] = React.useState(false); @@ -215,12 +215,7 @@ const DiscovertingCitiesGame = () => { const questionHistorialBar = () => { return questionHistorial.map((isCorrect, index) => ( - - + )); }; @@ -232,15 +227,7 @@ const DiscovertingCitiesGame = () => { // circular loading if (!questionData) { return ( - + @@ -254,22 +241,10 @@ const DiscovertingCitiesGame = () => { navigate('/homepage'); }, 4000); - return ( - + - incorrectlyAnsweredQuestions ? theme.palette.success.main : theme.palette.error.main }}> + incorrectlyAnsweredQuestions ? theme.palette.success.main : theme.palette.error.main }}> {correctlyAnsweredQuestions > incorrectlyAnsweredQuestions ? t("Game.win_msg") : t("Game.lose_msg") } @@ -295,16 +270,9 @@ const DiscovertingCitiesGame = () => { : // Cronómetro - selectResponse(-1, "FAILED")} //when time ends always fail question - > + selectResponse(-1, "FAILED")} size={100} > {({ remainingTime }) => { return (
@@ -326,20 +294,8 @@ const DiscovertingCitiesGame = () => { From dabf639c0e9cc67abb63ce7cba549a47bf149fa7 Mon Sep 17 00:00:00 2001 From: Pablo Date: Wed, 24 Apr 2024 22:23:26 +0200 Subject: [PATCH 058/132] Wise men stack configuration layout --- webapp/src/pages/WiseMenStackGame.js | 44 ++++++++++++++++------------ 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/webapp/src/pages/WiseMenStackGame.js b/webapp/src/pages/WiseMenStackGame.js index 70a3113f..3f4cf03f 100644 --- a/webapp/src/pages/WiseMenStackGame.js +++ b/webapp/src/pages/WiseMenStackGame.js @@ -1,6 +1,6 @@ import * as React from 'react'; import axios from 'axios'; -import { Container, Button, CssBaseline, Grid, Typography, CircularProgress, Card, CardContent, Select, MenuItem, useTheme } from '@mui/material'; +import { Container, Box, Button, CssBaseline, Grid, Typography, CircularProgress, Card, CardContent, Select, MenuItem, useTheme } from '@mui/material'; import CheckIcon from '@mui/icons-material/Check'; import ClearIcon from '@mui/icons-material/Clear'; import { useNavigate } from 'react-router-dom'; @@ -231,23 +231,30 @@ const WiseMenStackGame = () => { if(!isConfigured) { return ( - - Wise Men Stack - {t("Wise_Men.instructions")} - - {/* Dropdown for selecting category */} -
- - -
+ + + {t("Game.config.title")} + + + + + {t("Wise_Men.instructions")} + + + {/* Dropdown for selecting category */} +
+ + +
+
: // Cronómetro - selectResponse(-1, "FAILED")} size={100} > + selectResponse(-1, "FAILED")}> {({ remainingTime }) => { return (
@@ -292,8 +291,7 @@ const DiscovertingCitiesGame = () => { {questionData.options.map((option, index) => ( - : // Cronómetro - selectResponse(-1, "FAILED")} //when time ends always fail question - > + selectResponse(-1, "FAILED")}> {({ remainingTime }) => { return (
-
{remainingTime}
-
+
{remainingTime}
+
); }}
@@ -335,22 +292,9 @@ const Game = () => { {questionData.options.map((option, index) => ( - From da3d29c5a63eed4957bea33a5e1ef4db37ce7a12 Mon Sep 17 00:00:00 2001 From: Pablo Date: Wed, 24 Apr 2024 22:33:47 +0200 Subject: [PATCH 060/132] MUI components in Wise Men and unifyied internationalization dict elements --- webapp/src/localize/en.json | 2 +- webapp/src/localize/es.json | 3 +-- webapp/src/localize/fr.json | 5 +---- webapp/src/pages/WiseMenStackGame.js | 10 ++++++---- 4 files changed, 9 insertions(+), 11 deletions(-) diff --git a/webapp/src/localize/en.json b/webapp/src/localize/en.json index 1fd053a4..9b444938 100644 --- a/webapp/src/localize/en.json +++ b/webapp/src/localize/en.json @@ -77,7 +77,7 @@ "Wise_Men": { "instructions": "Choose a category:", - "category":"Categories: " + "category":"Categories" }, "Login": { diff --git a/webapp/src/localize/es.json b/webapp/src/localize/es.json index cdcda2b5..ce1729d4 100644 --- a/webapp/src/localize/es.json +++ b/webapp/src/localize/es.json @@ -76,8 +76,7 @@ }, "Wise_Men": { - "instructions": "Elige una categoría:", - "category":"Categorías: " + "instructions": "Elige una categoría:" }, "Login": { diff --git a/webapp/src/localize/fr.json b/webapp/src/localize/fr.json index d42258a3..81a657d2 100644 --- a/webapp/src/localize/fr.json +++ b/webapp/src/localize/fr.json @@ -78,10 +78,7 @@ "Wise_Men": { "instructions": "Choisissez une catégorie:", - "category":"Catégories: ", - "geography": "Geographie", - "political":"Politique", - "sports":"Sport" + "category":"Catégories" }, diff --git a/webapp/src/pages/WiseMenStackGame.js b/webapp/src/pages/WiseMenStackGame.js index 3f4cf03f..650e2cb7 100644 --- a/webapp/src/pages/WiseMenStackGame.js +++ b/webapp/src/pages/WiseMenStackGame.js @@ -237,13 +237,15 @@ const WiseMenStackGame = () => { - + {t("Wise_Men.instructions")} {/* Dropdown for selecting category */} -
- + + + {t("Game.config.category")}: + -
+
+ : + // Cronómetro + selectResponse(-1, "FAILED")}> + {({ remainingTime }) => { + return ( + + {remainingTime} + + ); + }} + + }
- {showConfetti && } -
- ); -} - -return ( - - - - - { answered ? - // Pausa - - : - // Cronómetro - selectResponse(-1, "FAILED")} //when time ends always fail question - > - {({ remainingTime }) => { - return ( -
-
{remainingTime}
-
- ); - }} -
- } -
- - - {questionData.question.toUpperCase()} - - - - {questionData.options.map((option, index) => ( - - - - ))} - - + + + {questionData.question.toUpperCase()} + + + + {questionData.options.map((option, index) => ( + + + + ))} + + - {/* Progress Cards */} - - {questionHistorialBar()} + {/* Progress Cards */} + + {questionHistorialBar()} + -
-); + ); }; export default Game; \ No newline at end of file From c0b2f3641ea3ae9283d284b57586294fa6650232 Mon Sep 17 00:00:00 2001 From: Pablo Date: Wed, 24 Apr 2024 23:52:25 +0200 Subject: [PATCH 066/132] Minor style changes in game --- webapp/src/pages/Game.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/webapp/src/pages/Game.js b/webapp/src/pages/Game.js index 9536556d..2d0d698d 100644 --- a/webapp/src/pages/Game.js +++ b/webapp/src/pages/Game.js @@ -243,7 +243,7 @@ const Game = () => { return ( - + incorrectlyAnsweredQuestions ? theme.palette.success.main : theme.palette.error.main }}> {correctlyAnsweredQuestions > incorrectlyAnsweredQuestions ? t("Game.win_msg") : t("Game.lose_msg") } @@ -284,17 +284,17 @@ const Game = () => { } - - + + {questionData.question.toUpperCase()} - + {questionData.options.map((option, index) => ( From 3e6a939a68b0ef4e0f0541e9cd9174b2e6f43a27 Mon Sep 17 00:00:00 2001 From: Pablo Date: Wed, 24 Apr 2024 23:52:51 +0200 Subject: [PATCH 067/132] Style changes in Wise Men --- webapp/src/pages/WiseMenStackGame.js | 197 ++++++++++++--------------- 1 file changed, 90 insertions(+), 107 deletions(-) diff --git a/webapp/src/pages/WiseMenStackGame.js b/webapp/src/pages/WiseMenStackGame.js index 0d12683d..cd16974b 100644 --- a/webapp/src/pages/WiseMenStackGame.js +++ b/webapp/src/pages/WiseMenStackGame.js @@ -1,8 +1,9 @@ import * as React from 'react'; import axios from 'axios'; -import { Container, Box, Button, CssBaseline, Grid, Typography, CircularProgress, Card, CardContent, Select, MenuItem, useTheme } from '@mui/material'; +import { Container, Box, Button, CssBaseline, Grid, Typography, CircularProgress, Card, Select, MenuItem, useTheme } from '@mui/material'; import CheckIcon from '@mui/icons-material/Check'; import ClearIcon from '@mui/icons-material/Clear'; +import { PlayArrow, Pause } from '@mui/icons-material'; import { useNavigate } from 'react-router-dom'; import { SessionContext } from '../SessionContext'; import { useContext } from 'react'; @@ -47,6 +48,8 @@ const WiseMenStackGame = () => { const [category, setCategory] = React.useState('Geography'); const [possibleAnswers, setPossibleAnswers] = React.useState([]); const [isConfigured, setConfiguration] = React.useState(false); + const [paused, setPaused] = React.useState(false); + const [passNewRound, setPassNewRound] = React.useState(false); const [questionHistorial, setQuestionHistorial] = React.useState(Array(round).fill(null)); @@ -83,13 +86,21 @@ const WiseMenStackGame = () => { } else { setShowConfetti(false); } - }, [correctlyAnsweredQuestions, incorrectlyAnsweredQuestions]); + }, [correctlyAnsweredQuestions, incorrectlyAnsweredQuestions]); + React.useEffect(() => { + if (passNewRound && !paused) { + setRound(prevRound => { + return prevRound + 1; + }); + setButtonStates([]); + } + }, [paused, passNewRound]); - // gets a random question from the database and initializes button states to null const startNewRound = async () => { setAnswered(false); - // It works deploying using git repo from machine with: axios.get(`http://20.80.235.188:8000/questions`)7 + + setPassNewRound(false); // Updates current language setCurrentLanguage(i18n.language); @@ -102,6 +113,19 @@ const WiseMenStackGame = () => { }).catch(error => { console.error("Could not get questions", error); + let quest = {} + quest.data = { + "_id":"1", + "question":"Esta pregunta de prueba resulta de su agrado?", + "options":["Muchísimo","Un cacho","Tope flama","Fino filipino"], + "correctAnswer":"Tope flama", + "categories":["Political"], + "id":"1", + "__v":0 + }; + setQuestionData(quest.data); + setButtonStates(new Array(quest.data.options.length).fill(null)); + getPossibleOptions(quest.data); }); }; @@ -207,27 +231,21 @@ const WiseMenStackGame = () => { setButtonStates(newButtonStates); setTimeout(async() => { - setRound(round + 1); - setButtonStates([]); + setPassNewRound(true); setCurrentLanguage(i18n.language); - }, 2000); + }, 4000); }; const questionHistorialBar = () => { return questionHistorial.map((isCorrect, index) => ( - - {index + 1} - + )); }; + + const togglePause = () => { + setTimerRunning(!timerRunning); + setPaused(!paused); + } if(!isConfigured) { return ( @@ -315,94 +333,65 @@ const WiseMenStackGame = () => { }, 4000); return ( - + - incorrectlyAnsweredQuestions ? 'green' : 'red', - fontSize: '4rem', // Tamaño de fuente - marginTop: '20px', // Espaciado superior - marginBottom: '50px', // Espaciado inferior - }} - > - {correctlyAnsweredQuestions > incorrectlyAnsweredQuestions ? t("Game.win_msg") : t("Game.lose_msg") } - -
- { t("Game.correct") }: {correctlyAnsweredQuestions} - { t("Game.incorrect") }: {incorrectlyAnsweredQuestions} - { t("Game.money") }: {totalScore} - { t("Game.time") }: {totalTimePlayed} -
+ incorrectlyAnsweredQuestions ? theme.palette.success.main : theme.palette.error.main }}> + {correctlyAnsweredQuestions > incorrectlyAnsweredQuestions ? t("Game.win_msg") : t("Game.lose_msg") } + + + { t("Game.correct") }: {correctlyAnsweredQuestions} + { t("Game.incorrect") }: {incorrectlyAnsweredQuestions} + { t("Game.money") }: {totalScore} + { t("Game.time") }: {totalTimePlayed} + {showConfetti && }
); } return ( - + - - - - {questionHistorialBar()} - + + + { answered ? + // Pausa + + : + // Cronómetro + selectResponse(-1, "FAILED")}> + {({ remainingTime }) => { + return ( + + {remainingTime} + + ); + }} + + } - - {t("Game.round")} {round} - - - {questionData.question} - selectResponse(0, "FAILED")} //when time ends always fail question - > - {({ remainingTime }) => { - return ( -
-
{remainingTime}
-
- ); - }} -
-
+ + + {questionData.question.toUpperCase()} + + + + {possibleAnswers.map((option, index) => ( + + + + ))} + + {possibleAnswers.map((option, index) => ( @@ -412,17 +401,7 @@ const WiseMenStackGame = () => { variant="contained" onClick={() => selectResponse(index, option)} disabled={buttonStates[index] !== null || answered} // before, you could still press more than one button - sx={{ - height: "50px", // Ajusta el tamaño según sea necesario - width: "50%", // Ajusta el ancho según sea necesario - borderRadius: "20px", // Ajusta el radio según sea necesario - margin: "5px", - backgroundColor: buttonStates[index] === "success" ? "green" : buttonStates[index] === "failure" ? "red" : null, - "&:disabled": { - backgroundColor: buttonStates[index] === "success" ? "green" : buttonStates[index] === "failure" ? "red" : "gray", - color: "white", - }, - }} + > {buttonStates[index] === "success" ? : buttonStates[index] === "failure" ? : null} {option} @@ -430,6 +409,10 @@ const WiseMenStackGame = () => { ))}
+ + + {questionHistorialBar()} +
); }; From 7f5b664cdebb5298c8747841bd22a0eb1bcc9f50 Mon Sep 17 00:00:00 2001 From: Pablo Date: Thu, 25 Apr 2024 00:09:39 +0200 Subject: [PATCH 068/132] Final style for WiseMen --- webapp/src/pages/WiseMenStackGame.js | 22 +++------------------- 1 file changed, 3 insertions(+), 19 deletions(-) diff --git a/webapp/src/pages/WiseMenStackGame.js b/webapp/src/pages/WiseMenStackGame.js index cd16974b..c52f4665 100644 --- a/webapp/src/pages/WiseMenStackGame.js +++ b/webapp/src/pages/WiseMenStackGame.js @@ -238,7 +238,7 @@ const WiseMenStackGame = () => { const questionHistorialBar = () => { return questionHistorial.map((isCorrect, index) => ( - + )); }; @@ -382,7 +382,7 @@ const WiseMenStackGame = () => { {possibleAnswers.map((option, index) => ( - - - ))} - - {questionHistorialBar()} + { answered || round === 1 ? : }
); From 18b2576d0f0cf614b17f66a3f8b155f9912c25d6 Mon Sep 17 00:00:00 2001 From: Pablo Date: Thu, 25 Apr 2024 00:12:31 +0200 Subject: [PATCH 069/132] Remove test question --- webapp/src/pages/WiseMenStackGame.js | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/webapp/src/pages/WiseMenStackGame.js b/webapp/src/pages/WiseMenStackGame.js index c52f4665..436937c7 100644 --- a/webapp/src/pages/WiseMenStackGame.js +++ b/webapp/src/pages/WiseMenStackGame.js @@ -113,19 +113,6 @@ const WiseMenStackGame = () => { }).catch(error => { console.error("Could not get questions", error); - let quest = {} - quest.data = { - "_id":"1", - "question":"Esta pregunta de prueba resulta de su agrado?", - "options":["Muchísimo","Un cacho","Tope flama","Fino filipino"], - "correctAnswer":"Tope flama", - "categories":["Political"], - "id":"1", - "__v":0 - }; - setQuestionData(quest.data); - setButtonStates(new Array(quest.data.options.length).fill(null)); - getPossibleOptions(quest.data); }); }; From 59bf639aec4a75fedfeff63c330d0aba3d0b6729 Mon Sep 17 00:00:00 2001 From: Pablo Date: Thu, 25 Apr 2024 00:33:29 +0200 Subject: [PATCH 070/132] Stylized pause & play button --- webapp/src/pages/Game.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/webapp/src/pages/Game.js b/webapp/src/pages/Game.js index 2d0d698d..8436d7c6 100644 --- a/webapp/src/pages/Game.js +++ b/webapp/src/pages/Game.js @@ -1,6 +1,6 @@ import * as React from 'react'; import axios from 'axios'; -import { useTheme, Container, Button, CssBaseline, Grid, Typography, CircularProgress, Card, Box } from '@mui/material'; +import { useTheme, Container, Button, CssBaseline, Grid, Typography, CircularProgress, Card, Box, IconButton } from '@mui/material'; import { PlayArrow, Pause } from '@mui/icons-material'; import CheckIcon from '@mui/icons-material/Check'; import ClearIcon from '@mui/icons-material/Clear'; @@ -266,9 +266,9 @@ const Game = () => { { answered ? // Pausa - + togglePause()} sx={{ height: 100, width: 100, border: `2px solid ${theme.palette.primary.main}` }} data-testid={ paused ? "play" : "pause"} > + { paused ? : } + : // Cronómetro Date: Thu, 25 Apr 2024 00:33:43 +0200 Subject: [PATCH 071/132] Fixed the Warm Question game view. --- webapp/src/pages/Game.js | 6 +- webapp/src/pages/WarmQuestionGame.js | 300 ++++++++++----------------- 2 files changed, 107 insertions(+), 199 deletions(-) diff --git a/webapp/src/pages/Game.js b/webapp/src/pages/Game.js index 9536556d..d3e0bc26 100644 --- a/webapp/src/pages/Game.js +++ b/webapp/src/pages/Game.js @@ -226,22 +226,20 @@ const Game = () => { // circular loading if (!questionData) { return ( - + ); } - // redirect to / if game over + // redirect to homepage if game over if (shouldRedirect) { // Redirect after 4 seconds setTimeout(() => { navigate('/homepage'); }, 4000); - return ( diff --git a/webapp/src/pages/WarmQuestionGame.js b/webapp/src/pages/WarmQuestionGame.js index bcd63cf9..81d18427 100644 --- a/webapp/src/pages/WarmQuestionGame.js +++ b/webapp/src/pages/WarmQuestionGame.js @@ -1,7 +1,6 @@ import * as React from 'react'; import axios from 'axios'; - -import { Container, Button, CssBaseline, Grid, Typography, CircularProgress } from '@mui/material'; +import { useTheme, Container, Button, CssBaseline, Grid, Typography, CircularProgress, Card, Box } from '@mui/material'; import { PlayArrow, Pause } from '@mui/icons-material'; import CheckIcon from '@mui/icons-material/Check'; import ClearIcon from '@mui/icons-material/Clear'; @@ -10,13 +9,11 @@ import { SessionContext } from '../SessionContext'; import { useContext } from 'react'; import Confetti from 'react-confetti'; import { CountdownCircleTimer } from "react-countdown-circle-timer"; -import Card from '@mui/material/Card'; -import CardContent from '@mui/material/CardContent'; +import { useTranslation } from 'react-i18next'; import i18n from '../localize/i18n'; const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000'; - const Game = () => { const navigate = useNavigate(); const MAX_ROUNDS = 10; @@ -26,6 +23,11 @@ const Game = () => { //sesion information const {username} = useContext(SessionContext); + // Translations + const { t } = useTranslation(); + + const theme = useTheme(); + // state initialization const [round, setRound] = React.useState(1); const [questionData, setQuestionData] = React.useState(null); @@ -42,11 +44,12 @@ const Game = () => { const [questionCountdownKey, setQuestionCountdownKey] = React.useState(15); //key to update question timer const [questionCountdownRunning, setQuestionCountdownRunning] = React.useState(false); //property to start and stop question timer const [userResponses, setUserResponses] = React.useState([]); + const [paused, setPaused] = React.useState(false); + const [passNewRound, setPassNewRound] = React.useState(false); const [language, setCurrentLanguage] = React.useState(i18n.language); const [questionHistorial, setQuestionHistorial] = React.useState(Array(MAX_ROUNDS).fill(null)); - React.useEffect(() => { let timer; if (timerRunning) { @@ -76,18 +79,23 @@ const Game = () => { // stablish if the confetti must show or not React.useEffect(() => { - if (correctlyAnsweredQuestions > incorrectlyAnsweredQuestions) { - setShowConfetti(true); - } else { - setShowConfetti(false); + correctlyAnsweredQuestions > incorrectlyAnsweredQuestions ? setShowConfetti(true) : setShowConfetti(false); + }, [correctlyAnsweredQuestions, incorrectlyAnsweredQuestions]); + + React.useEffect(() => { + if (passNewRound && !paused) { + setRound(prevRound => { + return prevRound + 1; + }); + setButtonStates([]); } - }, [correctlyAnsweredQuestions, incorrectlyAnsweredQuestions]); - + }, [paused, passNewRound]); // gets a random question from the database and initializes button states to null const startNewRound = async () => { setAnswered(false); - // It works deploying using git repo from machine with: axios.get(`http://20.80.235.188:8000/questions`) + setPassNewRound(false); + // Updates current language setCurrentLanguage(i18n.language); axios.get(`${apiEndpoint}/questions/${language}`) @@ -96,9 +104,20 @@ const Game = () => { setQuestionData(quest.data); setButtonStates(new Array(quest.data.options.length).fill(null)); }).catch(error => { - console.error(error); + // console.error(error); + let quest = {} + quest.data = { + "_id":"1", + "question":"Esta pregunta de prueba resulta de su agrado?", + "options":["Muchísimo","Un cacho","Tope flama","Fino filipino"], + "correctAnswer":"Tope flama", + "categories":["Political"], + "id":"1", + "__v":0 + }; + setQuestionData(quest.data); + setButtonStates(new Array(quest.data.options.length).fill(null)); }); - }; const updateStatistics = async() => { @@ -233,212 +252,103 @@ const Game = () => { const questionHistorialBar = () => { return questionHistorial.map((isCorrect, index) => ( - - {index + 1} - + )); - }; + }; const togglePause = () => { setTimerRunning(!timerRunning); - setQuestionCountdownRunning(!timerRunning); - if (timerRunning) { - // Si el juego estaba en marcha y se pausa, deshabilitar los botones - setButtonStates(new Array(questionData.options.length).fill(true)); - } else { - // Si el juego estaba pausado y se reanuda, habilitar los botones - setButtonStates(new Array(questionData.options.length).fill(null)); - } + setPaused(!paused); } - // circular loading if (!questionData) { return ( - + ); } - // redirect to / if game over -if (shouldRedirect) { - // Redirect after 3 seconds - setTimeout(() => { - navigate('/homepage'); - }, 4000); + // redirect to homepage if game over + if (shouldRedirect) { + // Redirect after 4 seconds + setTimeout(() => { + navigate('/homepage'); + }, 4000); + return ( + + + incorrectlyAnsweredQuestions ? theme.palette.success.main : theme.palette.error.main }}> + {correctlyAnsweredQuestions > incorrectlyAnsweredQuestions ? t("Game.win_msg") : t("Game.lose_msg") } + + + { t("Game.correct") }: {correctlyAnsweredQuestions} + { t("Game.incorrect") }: {incorrectlyAnsweredQuestions} + { t("Game.money") }: {totalScore} + { t("Game.time") }: {totalTimePlayed} + + {showConfetti && } + + ); + } return ( - - - incorrectlyAnsweredQuestions ? 'green' : 'red', - fontSize: '4rem', // Tamaño de fuente - marginTop: '20px', // Espaciado superior - marginBottom: '50px', // Espaciado inferior - }} - > - {correctlyAnsweredQuestions > incorrectlyAnsweredQuestions ? "Great Job!" : "Game Over"} - -
- Correct Answers: {correctlyAnsweredQuestions} - Incorrect Answers: {incorrectlyAnsweredQuestions} - Skipped Questions: {passedQuestions} - Total money: {totalScore} - Game time: {totalTimePlayed} seconds -
- {showConfetti && } -
- ); -} - return ( - + - - Game time: {totalTimePlayed} s - - - - - - - - {questionHistorialBar()} - + + { answered ? + // Pausa + + : + // Cronómetro + selectResponse(-1, "FAILED")}> + {({ remainingTime }) => { + return ( + + {remainingTime} + + ); + }} + + } - - {round} / {MAX_ROUNDS} - - - {questionData.question} - selectResponse(0, "FAILED")} //when time ends always fail question - > - {({ remainingTime }) => { - return ( -
-
{remainingTime}
-
- ); - }} -
-
- - - {questionData.options.map((option, index) => ( - - - - ))} - + + + {questionData.question.toUpperCase()} + + + + {questionData.options.map((option, index) => ( + + + + ))} + + {!answered && ( - + )} - + {/* Progress Cards */} + + {questionHistorialBar()} +
); }; From b0680414bbb18d5942ccb4821213499b649802c8 Mon Sep 17 00:00:00 2001 From: Pablo Date: Thu, 25 Apr 2024 00:40:18 +0200 Subject: [PATCH 072/132] Improved pause button with labels and applied to other games --- webapp/src/pages/DiscoveringCitiesGame.js | 10 ++++++---- webapp/src/pages/Game.js | 4 +++- webapp/src/pages/TheChallengeGame.js | 8 +++++--- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/webapp/src/pages/DiscoveringCitiesGame.js b/webapp/src/pages/DiscoveringCitiesGame.js index efee9fc4..2cbb9168 100644 --- a/webapp/src/pages/DiscoveringCitiesGame.js +++ b/webapp/src/pages/DiscoveringCitiesGame.js @@ -1,6 +1,6 @@ import * as React from 'react'; import axios from 'axios'; -import { useTheme, Container, Button, CssBaseline, Grid, Typography, CircularProgress, Card, Box } from '@mui/material'; +import { useTheme, Container, Button, CssBaseline, Grid, Typography, CircularProgress, Card, Box, IconButton } from '@mui/material'; import { PlayArrow, Pause } from '@mui/icons-material'; import CheckIcon from '@mui/icons-material/Check'; import ClearIcon from '@mui/icons-material/Clear'; @@ -265,9 +265,11 @@ const DiscovertingCitiesGame = () => { { answered ? // Pausa - + togglePause()} sx={{ height: 100, width: 100, border: `2px solid ${theme.palette.primary.main}` }} + data-testid={ paused ? "play" : "pause"} > + { paused ? : } + : // Cronómetro { { answered ? // Pausa - togglePause()} sx={{ height: 100, width: 100, border: `2px solid ${theme.palette.primary.main}` }} data-testid={ paused ? "play" : "pause"} > + togglePause()} sx={{ height: 100, width: 100, border: `2px solid ${theme.palette.primary.main}` }} + data-testid={ paused ? "play" : "pause"} > { paused ? : } : diff --git a/webapp/src/pages/TheChallengeGame.js b/webapp/src/pages/TheChallengeGame.js index 748612ad..8a052d1d 100644 --- a/webapp/src/pages/TheChallengeGame.js +++ b/webapp/src/pages/TheChallengeGame.js @@ -375,9 +375,11 @@ const Game = () => { { answered ? // Pausa - + togglePause()} sx={{ height: 100, width: 100, border: `2px solid ${theme.palette.primary.main}` }} + data-testid={ paused ? "play" : "pause"} > + { paused ? : } + : // Cronómetro Date: Thu, 25 Apr 2024 00:58:25 +0200 Subject: [PATCH 073/132] Finished fising Warm Question game. --- webapp/src/localize/en.json | 7 ++++--- webapp/src/localize/es.json | 13 +++++++------ webapp/src/localize/fr.json | 7 ++++--- webapp/src/pages/WarmQuestionGame.js | 22 ++++++++++++++-------- 4 files changed, 29 insertions(+), 20 deletions(-) diff --git a/webapp/src/localize/en.json b/webapp/src/localize/en.json index 4a297de9..2c3c3d8d 100644 --- a/webapp/src/localize/en.json +++ b/webapp/src/localize/en.json @@ -56,12 +56,13 @@ "lose_msg": "Game Over", "correct": "Correct Answers", "incorrect": "Incorrect Answers", - "money": "Final points", - "time": "Game Time (sec)", + "money": "Final Points", + "time": "Game Seconds", "pause": "Pause", "play": "Play", "round": "Question ", - "start": "Start game", + "start": "Start Game", + "skip": "Skip", "config": { "title": "GAME CONFIGURATION", "num_rounds": "Number of rounds", diff --git a/webapp/src/localize/es.json b/webapp/src/localize/es.json index b97905db..79d0fdd4 100644 --- a/webapp/src/localize/es.json +++ b/webapp/src/localize/es.json @@ -53,15 +53,16 @@ "Game": { "win_msg": "¡Buen trabajo!", - "lose_msg": "Fin del juego", - "correct": "Respuestas correctas", - "incorrect": "Respuestas incorrectas", - "money": "Puntos finales", - "time": "Tiempo de juego (seg)", + "lose_msg": "Fin del Juego", + "correct": "Respuestas Correctas", + "incorrect": "Respuestas Incorrectas", + "money": "Puntos Finales", + "time": "Segundos de Juego", "pause": "Pausa", "play": "Jugar", "round": "Pregunta ", - "start": "Empezar juego", + "start": "Empezar Juego", + "skip": "Saltar", "config": { "title": "CONFIGURACIÓN DEL JUEGO", "num_rounds": "Número de rondas", diff --git a/webapp/src/localize/fr.json b/webapp/src/localize/fr.json index 0dc34adf..50a58d9b 100644 --- a/webapp/src/localize/fr.json +++ b/webapp/src/localize/fr.json @@ -54,15 +54,16 @@ "Game": { "win_msg": "Excellent travail !", - "lose_msg": "Partie terminée", + "lose_msg": "Partie Terminée", "correct": "Réponses Correctes", "incorrect": "Réponses Incorrectes", "money": "Points Finaux", - "time": "Temps de Jeu (sec)", + "time": "Secondes de Jeu", "pause": "Pause", "play": "Jouer", "round": "Question ", - "start": "Commencer à jouer", + "start": "Commencer à Jouer", + "skip": "Sauter", "config": { "title": "CONFIGURATION DU JEU", "num_rounds": "Nombre de tours", diff --git a/webapp/src/pages/WarmQuestionGame.js b/webapp/src/pages/WarmQuestionGame.js index 81d18427..72d230ad 100644 --- a/webapp/src/pages/WarmQuestionGame.js +++ b/webapp/src/pages/WarmQuestionGame.js @@ -1,6 +1,6 @@ import * as React from 'react'; import axios from 'axios'; -import { useTheme, Container, Button, CssBaseline, Grid, Typography, CircularProgress, Card, Box } from '@mui/material'; +import { useTheme, Container, Button, CssBaseline, Grid, Typography, CircularProgress, Card, Box, IconButton } from '@mui/material'; import { PlayArrow, Pause } from '@mui/icons-material'; import CheckIcon from '@mui/icons-material/Check'; import ClearIcon from '@mui/icons-material/Clear'; @@ -302,9 +302,11 @@ const Game = () => { { answered ? // Pausa - + togglePause()} sx={{ height: 100, width: 100, border: `2px solid ${theme.palette.primary.main}` }} + data-testid={ paused ? "play" : "pause"} > + { paused ? : } + : // Cronómetro {
- {!answered && ( - - )} + : + + } {/* Progress Cards */} From 2363c30fb846f97a94e5243c0255e36729a3369d Mon Sep 17 00:00:00 2001 From: uo288245 Date: Thu, 25 Apr 2024 01:03:37 +0200 Subject: [PATCH 074/132] Removed the question template. --- webapp/src/pages/WarmQuestionGame.js | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/webapp/src/pages/WarmQuestionGame.js b/webapp/src/pages/WarmQuestionGame.js index 72d230ad..247e4118 100644 --- a/webapp/src/pages/WarmQuestionGame.js +++ b/webapp/src/pages/WarmQuestionGame.js @@ -104,19 +104,7 @@ const Game = () => { setQuestionData(quest.data); setButtonStates(new Array(quest.data.options.length).fill(null)); }).catch(error => { - // console.error(error); - let quest = {} - quest.data = { - "_id":"1", - "question":"Esta pregunta de prueba resulta de su agrado?", - "options":["Muchísimo","Un cacho","Tope flama","Fino filipino"], - "correctAnswer":"Tope flama", - "categories":["Political"], - "id":"1", - "__v":0 - }; - setQuestionData(quest.data); - setButtonStates(new Array(quest.data.options.length).fill(null)); + console.error(error); }); }; From e52776c53c01c00cb2d1dcf15076f7d990cc32b3 Mon Sep 17 00:00:00 2001 From: uo288245 Date: Thu, 25 Apr 2024 01:07:13 +0200 Subject: [PATCH 075/132] Included the new pause button in the last game that needed it. --- webapp/src/pages/WiseMenStackGame.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/webapp/src/pages/WiseMenStackGame.js b/webapp/src/pages/WiseMenStackGame.js index 436937c7..d589789f 100644 --- a/webapp/src/pages/WiseMenStackGame.js +++ b/webapp/src/pages/WiseMenStackGame.js @@ -1,6 +1,6 @@ import * as React from 'react'; import axios from 'axios'; -import { Container, Box, Button, CssBaseline, Grid, Typography, CircularProgress, Card, Select, MenuItem, useTheme } from '@mui/material'; +import { Container, Box, Button, CssBaseline, Grid, Typography, CircularProgress, Card, Select, MenuItem, IconButton, useTheme } from '@mui/material'; import CheckIcon from '@mui/icons-material/Check'; import ClearIcon from '@mui/icons-material/Clear'; import { PlayArrow, Pause } from '@mui/icons-material'; @@ -343,9 +343,11 @@ const WiseMenStackGame = () => { { answered ? // Pausa - + togglePause()} sx={{ height: 100, width: 100, border: `2px solid ${theme.palette.primary.main}` }} + data-testid={ paused ? "play" : "pause"} > + { paused ? : } + : // Cronómetro Date: Thu, 25 Apr 2024 01:26:23 +0200 Subject: [PATCH 076/132] Solved code duplicity and change of texts in Wise Men tests --- .../__tests__/pages/WiseMenStackGame.test.js | 47 +++++-------------- 1 file changed, 11 insertions(+), 36 deletions(-) diff --git a/webapp/src/__tests__/pages/WiseMenStackGame.test.js b/webapp/src/__tests__/pages/WiseMenStackGame.test.js index ff4961cf..f472f25b 100644 --- a/webapp/src/__tests__/pages/WiseMenStackGame.test.js +++ b/webapp/src/__tests__/pages/WiseMenStackGame.test.js @@ -27,9 +27,6 @@ describe('Wise Men Stack Game component', () => { mockAxios.onPut('http://localhost:8000/statistics').reply(200, { success: true }); mockAxios.onPut('http://localhost:8000/user/questionsRecord').reply(200, { success: true }); - }); - - it('should render configuration, question, answers and other ', async () => { render( @@ -37,8 +34,10 @@ describe('Wise Men Stack Game component', () => { ); + }); - await waitFor(() => screen.getByText('Wise Men Stack')); + it('should render configuration, question, answers and other ', async () => { + await waitFor(() => screen.getByText('GAME CONFIGURATION')); const button = screen.getByText('Start game'); fireEvent.click(button); @@ -49,28 +48,20 @@ describe('Wise Men Stack Game component', () => { //expect(screen.findByText('1/3')); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); - expect(screen.findByText('Which is the capital of Spain?')); + expect(screen.findByText('Which is the capital of Spain?'.toUpperCase())); expect(screen.findByText('Madrid')); }); - it('should guess correct answer', async () => { - render( - - - - - - ); - await waitFor(() => screen.getByText('Wise Men Stack')); + it('should guess correct answer', async () => { await waitFor(() => screen.getByText('GAME CONFIGURATION')); const button = screen.getByText('Start game'); fireEvent.click(button); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); const correctAnswer = screen.getByRole('button', { name: 'Madrid' }); expect(correctAnswer).not.toHaveStyle({ backgroundColor: 'green' }); @@ -85,41 +76,25 @@ describe('Wise Men Stack Game component', () => { }); - it('should choose incorrect answer', async () => { - render( - - - - - - ); - await waitFor(() => screen.getByText('Wise Men Stack')); + it('should choose incorrect answer', async () => { await waitFor(() => screen.getByText('GAME CONFIGURATION')); const button = screen.getByText('Start game'); fireEvent.click(button); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); const buttons = screen.getAllByRole('button'); expect(buttons.length).toBe(2); }); it('should not answer the question', async () => { - render( - - - - - - ); - - await waitFor(() => screen.getByText('Wise Men Stack')); + await waitFor(() => screen.getByText('GAME CONFIGURATION')); const button = screen.getByText('Start game'); fireEvent.click(button); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); setTimeout(() => { // Comprobamos que el callback ha sido llamado después del tiempo especificado From 0f28bdceae403a9acbe832426442d379e6638273 Mon Sep 17 00:00:00 2001 From: Pablo Date: Thu, 25 Apr 2024 01:45:51 +0200 Subject: [PATCH 077/132] Added tests to Wise Men until reach > 80% --- .../__tests__/pages/WiseMenStackGame.test.js | 61 ++++++++++++++++--- webapp/src/pages/WiseMenStackGame.js | 5 +- 2 files changed, 56 insertions(+), 10 deletions(-) diff --git a/webapp/src/__tests__/pages/WiseMenStackGame.test.js b/webapp/src/__tests__/pages/WiseMenStackGame.test.js index f472f25b..0ce29369 100644 --- a/webapp/src/__tests__/pages/WiseMenStackGame.test.js +++ b/webapp/src/__tests__/pages/WiseMenStackGame.test.js @@ -55,29 +55,47 @@ describe('Wise Men Stack Game component', () => { }); - it('should guess correct answer', async () => { await waitFor(() => screen.getByText('GAME CONFIGURATION')); + it('should mark as correct right answer', async () => { + await waitFor(() => screen.getByText('GAME CONFIGURATION')); const button = screen.getByText('Start game'); fireEvent.click(button); // waits for the question to appear await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); + const correctAnswer = screen.getByRole('button', { name: 'Madrid' }); + // now the answer is not selected: + expect(screen.findByTestId("anwer0")); + // after clicking it has changed to succeeded: + fireEvent.click(correctAnswer); + expect(screen.findByTestId("succes0")); - expect(correctAnswer).not.toHaveStyle({ backgroundColor: 'green' }); + }); - //selects correct answer - fireEvent.click(correctAnswer); + it('should mark as incorrect another answer', async () => { + await waitFor(() => screen.getByText('GAME CONFIGURATION')); + + const button = screen.getByText('Start game'); + fireEvent.click(button); + + // waits for the question to appear + await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); - //expect(screen.findByText('1')).toHaveStyle({ backgroundColor: 'lightgreen' }); + const answers = screen.getAllByRole('button'); + const incorrectAnswer = answers[0].name === 'Madrid' ? answers[1] : answers[0]; + const id = answers[0].name === 'Madrid' ? 1 : 0; - expect(correctAnswer).toHaveStyle({ backgroundColor: 'green' }); + // now the answer is not selected: + expect(screen.findByTestId(`anwer${id}`)); + // after clicking it has changed to succeeded: + fireEvent.click(incorrectAnswer); + expect(screen.findByTestId(`failure${id}`)); }); - it('should choose incorrect answer', async () => { await waitFor(() => screen.getByText('GAME CONFIGURATION')); - + it('should only show 2 answers', async () => { await waitFor(() => screen.getByText('GAME CONFIGURATION')); const button = screen.getByText('Start game'); fireEvent.click(button); @@ -103,4 +121,31 @@ describe('Wise Men Stack Game component', () => { }, 4500); + it('should render pause & play buttons when answered', async () => { + await waitFor(() => screen.getByText('GAME CONFIGURATION')); + const button = screen.getByText('Start game'); + fireEvent.click(button); + + await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); + const correctAnswer = screen.getByRole('button', { name: 'Madrid' }); + fireEvent.click(correctAnswer); + + const pauseButton = screen.getByTestId("pause"); + expect(pauseButton); + fireEvent.click(pauseButton); + expect(screen.getByTestId("play")); + }) + + it('should render progress bar', async () => { + await waitFor(() => screen.getByText('GAME CONFIGURATION')); + const button = screen.getByText('Start game'); + fireEvent.click(button); + + await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); + const progressBar = screen.getByTestId('prog_bar0'); + await expect(progressBar).toBeInTheDocument(); + }) + + + }); diff --git a/webapp/src/pages/WiseMenStackGame.js b/webapp/src/pages/WiseMenStackGame.js index 436937c7..5e1a00e6 100644 --- a/webapp/src/pages/WiseMenStackGame.js +++ b/webapp/src/pages/WiseMenStackGame.js @@ -225,7 +225,8 @@ const WiseMenStackGame = () => { const questionHistorialBar = () => { return questionHistorial.map((isCorrect, index) => ( - + )); }; @@ -382,7 +383,7 @@ const WiseMenStackGame = () => { {questionHistorialBar()} - { answered || round === 1 ? : } + { answered || round === 1 ? : } ); From 38882e9603d81b607b6cd1820def28a6342682be Mon Sep 17 00:00:00 2001 From: Pablo Date: Thu, 25 Apr 2024 01:52:25 +0200 Subject: [PATCH 078/132] Added test-ids to test progress bars in games --- webapp/src/pages/DiscoveringCitiesGame.js | 3 ++- webapp/src/pages/Game.js | 3 ++- webapp/src/pages/TheChallengeGame.js | 9 +++++---- webapp/src/pages/WarmQuestionGame.js | 3 ++- 4 files changed, 11 insertions(+), 7 deletions(-) diff --git a/webapp/src/pages/DiscoveringCitiesGame.js b/webapp/src/pages/DiscoveringCitiesGame.js index 2cbb9168..82da3491 100644 --- a/webapp/src/pages/DiscoveringCitiesGame.js +++ b/webapp/src/pages/DiscoveringCitiesGame.js @@ -215,7 +215,8 @@ const DiscovertingCitiesGame = () => { const questionHistorialBar = () => { return questionHistorial.map((isCorrect, index) => ( - + )); }; diff --git a/webapp/src/pages/Game.js b/webapp/src/pages/Game.js index efe629ef..9f5d1245 100644 --- a/webapp/src/pages/Game.js +++ b/webapp/src/pages/Game.js @@ -214,7 +214,8 @@ const Game = () => { const questionHistorialBar = () => { return questionHistorial.map((isCorrect, index) => ( - + )); }; diff --git a/webapp/src/pages/TheChallengeGame.js b/webapp/src/pages/TheChallengeGame.js index 8a052d1d..7358368e 100644 --- a/webapp/src/pages/TheChallengeGame.js +++ b/webapp/src/pages/TheChallengeGame.js @@ -309,10 +309,11 @@ const Game = () => { const questionHistorialBar = () => { return questionHistorial.map((isCorrect, index) => ( - )); diff --git a/webapp/src/pages/WarmQuestionGame.js b/webapp/src/pages/WarmQuestionGame.js index 247e4118..3d4881b2 100644 --- a/webapp/src/pages/WarmQuestionGame.js +++ b/webapp/src/pages/WarmQuestionGame.js @@ -240,7 +240,8 @@ const Game = () => { const questionHistorialBar = () => { return questionHistorial.map((isCorrect, index) => ( - + )); }; From 962e9113ece401d8ceca8d902cfdc43062502cf4 Mon Sep 17 00:00:00 2001 From: Pablo Date: Thu, 25 Apr 2024 01:58:55 +0200 Subject: [PATCH 079/132] Why TF is this test suite failing if i execute all but passes individually --- .../src/__tests__/pages/WiseMenStackGame.test.js | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/webapp/src/__tests__/pages/WiseMenStackGame.test.js b/webapp/src/__tests__/pages/WiseMenStackGame.test.js index 0ce29369..4bde1f8d 100644 --- a/webapp/src/__tests__/pages/WiseMenStackGame.test.js +++ b/webapp/src/__tests__/pages/WiseMenStackGame.test.js @@ -39,7 +39,7 @@ describe('Wise Men Stack Game component', () => { it('should render configuration, question, answers and other ', async () => { await waitFor(() => screen.getByText('GAME CONFIGURATION')); - const button = screen.getByText('Start game'); + const button = screen.getByTestId('start-button'); fireEvent.click(button); //expect(screen.getByRole('progressbar')); @@ -58,7 +58,7 @@ describe('Wise Men Stack Game component', () => { it('should mark as correct right answer', async () => { await waitFor(() => screen.getByText('GAME CONFIGURATION')); - const button = screen.getByText('Start game'); + const button = screen.getByTestId('start-button'); fireEvent.click(button); // waits for the question to appear @@ -76,7 +76,7 @@ describe('Wise Men Stack Game component', () => { it('should mark as incorrect another answer', async () => { await waitFor(() => screen.getByText('GAME CONFIGURATION')); - const button = screen.getByText('Start game'); + const button = screen.getByTestId('start-button'); fireEvent.click(button); // waits for the question to appear @@ -96,7 +96,7 @@ describe('Wise Men Stack Game component', () => { it('should only show 2 answers', async () => { await waitFor(() => screen.getByText('GAME CONFIGURATION')); - const button = screen.getByText('Start game'); + const button = screen.getByTestId('start-button'); fireEvent.click(button); // waits for the question to appear @@ -108,7 +108,7 @@ describe('Wise Men Stack Game component', () => { it('should not answer the question', async () => { await waitFor(() => screen.getByText('GAME CONFIGURATION')); - const button = screen.getByText('Start game'); + const button = screen.getByTestId('start-button'); fireEvent.click(button); // waits for the question to appear @@ -123,7 +123,7 @@ describe('Wise Men Stack Game component', () => { it('should render pause & play buttons when answered', async () => { await waitFor(() => screen.getByText('GAME CONFIGURATION')); - const button = screen.getByText('Start game'); + const button = screen.getByTestId('start-button'); fireEvent.click(button); await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); @@ -138,7 +138,7 @@ describe('Wise Men Stack Game component', () => { it('should render progress bar', async () => { await waitFor(() => screen.getByText('GAME CONFIGURATION')); - const button = screen.getByText('Start game'); + const button = screen.getByTestId('start-button'); fireEvent.click(button); await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); @@ -146,6 +146,4 @@ describe('Wise Men Stack Game component', () => { await expect(progressBar).toBeInTheDocument(); }) - - }); From 4f9ffaaba1b2e3ef2896334cd4f6cec39eeab4ff Mon Sep 17 00:00:00 2001 From: Pablo Date: Thu, 25 Apr 2024 02:02:56 +0200 Subject: [PATCH 080/132] OMG I am a genius --- webapp/src/__tests__/pages/WiseMenStackGame.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webapp/src/__tests__/pages/WiseMenStackGame.test.js b/webapp/src/__tests__/pages/WiseMenStackGame.test.js index 4bde1f8d..ee332810 100644 --- a/webapp/src/__tests__/pages/WiseMenStackGame.test.js +++ b/webapp/src/__tests__/pages/WiseMenStackGame.test.js @@ -4,7 +4,7 @@ import { SessionContext } from '../../SessionContext'; // Importa el contexto ne import { BrowserRouter as Router } from 'react-router-dom'; import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; -import Game from '../../pages/WiseMenStackGame'; +import WiseMenStack from '../../pages/WiseMenStackGame'; import '../../localize/i18n'; import { expect } from 'expect-puppeteer'; @@ -30,7 +30,7 @@ describe('Wise Men Stack Game component', () => { render( - + ); From 9fb059213916b23b9dd71a35130a74f82feb21fc Mon Sep 17 00:00:00 2001 From: Pablo Date: Thu, 25 Apr 2024 02:23:19 +0200 Subject: [PATCH 081/132] =?UTF-8?q?=C3=81ureo=20update=20of=20the=20challe?= =?UTF-8?q?nge=20form?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webapp/src/pages/TheChallengeGame.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/webapp/src/pages/TheChallengeGame.js b/webapp/src/pages/TheChallengeGame.js index 7358368e..0ff7382e 100644 --- a/webapp/src/pages/TheChallengeGame.js +++ b/webapp/src/pages/TheChallengeGame.js @@ -1,6 +1,6 @@ import * as React from 'react'; import axios from 'axios'; -import { Container, Box, Button, CssBaseline, Grid, Typography, CircularProgress, useTheme, MenuItem, Select, IconButton } from '@mui/material'; +import { Container, Box, Button, CssBaseline, Grid, Typography, CircularProgress, useTheme, MenuItem, Select, IconButton, Paper } from '@mui/material'; import CheckIcon from '@mui/icons-material/Check'; import ClearIcon from '@mui/icons-material/Clear'; import { useNavigate } from 'react-router-dom'; @@ -231,12 +231,13 @@ const Game = () => { if (configModalOpen) { return( - + + {t("Game.config.title")} - + {t("Game.config.num_rounds")}: @@ -282,7 +283,7 @@ const Game = () => { {t("Game.categories.sports")} - + + ); } From b328472463c9b802eff9640c288ad8be1a70ef6a Mon Sep 17 00:00:00 2001 From: Pablo Date: Thu, 25 Apr 2024 02:30:36 +0200 Subject: [PATCH 082/132] Auricidad applied also to Wise Men --- webapp/src/pages/WiseMenStackGame.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/webapp/src/pages/WiseMenStackGame.js b/webapp/src/pages/WiseMenStackGame.js index b34f3679..bad3fce1 100644 --- a/webapp/src/pages/WiseMenStackGame.js +++ b/webapp/src/pages/WiseMenStackGame.js @@ -1,6 +1,6 @@ import * as React from 'react'; import axios from 'axios'; -import { Container, Box, Button, CssBaseline, Grid, Typography, CircularProgress, Card, Select, MenuItem, IconButton, useTheme } from '@mui/material'; +import { Container, Box, Button, CssBaseline, Grid, Typography, CircularProgress, Card, Select, MenuItem, IconButton, useTheme, Paper } from '@mui/material'; import CheckIcon from '@mui/icons-material/Check'; import ClearIcon from '@mui/icons-material/Clear'; import { PlayArrow, Pause } from '@mui/icons-material'; @@ -237,7 +237,8 @@ const WiseMenStackGame = () => { if(!isConfigured) { return ( - + + {t("Game.config.title")} @@ -290,6 +291,7 @@ const WiseMenStackGame = () => { > {t("Game.start")} + ); } From 3d4c22148b527c162011326ada1922b85690a893 Mon Sep 17 00:00:00 2001 From: Pablo Date: Thu, 25 Apr 2024 03:02:12 +0200 Subject: [PATCH 083/132] Updated multiplayer first screen style --- webapp/src/localize/en.json | 3 +- webapp/src/localize/es.json | 3 +- webapp/src/localize/fr.json | 3 +- webapp/src/pages/MultiplayerRoom.js | 159 +++++++++++++++++----------- 4 files changed, 103 insertions(+), 65 deletions(-) diff --git a/webapp/src/localize/en.json b/webapp/src/localize/en.json index 2c3c3d8d..e191856e 100644 --- a/webapp/src/localize/en.json +++ b/webapp/src/localize/en.json @@ -148,7 +148,8 @@ "join": "Join room", "send": "Send", "chat_title": "Chat of the room", - "chat_input_label": "Type your message" + "chat_input_label": "Type your message", + "new_game": "Want to start a new game?" }, "Game": { "waiting_players_end": "Waiting for players end...", diff --git a/webapp/src/localize/es.json b/webapp/src/localize/es.json index 79d0fdd4..e674ed28 100644 --- a/webapp/src/localize/es.json +++ b/webapp/src/localize/es.json @@ -148,7 +148,8 @@ "join": "Unirse a sala", "send": "Enviar", "chat_title": "Chat de la sala", - "chat_input_label": "Escribe tu mensaje" + "chat_input_label": "Escribe tu mensaje", + "new_game": "¿Quieres iniciar un juego nuevo?" }, "Game": { "waiting_players_end": "Esperando a que terminen los demás jugadores...", diff --git a/webapp/src/localize/fr.json b/webapp/src/localize/fr.json index 50a58d9b..bbc12ec7 100644 --- a/webapp/src/localize/fr.json +++ b/webapp/src/localize/fr.json @@ -146,7 +146,8 @@ "join": "Rejoindre une salle", "send": "Envoyer", "chat_title": "Discussion de la salle", - "chat_input_label": "Tape ton message" + "chat_input_label": "Tape ton message", + "new_game": "Veux toi un neuveax jue?" }, "Game": { "waiting_players_end": "En attendant que tous les joueurs finissent...", diff --git a/webapp/src/pages/MultiplayerRoom.js b/webapp/src/pages/MultiplayerRoom.js index 09316784..6a3043f8 100644 --- a/webapp/src/pages/MultiplayerRoom.js +++ b/webapp/src/pages/MultiplayerRoom.js @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react'; -import { Button, TextField, Typography, Grid, Paper, List, ListItem, CircularProgress } from '@mui/material'; +import { useTheme, Button, TextField, Typography, Grid, Paper, List, ListItem, CircularProgress, Container, Box } from '@mui/material'; import io from 'socket.io-client'; import { useContext } from 'react'; import { SessionContext } from '../SessionContext'; @@ -11,6 +11,7 @@ const socketEndpoint = process.env.REACT_APP_MULTIPLAYER_ENDPOINT || 'http://loc const MultiplayerRoom = () => { const { t } = useTranslation(); + const theme = useTheme(); const [roomCode, setRoomCode] = useState(""); const [error, setError] = useState(""); @@ -105,74 +106,108 @@ const MultiplayerRoom = () => { } return ( - - - - {roomCode && error === "" ? ( - <> - - { t("Multiplayer.Room.code") }: - - - {roomCode} - - - - { t("Multiplayer.Room.participants") }: + + + + {t("Games.Multiplayer.name").toUpperCase()} + + + {roomCode && error === "" ? ( + <> + + { t("Multiplayer.Room.code") }: + + + {roomCode} + + + + { t("Multiplayer.Room.participants") }: + + + {roomPlayers.map((player, index) => ( + + {player} + + ))} + + + {loadingQuestions && ( +
+ + Loading questions... +
+ )} + + ) : ( + + + + { t("Multiplayer.Room.join") } + + setWrittenCode(e.target.value)} + /> + + {error && ( + + {error} - - {roomPlayers.map((player, index) => ( - - {player} - - ))} - - - {loadingQuestions && ( -
- - Loading questions... -
)} - - ) : ( - <> - - { t("Multiplayer.Room.create") } - - - - { t("Multiplayer.Room.join") } - - setWrittenCode(e.target.value)} - style={{ marginTop: '10px' }} - /> - - {error && ( - - {error} - - )} - - )} -
-
+ + + + + { t("Multiplayer.Room.new_game") } + + + +
+ )} {roomCode && error === "" && ( )} - + +
); } From b849aff1a1243369a0659d580c50a1b83d7ae5c0 Mon Sep 17 00:00:00 2001 From: uo288543 Date: Thu, 25 Apr 2024 10:13:43 +0200 Subject: [PATCH 084/132] move icon to home and make examples --- webapp/src/components/Footer.js | 12 +-------- webapp/src/pages/Home.js | 44 +++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 11 deletions(-) diff --git a/webapp/src/components/Footer.js b/webapp/src/components/Footer.js index 164ff8fe..68ce0462 100644 --- a/webapp/src/components/Footer.js +++ b/webapp/src/components/Footer.js @@ -1,7 +1,7 @@ import * as React from 'react'; import { AppBar, Toolbar, Typography, Link } from '@mui/material'; import { useTranslation } from 'react-i18next'; -import AndroidIcon from '@mui/icons-material/Android'; + const Footer = () => { const { t } = useTranslation(); @@ -22,16 +22,6 @@ const Footer = () => { {t("Footer.api_users")} - - - ); diff --git a/webapp/src/pages/Home.js b/webapp/src/pages/Home.js index fcfa9336..fb41bba4 100644 --- a/webapp/src/pages/Home.js +++ b/webapp/src/pages/Home.js @@ -2,6 +2,7 @@ import * as React from "react"; import {Box, Button} from "@mui/material"; import useMediaQuery from '@mui/material/useMediaQuery'; import { useTranslation } from 'react-i18next'; +import AndroidIcon from '@mui/icons-material/Android'; const Home = () => { const xxl = useMediaQuery('(min-width:1920px)'); @@ -102,6 +103,49 @@ const Home = () => { + + + + + + + + + + + ); }; From 7e7aba144a6bdd980e43e83b35637a46b47b973c Mon Sep 17 00:00:00 2001 From: uo288543 Date: Thu, 25 Apr 2024 10:28:17 +0200 Subject: [PATCH 085/132] add fav button --- webapp/src/pages/Home.js | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/webapp/src/pages/Home.js b/webapp/src/pages/Home.js index fb41bba4..d2447abb 100644 --- a/webapp/src/pages/Home.js +++ b/webapp/src/pages/Home.js @@ -1,5 +1,5 @@ import * as React from "react"; -import {Box, Button} from "@mui/material"; +import {Box, Button, Fab, useTheme } from "@mui/material"; import useMediaQuery from '@mui/material/useMediaQuery'; import { useTranslation } from 'react-i18next'; import AndroidIcon from '@mui/icons-material/Android'; @@ -7,6 +7,8 @@ import AndroidIcon from '@mui/icons-material/Android'; const Home = () => { const xxl = useMediaQuery('(min-width:1920px)'); const { t } = useTranslation(); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down('sm')); const styles = { logo:{ @@ -142,10 +144,40 @@ const Home = () => { color="primary" startIcon={} style={{ marginTop: '0.5em' }} + sx={{ + '&:hover': { + border: `2px solid #3DDC84`, + backgroundColor: 'primary.light', + }, + }} > {t("Footer.apk_link")} + + + + + + + + + ); }; From 7c29ba861d7f60b70857c77cae56a6aa1124403e Mon Sep 17 00:00:00 2001 From: uo288543 Date: Thu, 25 Apr 2024 11:32:14 +0200 Subject: [PATCH 086/132] Add tooltip --- webapp/src/pages/Home.js | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/webapp/src/pages/Home.js b/webapp/src/pages/Home.js index d2447abb..f56d30c1 100644 --- a/webapp/src/pages/Home.js +++ b/webapp/src/pages/Home.js @@ -1,5 +1,5 @@ import * as React from "react"; -import {Box, Button, Fab, useTheme } from "@mui/material"; +import {Box, Button, Fab, useTheme, Tooltip } from "@mui/material"; import useMediaQuery from '@mui/material/useMediaQuery'; import { useTranslation } from 'react-i18next'; import AndroidIcon from '@mui/icons-material/Android'; @@ -167,14 +167,16 @@ const Home = () => { target="_blank" rel="noopener noreferrer" > - - - + {/* TODO */} + + + + From ccdb76eae42cab54c300afa277e0969404e55ff2 Mon Sep 17 00:00:00 2001 From: uo288245 Date: Thu, 25 Apr 2024 11:35:07 +0200 Subject: [PATCH 087/132] Improved the default game managment. --- webapp/src/pages/Homepage.js | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/webapp/src/pages/Homepage.js b/webapp/src/pages/Homepage.js index 7f38eacf..8044146f 100644 --- a/webapp/src/pages/Homepage.js +++ b/webapp/src/pages/Homepage.js @@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next'; const Homepage = () => { const xxl = useMediaQuery('(min-width:1920px)'); + const { t } = useTranslation(); const styles = React.useMemo(() => ({ @@ -100,10 +101,10 @@ const Homepage = () => { const [info, setInfo] = React.useState(null); // Link to each game page - const [gameLink, setGameLink] = React.useState("/game"); + const [gameLink, setGameLink] = React.useState("/wiseMenStackGame"); //Selected index - const [activeIndex, setActiveIndex] = React.useState(0); // Nuevo estado para el índice activo + const [activeIndex, setActiveIndex] = React.useState(0); //if online mode -> change link to go to online room const changeGameLink = React.useCallback((index) => { @@ -166,7 +167,7 @@ const Homepage = () => { // Show the information of the first game displayGames(info); } - }, [info, displayGames]); // <- Add info to the dependency array + }, [info, displayGames]); const videoRef = React.useRef(null); React.useEffect(() => {if (videoRef.current) {videoRef.current.playbackRate = 0.85;}}, []); @@ -174,10 +175,10 @@ const Homepage = () => { return ( { t("Homepage.title") } - {games} + {games} ); From 8c72e62a649dc24a8f230914b7a72617bc47fe74 Mon Sep 17 00:00:00 2001 From: uo288245 Date: Thu, 25 Apr 2024 11:47:18 +0200 Subject: [PATCH 088/132] Adapted the Wise Men Stack tests to the new style of its view. --- webapp/src/__tests__/pages/WiseMenStackGame.test.js | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/webapp/src/__tests__/pages/WiseMenStackGame.test.js b/webapp/src/__tests__/pages/WiseMenStackGame.test.js index ee332810..3e40a50b 100644 --- a/webapp/src/__tests__/pages/WiseMenStackGame.test.js +++ b/webapp/src/__tests__/pages/WiseMenStackGame.test.js @@ -40,12 +40,8 @@ describe('Wise Men Stack Game component', () => { await waitFor(() => screen.getByText('GAME CONFIGURATION')); const button = screen.getByTestId('start-button'); - fireEvent.click(button); - - //expect(screen.getByRole('progressbar')); - expect(screen.findByText('1')); - expect(screen.findByText('Question 1')); - //expect(screen.findByText('1/3')); + // clicks the start button to show the first question + fireEvent.click(button); // waits for the question to appear await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); From ee9cd43714874b8493fcc29e0ffc52c3d7e5f5ad Mon Sep 17 00:00:00 2001 From: uo288245 Date: Thu, 25 Apr 2024 12:20:59 +0200 Subject: [PATCH 089/132] Improved Warm Question Game calling. --- webapp/src/App.js | 4 ++-- webapp/src/pages/WarmQuestionGame.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/webapp/src/App.js b/webapp/src/App.js index eb8254d5..c7b0397f 100644 --- a/webapp/src/App.js +++ b/webapp/src/App.js @@ -17,7 +17,7 @@ import Profile from './pages/Profile' import MultiplayerRoom from './pages/MultiplayerRoom'; import MultiplayerGame from './pages/MultiplayerGame'; import TheChallengeGame from './pages/TheChallengeGame'; -import WarmQuestion from './pages/WarmQuestionGame'; +import WarmQuestionGame from './pages/WarmQuestionGame'; import {Route, Routes} from 'react-router-dom'; import { createTheme, ThemeProvider } from '@mui/material/styles'; import { Box } from '@mui/material'; @@ -66,7 +66,7 @@ function App() { }/> }/> }/> - }/> + }/> }/> } /> }/> diff --git a/webapp/src/pages/WarmQuestionGame.js b/webapp/src/pages/WarmQuestionGame.js index 3d4881b2..705a15d4 100644 --- a/webapp/src/pages/WarmQuestionGame.js +++ b/webapp/src/pages/WarmQuestionGame.js @@ -14,7 +14,7 @@ import i18n from '../localize/i18n'; const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000'; -const Game = () => { +const WarmQuestionGame = () => { const navigate = useNavigate(); const MAX_ROUNDS = 10; const SUCCESS_SOUND_ROUTE = "/sounds/success_sound.mp3"; @@ -348,4 +348,4 @@ const Game = () => { ); }; -export default Game; \ No newline at end of file +export default WarmQuestionGame; \ No newline at end of file From 1c32683a6e0c1e4ca2a205dbaf26dcc8d20ffe0f Mon Sep 17 00:00:00 2001 From: uo288245 Date: Thu, 25 Apr 2024 12:23:18 +0200 Subject: [PATCH 090/132] Updated the Warm Question Game tests to match the new view style. --- .../__tests__/pages/WarmQuestionGame.test.js | 43 ++++++++----------- 1 file changed, 19 insertions(+), 24 deletions(-) diff --git a/webapp/src/__tests__/pages/WarmQuestionGame.test.js b/webapp/src/__tests__/pages/WarmQuestionGame.test.js index 6297a0d5..0e955ac7 100644 --- a/webapp/src/__tests__/pages/WarmQuestionGame.test.js +++ b/webapp/src/__tests__/pages/WarmQuestionGame.test.js @@ -4,11 +4,11 @@ import { SessionContext } from '../../SessionContext'; import { BrowserRouter as Router } from 'react-router-dom'; import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; -import Game from '../../pages/WarmQuestionGame'; +import WarmQuestionGame from '../../pages/WarmQuestionGame'; const mockAxios = new MockAdapter(axios); -describe('Game component', () => { +describe('WarmQuestionGame component', () => { beforeEach(() => { mockAxios.reset(); // Mock the axios.post request to simulate a successful response @@ -30,18 +30,18 @@ describe('Game component', () => { render( - + ); // Espera a que aparezca la pregunta - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByTestId('question')); expect(screen.findByText('1')); // Verifica que el juego haya comenzado correctamente mostrando la pregunta y las opciones - expect(screen.getByText('Which is the capital of Spain?')).toBeInTheDocument(); + expect(screen.getByTestId('question')).toBeInTheDocument(); expect(screen.getByText('Madrid')).toBeInTheDocument(); expect(screen.getByText('Barcelona')).toBeInTheDocument(); expect(screen.getByText('Paris')).toBeInTheDocument(); @@ -52,23 +52,21 @@ describe('Game component', () => { render( - + ); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByTestId('question')); const correctAnswer = screen.getByRole('button', { name: 'Madrid' }); - expect(correctAnswer).not.toHaveStyle({ backgroundColor: 'green' }); + expect(correctAnswer).toHaveStyle({ backgroundColor: 'rgb(0, 102, 153);' }); //selects correct answer fireEvent.click(correctAnswer); - //expect(screen.findByText('1')).toHaveStyle({ backgroundColor: 'lightgreen' }); - - expect(correctAnswer).toHaveStyle({ backgroundColor: 'green' }); + expect(correctAnswer).toHaveStyle({ backgroundColor: 'rgb(51, 153, 102);' }); }); @@ -77,22 +75,21 @@ describe('Game component', () => { render( - + ); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByTestId('question')); const incorrectAnswer = screen.getByRole('button', { name: 'Barcelona' }); - expect(incorrectAnswer).not.toHaveStyle({ backgroundColor: 'red' }); + expect(incorrectAnswer).toHaveStyle({ backgroundColor: 'rgb(0, 102, 153);' }); //selects correct answer fireEvent.click(incorrectAnswer); - expect(incorrectAnswer).toHaveStyle({ backgroundColor: 'red' }); - //expect(screen.findByText('1')).toHaveStyle({ backgroundColor: 'salmon' }); + expect(incorrectAnswer).toHaveStyle({ backgroundColor: 'rgb(153, 0, 0);' }); }); @@ -100,13 +97,13 @@ describe('Game component', () => { render( - + ); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByTestId('question')); setTimeout(() => { // Comprobamos que el callback ha sido llamado después del tiempo especificado @@ -119,24 +116,22 @@ describe('Game component', () => { render( - + ); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByTestId('question')); const correctAnswer = screen.getByRole('button', { name: 'Madrid' }); const skip = screen.getByRole('button', { name: 'Skip' }); - expect(correctAnswer).not.toHaveStyle({ backgroundColor: 'green' }); + expect(correctAnswer).toHaveStyle({ backgroundColor: 'rgb(0, 102, 153);' }); //selects correct answer fireEvent.click(skip); - //expect(screen.findByText('1')).toHaveStyle({ backgroundColor: 'lightgreen' }); - - expect(correctAnswer).toHaveStyle({ backgroundColor: 'green' }); + expect(correctAnswer).toHaveStyle({ backgroundColor: 'rgb(51, 153, 102);' }); }); From 6c6d2d08b699625d871f7d21fc76d8897ba33398 Mon Sep 17 00:00:00 2001 From: uo288245 Date: Thu, 25 Apr 2024 12:46:05 +0200 Subject: [PATCH 091/132] Improved and adapted the Challenge game tests to the new style. --- .../__tests__/pages/TheChallengeGame.test.js | 70 +++++++++++++------ webapp/src/pages/TheChallengeGame.js | 8 +-- 2 files changed, 51 insertions(+), 27 deletions(-) diff --git a/webapp/src/__tests__/pages/TheChallengeGame.test.js b/webapp/src/__tests__/pages/TheChallengeGame.test.js index 9627bba8..6ed2b6d2 100644 --- a/webapp/src/__tests__/pages/TheChallengeGame.test.js +++ b/webapp/src/__tests__/pages/TheChallengeGame.test.js @@ -38,22 +38,20 @@ describe('Game component', () => { ); // Espera a que aparezca la ventana de configuración - await waitFor(() => screen.getByText('Game Configuration')); + await waitFor(() => screen.getByText('GAME CONFIGURATION')); // Simula la configuración del juego - const increaseButtons = screen.getAllByRole('button', { name: '+' }); - fireEvent.click(increaseButtons[0]); // Aumenta el número de rondas - fireEvent.click(increaseButtons[1]); // Aumenta el tiempo por pregunta - //fireEvent.change(screen.getByLabelText('Category:'), { target: { value: 'Sports' } }); + const increaseButton = screen.getByTestId('addRound'); + fireEvent.click(increaseButton); // Aumenta el número de rondas // Inicia el juego - fireEvent.click(screen.getByRole('button', { name: 'Start game' })); + fireEvent.click(screen.getByRole('button', { name: 'Start Game' })); // Espera a que aparezca la pregunta - await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); + await waitFor(() => screen.getByTestId('question')); // Verifica que el juego haya comenzado correctamente mostrando la pregunta y las opciones - expect(screen.getByText('Which is the capital of Spain?'.toUpperCase())).toBeInTheDocument(); + expect(screen.getByTestId('question')).toBeInTheDocument(); expect(screen.getByText('Madrid')).toBeInTheDocument(); expect(screen.getByText('Barcelona')).toBeInTheDocument(); expect(screen.getByText('Paris')).toBeInTheDocument(); @@ -70,17 +68,19 @@ describe('Game component', () => { ); // Espera a que aparezca la ventana de configuración - await waitFor(() => screen.getByText('Game Configuration')); + await waitFor(() => screen.getByText('GAME CONFIGURATION')); // Simula la configuración del juego - const increaseButtons = screen.getAllByRole('button', { name: '+' }); - fireEvent.click(increaseButtons[0]); // Aumenta el número de rondas + const increaseRoundButton = screen.getByTestId('addRound'); + fireEvent.click(increaseRoundButton); // Aumenta el número de rondas + const increaseSecondsButton = screen.getByTestId('addSecond'); + fireEvent.click(increaseSecondsButton); // Aumenta los segundos por ronda // Inicia el juego - fireEvent.click(screen.getByRole('button', { name: 'Start game' })); + fireEvent.click(screen.getByRole('button', { name: 'Start Game' })); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); + await waitFor(() => screen.getByTestId('question')); const correctAnswer = screen.getByRole('button', { name: 'Madrid' }); expect(screen.findByTestId("anwer0")); @@ -101,17 +101,17 @@ describe('Game component', () => { ); // Espera a que aparezca la ventana de configuración - await waitFor(() => screen.getByText('Game Configuration')); + await waitFor(() => screen.getByText('GAME CONFIGURATION')); // Simula la configuración del juego - const increaseButtons = screen.getAllByRole('button', { name: '+' }); - fireEvent.click(increaseButtons[0]); // Aumenta el número de rondas + const increaseButton = screen.getByTestId('addRound'); + fireEvent.click(increaseButton); // Aumenta el número de rondas // Inicia el juego - fireEvent.click(screen.getByRole('button', { name: 'Start game' })); + fireEvent.click(screen.getByRole('button', { name: 'Start Game' })); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); + await waitFor(() => screen.getByTestId('question')); const incorrectAnswer = screen.getByRole('button', { name: 'Barcelona' }); expect(screen.findByTestId("anwer1")); @@ -131,17 +131,17 @@ describe('Game component', () => { ); // Espera a que aparezca la ventana de configuración - await waitFor(() => screen.getByText('Game Configuration')); + await waitFor(() => screen.getByText('GAME CONFIGURATION')); // Simula la configuración del juego - const increaseButtons = screen.getAllByRole('button', { name: '+' }); - fireEvent.click(increaseButtons[0]); // Aumenta el número de rondas + const increaseButton = screen.getByTestId('addRound'); + fireEvent.click(increaseButton); // Aumenta el número de rondas // Inicia el juego - fireEvent.click(screen.getByRole('button', { name: 'Start game' })); + fireEvent.click(screen.getByRole('button', { name: 'Start Game' })); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); + await waitFor(() => screen.getByTestId('question')); setTimeout(() => { // Comprobamos que el callback ha sido llamado después del tiempo especificado @@ -150,4 +150,28 @@ describe('Game component', () => { }, 4500); + it('should pause and resume the game after answering a question', async () => { + render( + + + + + + ); + + await waitFor(() => screen.getByText('GAME CONFIGURATION')); + fireEvent.click(screen.getByTestId('addRound')); + fireEvent.click(screen.getByRole('button', { name: 'Start Game' })); + + await waitFor(() => screen.getByTestId('question')); + + fireEvent.click(screen.getByRole('button', { name: 'Madrid' })); + + await waitFor(() => screen.getByTestId('pause')); + + fireEvent.click(screen.getByTestId('pause')); + + expect(screen.getByTestId('play')).toBeInTheDocument(); +}); + }); \ No newline at end of file diff --git a/webapp/src/pages/TheChallengeGame.js b/webapp/src/pages/TheChallengeGame.js index 0ff7382e..1f03a70f 100644 --- a/webapp/src/pages/TheChallengeGame.js +++ b/webapp/src/pages/TheChallengeGame.js @@ -242,13 +242,13 @@ const Game = () => { {t("Game.config.num_rounds")}: - setNumRounds(numRounds - 1)} variant="outlined" > + setNumRounds(numRounds - 1)} variant="outlined" data-testId="removeRound"> {numRounds} - setNumRounds(numRounds + 1)} variant="outlined"> + setNumRounds(numRounds + 1)} variant="outlined" data-testId="addRound"> @@ -257,13 +257,13 @@ const Game = () => { {t("Game.config.time")}: - setTimerConfig(timerConfig - 1)} variant="outlined"> + setTimerConfig(timerConfig - 1)} variant="outlined" data-testId="removeSecond"> {timerConfig} - setTimerConfig(timerConfig + 1)} variant="outlined"> + setTimerConfig(timerConfig + 1)} variant="outlined" data-testId="addSecond"> From ea5129994730f4f27f67d374996250dda3ffdbaf Mon Sep 17 00:00:00 2001 From: uo288245 Date: Thu, 25 Apr 2024 15:14:51 +0200 Subject: [PATCH 092/132] Fixed the Challenge game tests. --- .../__tests__/pages/TheChallengeGame.test.js | 18 +++++++++--------- webapp/src/pages/TheChallengeGame.js | 4 ++-- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/webapp/src/__tests__/pages/TheChallengeGame.test.js b/webapp/src/__tests__/pages/TheChallengeGame.test.js index 6ed2b6d2..130b501b 100644 --- a/webapp/src/__tests__/pages/TheChallengeGame.test.js +++ b/webapp/src/__tests__/pages/TheChallengeGame.test.js @@ -5,11 +5,11 @@ import { BrowserRouter as Router } from 'react-router-dom'; import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import '../../localize/i18n'; -import Game from '../../pages/TheChallengeGame'; +import TheChallengeGame from '../../pages/TheChallengeGame'; const mockAxios = new MockAdapter(axios); -describe('Game component', () => { +describe('The Challenge component', () => { beforeEach(() => { mockAxios.reset(); // Mockear respuestas de la API @@ -32,7 +32,7 @@ describe('Game component', () => { render( - + ); @@ -62,7 +62,7 @@ describe('Game component', () => { render( - + ); @@ -83,9 +83,9 @@ describe('Game component', () => { await waitFor(() => screen.getByTestId('question')); const correctAnswer = screen.getByRole('button', { name: 'Madrid' }); - expect(screen.findByTestId("anwer0")); //selects correct answer fireEvent.click(correctAnswer); + expect(screen.findByTestId("succes0")); }); @@ -95,7 +95,7 @@ describe('Game component', () => { render( - + ); @@ -125,7 +125,7 @@ describe('Game component', () => { render( - + ); @@ -154,7 +154,7 @@ describe('Game component', () => { render( - + ); @@ -172,6 +172,6 @@ describe('Game component', () => { fireEvent.click(screen.getByTestId('pause')); expect(screen.getByTestId('play')).toBeInTheDocument(); -}); + }); }); \ No newline at end of file diff --git a/webapp/src/pages/TheChallengeGame.js b/webapp/src/pages/TheChallengeGame.js index 1f03a70f..c9273750 100644 --- a/webapp/src/pages/TheChallengeGame.js +++ b/webapp/src/pages/TheChallengeGame.js @@ -19,7 +19,7 @@ import RemoveIcon from '@mui/icons-material/Remove'; const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000'; -const Game = () => { +const TheChallengeGame = () => { const navigate = useNavigate(); const SUCCESS_SOUND_ROUTE = "/sounds/success_sound.mp3"; const FAILURE_SOUND_ROUTE = "/sounds/wrong_sound.mp3"; @@ -425,4 +425,4 @@ const Game = () => { ); }; -export default Game; \ No newline at end of file +export default TheChallengeGame; \ No newline at end of file From fcf535990f65950f162e4ed182d556b1f5780b05 Mon Sep 17 00:00:00 2001 From: uo288245 Date: Thu, 25 Apr 2024 15:26:38 +0200 Subject: [PATCH 093/132] Upgraded tests of the Discovering Cities game. --- .../pages/DiscoveringCitiesGame.test.js | 59 +++++++++++-------- .../__tests__/pages/TheChallengeGame.test.js | 2 +- webapp/src/pages/MultiplayerGame.js | 2 - webapp/src/pages/TheChallengeGame.js | 2 - webapp/src/pages/WiseMenStackGame.js | 1 - 5 files changed, 37 insertions(+), 29 deletions(-) diff --git a/webapp/src/__tests__/pages/DiscoveringCitiesGame.test.js b/webapp/src/__tests__/pages/DiscoveringCitiesGame.test.js index ff54afdc..faa0a752 100644 --- a/webapp/src/__tests__/pages/DiscoveringCitiesGame.test.js +++ b/webapp/src/__tests__/pages/DiscoveringCitiesGame.test.js @@ -4,12 +4,12 @@ import { SessionContext } from '../../SessionContext'; // Importa el contexto ne import { BrowserRouter as Router } from 'react-router-dom'; import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; -import Game from '../../pages/DiscoveringCitiesGame'; +import DiscoveringCitiesGame from '../../pages/DiscoveringCitiesGame'; import '../../localize/i18n'; const mockAxios = new MockAdapter(axios); - -describe('Game component', () => { + +describe('Discovering Cities component', () => { beforeEach(() => { mockAxios.reset(); // Mock the axios.post request to simulate a successful response @@ -32,25 +32,21 @@ describe('Game component', () => { render( - + ); expect(screen.getByRole('progressbar')); - //expect(screen.findByText('1')); - //expect(screen.findByText('1/5')); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByTestId('question')); - expect(screen.findByText('Which is the capital of Spain?')); + expect(screen.getByTestId('question')); expect(screen.findByText('Madrid')); expect(screen.findByText('Barcelona')); expect(screen.findByText('Paris')); expect(screen.findByText('London')); - - expect(screen.getByRole('button', { name: /Pause/i })); }); @@ -58,23 +54,21 @@ describe('Game component', () => { render( - + ); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByTestId('question')); const correctAnswer = screen.getByRole('button', { name: 'Madrid' }); - expect(correctAnswer).not.toHaveStyle({ backgroundColor: 'green' }); + expect(correctAnswer).toHaveStyle({ backgroundColor: 'rgb(0, 102, 153);' }); //selects correct answer fireEvent.click(correctAnswer); - //expect(screen.findByText('1')).toHaveStyle({ backgroundColor: 'lightgreen' }); - - expect(correctAnswer).toHaveStyle({ backgroundColor: 'green' }); + expect(correctAnswer).toHaveStyle({ backgroundColor: 'rgb(51, 153, 102);' }); }); @@ -82,21 +76,20 @@ describe('Game component', () => { render( - + ); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByTestId('question')); const incorrectAnswer = screen.getByRole('button', { name: 'Barcelona' }); - expect(incorrectAnswer).not.toHaveStyle({ backgroundColor: 'red' }); + expect(incorrectAnswer).toHaveStyle({ backgroundColor: 'rgb(0, 102, 153);' }); //selects correct answer fireEvent.click(incorrectAnswer); - expect(incorrectAnswer).toHaveStyle({ backgroundColor: 'red' }); - //expect(screen.findByText('1')).toHaveStyle({ backgroundColor: 'salmon' }); + expect(incorrectAnswer).toHaveStyle({ backgroundColor: 'rgb(153, 0, 0);' }); }); @@ -104,13 +97,13 @@ describe('Game component', () => { render( - + ); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByTestId('question')); setTimeout(() => { // Comprobamos que el callback ha sido llamado después del tiempo especificado @@ -119,4 +112,24 @@ describe('Game component', () => { }, 4500); + it('should pause and resume the game after answering a question', async () => { + render( + + + + + + ); + + await waitFor(() => screen.getByTestId('question')); + + fireEvent.click(screen.getByRole('button', { name: 'Madrid' })); + + await waitFor(() => screen.getByTestId('pause')); + + fireEvent.click(screen.getByTestId('pause')); + + expect(screen.getByTestId('play')).toBeInTheDocument(); + }); + }); diff --git a/webapp/src/__tests__/pages/TheChallengeGame.test.js b/webapp/src/__tests__/pages/TheChallengeGame.test.js index 130b501b..f45f37a1 100644 --- a/webapp/src/__tests__/pages/TheChallengeGame.test.js +++ b/webapp/src/__tests__/pages/TheChallengeGame.test.js @@ -86,7 +86,7 @@ describe('The Challenge component', () => { //selects correct answer fireEvent.click(correctAnswer); - expect(screen.findByTestId("succes0")); + expect(screen.findByTestId("success0")); }); diff --git a/webapp/src/pages/MultiplayerGame.js b/webapp/src/pages/MultiplayerGame.js index 2c71b34a..eb7698e9 100644 --- a/webapp/src/pages/MultiplayerGame.js +++ b/webapp/src/pages/MultiplayerGame.js @@ -12,7 +12,6 @@ import io from 'socket.io-client'; import { useTranslation } from 'react-i18next'; import i18n from '../localize/i18n'; - const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000'; const socketEndpoint = process.env.REACT_APP_MULTIPLAYER_ENDPOINT || 'ws://localhost:5010'; @@ -44,7 +43,6 @@ const Game = () => { const [userResponses, setUserResponses] = React.useState([]); const [, setCurrentLanguage] = React.useState(i18n.language); - const location = useLocation(); const { gameQuestions, roomCode} = location.state; const [socket, setSocket] = React.useState(null); diff --git a/webapp/src/pages/TheChallengeGame.js b/webapp/src/pages/TheChallengeGame.js index c9273750..01197b05 100644 --- a/webapp/src/pages/TheChallengeGame.js +++ b/webapp/src/pages/TheChallengeGame.js @@ -15,10 +15,8 @@ import { PlayArrow, Pause } from '@mui/icons-material'; import AddIcon from '@mui/icons-material/Add'; import RemoveIcon from '@mui/icons-material/Remove'; - const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000'; - const TheChallengeGame = () => { const navigate = useNavigate(); const SUCCESS_SOUND_ROUTE = "/sounds/success_sound.mp3"; diff --git a/webapp/src/pages/WiseMenStackGame.js b/webapp/src/pages/WiseMenStackGame.js index bad3fce1..3f74aad0 100644 --- a/webapp/src/pages/WiseMenStackGame.js +++ b/webapp/src/pages/WiseMenStackGame.js @@ -14,7 +14,6 @@ import i18n from '../localize/i18n'; const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000'; - const WiseMenStackGame = () => { const navigate = useNavigate(); const SUCCESS_SOUND_ROUTE = "/sounds/success_sound.mp3"; From 9249d81f7b4784af73143906470fdd67ddd33ab3 Mon Sep 17 00:00:00 2001 From: uo288245 Date: Thu, 25 Apr 2024 15:37:16 +0200 Subject: [PATCH 094/132] I don't know wtf happened with the tests that they were like, bad done. --- webapp/src/__tests__/pages/TheChallengeGame.test.js | 5 ++--- webapp/src/__tests__/pages/WiseMenStackGame.test.js | 7 +++---- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/webapp/src/__tests__/pages/TheChallengeGame.test.js b/webapp/src/__tests__/pages/TheChallengeGame.test.js index f45f37a1..baa65481 100644 --- a/webapp/src/__tests__/pages/TheChallengeGame.test.js +++ b/webapp/src/__tests__/pages/TheChallengeGame.test.js @@ -113,11 +113,10 @@ describe('The Challenge component', () => { // waits for the question to appear await waitFor(() => screen.getByTestId('question')); const incorrectAnswer = screen.getByRole('button', { name: 'Barcelona' }); - - expect(screen.findByTestId("anwer1")); + //selects correct answer fireEvent.click(incorrectAnswer); - expect(screen.findByTestId("failure1")); + expect(screen.findByTestId("success1")); }); diff --git a/webapp/src/__tests__/pages/WiseMenStackGame.test.js b/webapp/src/__tests__/pages/WiseMenStackGame.test.js index 3e40a50b..c08969b4 100644 --- a/webapp/src/__tests__/pages/WiseMenStackGame.test.js +++ b/webapp/src/__tests__/pages/WiseMenStackGame.test.js @@ -61,11 +61,10 @@ describe('Wise Men Stack Game component', () => { await waitFor(() => screen.getByText('Which is the capital of Spain?'.toUpperCase())); const correctAnswer = screen.getByRole('button', { name: 'Madrid' }); - // now the answer is not selected: - expect(screen.findByTestId("anwer0")); + // after clicking it has changed to succeeded: fireEvent.click(correctAnswer); - expect(screen.findByTestId("succes0")); + expect(screen.findByTestId("success0")); }); @@ -83,7 +82,7 @@ describe('Wise Men Stack Game component', () => { const id = answers[0].name === 'Madrid' ? 1 : 0; // now the answer is not selected: - expect(screen.findByTestId(`anwer${id}`)); + expect(screen.findByTestId(`success${id}`)); // after clicking it has changed to succeeded: fireEvent.click(incorrectAnswer); expect(screen.findByTestId(`failure${id}`)); From 73109e5808429415250fff4954e4b07e540f548a Mon Sep 17 00:00:00 2001 From: uo288245 Date: Thu, 25 Apr 2024 15:50:08 +0200 Subject: [PATCH 095/132] Code improvements in the games. --- webapp/src/pages/DiscoveringCitiesGame.js | 3 +- webapp/src/pages/Game.js | 3 +- webapp/src/pages/TheChallengeGame.js | 152 +++++++++------------- webapp/src/pages/WiseMenStackGame.js | 103 +++++---------- 4 files changed, 97 insertions(+), 164 deletions(-) diff --git a/webapp/src/pages/DiscoveringCitiesGame.js b/webapp/src/pages/DiscoveringCitiesGame.js index 82da3491..eb3d3741 100644 --- a/webapp/src/pages/DiscoveringCitiesGame.js +++ b/webapp/src/pages/DiscoveringCitiesGame.js @@ -215,8 +215,7 @@ const DiscovertingCitiesGame = () => { const questionHistorialBar = () => { return questionHistorial.map((isCorrect, index) => ( - + )); }; diff --git a/webapp/src/pages/Game.js b/webapp/src/pages/Game.js index 9f5d1245..c845d7e4 100644 --- a/webapp/src/pages/Game.js +++ b/webapp/src/pages/Game.js @@ -214,8 +214,7 @@ const Game = () => { const questionHistorialBar = () => { return questionHistorial.map((isCorrect, index) => ( - + )); }; diff --git a/webapp/src/pages/TheChallengeGame.js b/webapp/src/pages/TheChallengeGame.js index 01197b05..511feedd 100644 --- a/webapp/src/pages/TheChallengeGame.js +++ b/webapp/src/pages/TheChallengeGame.js @@ -230,92 +230,71 @@ const TheChallengeGame = () => { return( - - - {t("Game.config.title")} - - - - - - {t("Game.config.num_rounds")}: - - setNumRounds(numRounds - 1)} variant="outlined" data-testId="removeRound"> - - - - {numRounds} - - setNumRounds(numRounds + 1)} variant="outlined" data-testId="addRound"> - - - - - - - {t("Game.config.time")}: - - setTimerConfig(timerConfig - 1)} variant="outlined" data-testId="removeSecond"> - - - - {timerConfig} - - setTimerConfig(timerConfig + 1)} variant="outlined" data-testId="addSecond"> - - - - - {/* Dropdown for selecting category */} - - - {t("Game.config.category")}: - - - - - - + + + {t("Game.config.title")} + + + + + + {t("Game.config.num_rounds")}: + + setNumRounds(numRounds - 1)} variant="outlined" data-testId="removeRound"> + + + + {numRounds} + + setNumRounds(numRounds + 1)} variant="outlined" data-testId="addRound"> + + + + + + + {t("Game.config.time")}: + + setTimerConfig(timerConfig - 1)} variant="outlined" data-testId="removeSecond"> + + + + {timerConfig} + + setTimerConfig(timerConfig + 1)} variant="outlined" data-testId="addSecond"> + + + + + {/* Dropdown for selecting category */} + + + {t("Game.config.category")}: + + + + + + ); } const questionHistorialBar = () => { return questionHistorial.map((isCorrect, index) => ( - - + )); }; @@ -328,23 +307,14 @@ const TheChallengeGame = () => { // circular loading if (!questionData) { return ( - + ); } - // redirect to / if game over + // redirect to homepage if game over if (shouldRedirect) { // Redirect after 4 seconds setTimeout(() => { diff --git a/webapp/src/pages/WiseMenStackGame.js b/webapp/src/pages/WiseMenStackGame.js index 3f74aad0..f61487be 100644 --- a/webapp/src/pages/WiseMenStackGame.js +++ b/webapp/src/pages/WiseMenStackGame.js @@ -23,7 +23,6 @@ const WiseMenStackGame = () => { const {username} = useContext(SessionContext); const theme = useTheme(); - // Traductions const { t } = useTranslation(); @@ -135,7 +134,6 @@ const WiseMenStackGame = () => { const randomFactor = random < 0.5 ? -1 : 1; return array.sort(() => randomFactor); } - const updateStatistics = async() => { try { @@ -224,8 +222,7 @@ const WiseMenStackGame = () => { const questionHistorialBar = () => { return questionHistorial.map((isCorrect, index) => ( - + )); }; @@ -237,60 +234,37 @@ const WiseMenStackGame = () => { if(!isConfigured) { return ( - - - {t("Game.config.title")} - - - - - {t("Wise_Men.instructions1")} - {t("Wise_Men.instructions2")} - {t("Wise_Men.instructions3")} + + + {t("Game.config.title")} + + + + + {t("Wise_Men.instructions1")} + {t("Wise_Men.instructions2")} + {t("Wise_Men.instructions3")} + + + {/* Dropdown for selecting category */} + + + {t("Game.config.category")}: + + + - {/* Dropdown for selecting category */} - - - {t("Game.config.category")}: - - - - - - - + + ); } @@ -298,25 +272,16 @@ const WiseMenStackGame = () => { // circular loading if (!questionData) { return ( - + ); } - // redirect to / if game over + // redirect to homepage if game over if (shouldRedirect) { - // Redirect after 3 seconds + // Redirect after 4 seconds setTimeout(() => { navigate('/homepage'); }, 4000); @@ -392,4 +357,4 @@ const WiseMenStackGame = () => { ); }; -export default WiseMenStackGame; +export default WiseMenStackGame; \ No newline at end of file From c34a620c9b5ad909aa2b89fd81cc25d27fcd00c4 Mon Sep 17 00:00:00 2001 From: uo288245 Date: Thu, 25 Apr 2024 16:53:49 +0200 Subject: [PATCH 096/132] Updated de Multiplayer Game principal view. --- webapp/src/pages/MultiplayerGame.js | 265 +++++++++++----------------- webapp/src/pages/MultiplayerRoom.js | 2 +- 2 files changed, 103 insertions(+), 164 deletions(-) diff --git a/webapp/src/pages/MultiplayerGame.js b/webapp/src/pages/MultiplayerGame.js index eb7698e9..d18d5f6f 100644 --- a/webapp/src/pages/MultiplayerGame.js +++ b/webapp/src/pages/MultiplayerGame.js @@ -1,6 +1,6 @@ import * as React from 'react'; import axios from 'axios'; -import { Container, Button, CssBaseline, Grid, Typography, CircularProgress, Card, CardContent } from '@mui/material'; +import { useTheme, Container, Button, CssBaseline, Grid, Typography, CircularProgress, Card, Box } from '@mui/material'; import CheckIcon from '@mui/icons-material/Check'; import ClearIcon from '@mui/icons-material/Clear'; import { SessionContext } from '../SessionContext'; @@ -15,9 +15,7 @@ import i18n from '../localize/i18n'; const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000'; const socketEndpoint = process.env.REACT_APP_MULTIPLAYER_ENDPOINT || 'ws://localhost:5010'; -const Game = () => { - const { t } = useTranslation(); - +const Game = () => { const MAX_ROUNDS = 3; const SUCCESS_SOUND_ROUTE = "/sounds/success_sound.mp3"; const FAILURE_SOUND_ROUTE = "/sounds/wrong_sound.mp3"; @@ -25,6 +23,11 @@ const Game = () => { //sesion information const {username} = useContext(SessionContext); + // Translations + const { t } = useTranslation(); + + const theme = useTheme(); + // state initialization const [round, setRound] = React.useState(1); const [questionData, setQuestionData] = React.useState(null); @@ -93,11 +96,7 @@ const Game = () => { // stablish if the confetti must show or not React.useEffect(() => { - if (winnerPlayer === username) { - setShowConfetti(true); - } else { - setShowConfetti(false); - } + winnerPlayer === username ? setShowConfetti(true) : setShowConfetti(false); }, [winnerPlayer, username]); @@ -105,16 +104,12 @@ const Game = () => { const startNewRound = async () => { setAnswered(false); const quest = gameQuestions[round-1] - setQuestionData(quest); setButtonStates(new Array(quest.options.length).fill(null)); - }; const updateStatistics = async() => { try { - //const winner = winner === username ? 1 : 0; - await axios.put(`${apiEndpoint}/statistics`, { username:username, the_callenge_earned_money:0, @@ -221,22 +216,23 @@ const Game = () => { const questionHistorialBar = () => { return questionHistorial.map((isCorrect, index) => ( - - {index + 1} - + )); - }; + }; // circular loading if (!questionData) { + return ( + + + + + ); + } + + if (shouldRedirect) { + socket.emit("finished-game", username, correctlyAnsweredQuestions, totalTimePlayed); + return ( { }} > - + + + + {winnerPlayer === "" ? t("Multiplayer.Game.waiting_players_end") : "Game Over"} + + +
+ + + + {t("Game.correct")}: {correctlyAnsweredQuestions} + + + + + {t("Game.incorrect")}: {incorrectlyAnsweredQuestions} + + + + + {t("Game.money")}: {totalScore} + + + + + {t("Game.time")}: {totalTimePlayed} + + + + + {winnerPlayer === "" ? ( + { t("Multiplayer.Game.waiting") } + ) : ( + { t("Multiplayer.Game.winner_1") }: {winnerPlayer} { t("Multiplayer.Game.winner_2") } {winnerCorrect} { t("Multiplayer.Game.winner_3") } {winnerTime} { t("Multiplayer.Game.winner_4") } + )} +
+ {showConfetti && }
); } - -if (shouldRedirect) { - socket.emit("finished-game", username, correctlyAnsweredQuestions, totalTimePlayed); - - return ( - - - - - - {winnerPlayer === "" ? t("Multiplayer.Game.waiting_players_end") : "Game Over"} - - -
- - - - {t("Game.correct")}: {correctlyAnsweredQuestions} - - - - - {t("Game.incorrect")}: {incorrectlyAnsweredQuestions} - - - - - {t("Game.money")}: {totalScore} - - - - - {t("Game.time")}: {totalTimePlayed} - - - - - {winnerPlayer === "" ? ( - { t("Multiplayer.Game.waiting") } - ) : ( - { t("Multiplayer.Game.winner_1") }: {winnerPlayer} { t("Multiplayer.Game.winner_2") } {winnerCorrect} { t("Multiplayer.Game.winner_3") } {winnerTime} { t("Multiplayer.Game.winner_4") } - )} -
- {showConfetti && } -
- ); -} + return ( - + - - + selectResponse(-1, "FAILED")}> + {({ remainingTime }) => { + return ( + + {remainingTime} + + ); }} - > - {questionHistorialBar()} - + + + + + + {questionData.question.toUpperCase()} + + + + {questionData.options.map((option, index) => ( + + + + ))} + - - {round} / {MAX_ROUNDS} - - - {questionData.question} - selectResponse(0, "FAILED")} //when time ends always fail question - > - {({ remainingTime }) => { - return ( -
-
{remainingTime}
-
- ); - }} -
-
- - - {questionData.options.map((option, index) => ( - - - - ))} - + {/* Progress Cards */} + + {questionHistorialBar()} +
); }; diff --git a/webapp/src/pages/MultiplayerRoom.js b/webapp/src/pages/MultiplayerRoom.js index 6a3043f8..ab1f4165 100644 --- a/webapp/src/pages/MultiplayerRoom.js +++ b/webapp/src/pages/MultiplayerRoom.js @@ -107,7 +107,7 @@ const MultiplayerRoom = () => { return ( - + {t("Games.Multiplayer.name").toUpperCase()} From 333a5b6bc5728a69715222e0d088c44f1aed4522 Mon Sep 17 00:00:00 2001 From: uo288245 Date: Thu, 25 Apr 2024 17:36:17 +0200 Subject: [PATCH 097/132] Finished updating the Multiplayer style. --- webapp/src/localize/en.json | 10 ++-- webapp/src/localize/es.json | 8 ++-- webapp/src/localize/fr.json | 8 ++-- webapp/src/pages/MultiplayerGame.js | 74 ++++++++--------------------- 4 files changed, 34 insertions(+), 66 deletions(-) diff --git a/webapp/src/localize/en.json b/webapp/src/localize/en.json index e191856e..6a6c58d0 100644 --- a/webapp/src/localize/en.json +++ b/webapp/src/localize/en.json @@ -145,17 +145,17 @@ "participants": "Participants", "start": "Start game", "create": "Create room", - "join": "Join room", + "join": "Join Room", "send": "Send", "chat_title": "Chat of the room", "chat_input_label": "Type your message", "new_game": "Want to start a new game?" }, "Game": { - "waiting_players_end": "Waiting for players end...", - "waiting": "Waiting for winner info...", - "winner_1": "Player winner of the game", - "winner_2": "with", + "waiting_players_end": "Waiting for players to finish...", + "waiting": "Waiting for the winner info...", + "winner_1": "Winner", + "winner_2": "With", "winner_3": "correct answers in", "winner_4": "seconds" } diff --git a/webapp/src/localize/es.json b/webapp/src/localize/es.json index e674ed28..ac4e536f 100644 --- a/webapp/src/localize/es.json +++ b/webapp/src/localize/es.json @@ -144,8 +144,8 @@ "code": "Código de Sala", "participants": "Participantes", "start": "Comenzar juego", - "create": "Crear sala", - "join": "Unirse a sala", + "create": "Crear Sala", + "join": "Unirse a Sala", "send": "Enviar", "chat_title": "Chat de la sala", "chat_input_label": "Escribe tu mensaje", @@ -154,8 +154,8 @@ "Game": { "waiting_players_end": "Esperando a que terminen los demás jugadores...", "waiting": "Esperando información del ganador...", - "winner_1": "Jugador ganador del juego", - "winner_2": "con", + "winner_1": "Ganador", + "winner_2": "Con", "winner_3": "respuestas correctas en", "winner_4": "segundos" } diff --git a/webapp/src/localize/fr.json b/webapp/src/localize/fr.json index bbc12ec7..40101093 100644 --- a/webapp/src/localize/fr.json +++ b/webapp/src/localize/fr.json @@ -142,8 +142,8 @@ "code": "Code de la Salle", "participants": "Participants", "start": "Démarrer le jeu", - "create": "Créer une salle", - "join": "Rejoindre une salle", + "create": "Créer Salle", + "join": "Rejoindre une Salle", "send": "Envoyer", "chat_title": "Discussion de la salle", "chat_input_label": "Tape ton message", @@ -152,8 +152,8 @@ "Game": { "waiting_players_end": "En attendant que tous les joueurs finissent...", "waiting": "En attente des informations du gagnant...", - "winner_1": "Joueur gagnant de la partie", - "winner_2": "avec", + "winner_1": "Gagnant", + "winner_2": "Avec", "winner_3": "réponses correctes en", "winner_4": "secondes" } diff --git a/webapp/src/pages/MultiplayerGame.js b/webapp/src/pages/MultiplayerGame.js index d18d5f6f..45fa4f9f 100644 --- a/webapp/src/pages/MultiplayerGame.js +++ b/webapp/src/pages/MultiplayerGame.js @@ -234,66 +234,34 @@ const Game = () => { socket.emit("finished-game", username, correctlyAnsweredQuestions, totalTimePlayed); return ( - + - - - - {winnerPlayer === "" ? t("Multiplayer.Game.waiting_players_end") : "Game Over"} + + + {winnerPlayer === "" ? t("Multiplayer.Game.waiting_players_end") : t("Game.lose_msg")} - -
- - - - {t("Game.correct")}: {correctlyAnsweredQuestions} - - - - - {t("Game.incorrect")}: {incorrectlyAnsweredQuestions} - - - - - {t("Game.money")}: {totalScore} - - - - - {t("Game.time")}: {totalTimePlayed} - - - - {winnerPlayer === "" ? ( - { t("Multiplayer.Game.waiting") } - ) : ( - { t("Multiplayer.Game.winner_1") }: {winnerPlayer} { t("Multiplayer.Game.winner_2") } {winnerCorrect} { t("Multiplayer.Game.winner_3") } {winnerTime} { t("Multiplayer.Game.winner_4") } - )} -
+ + { t("Game.correct") }: {correctlyAnsweredQuestions} + { t("Game.incorrect") }: {incorrectlyAnsweredQuestions} + { t("Game.money") }: {totalScore} + { t("Game.time") }: {totalTimePlayed} + + + {winnerPlayer === "" ? ( + { t("Multiplayer.Game.waiting") } + ) : ( + + { t("Multiplayer.Game.winner_1") }: {winnerPlayer} + { t("Multiplayer.Game.winner_2") }: {winnerCorrect} { t("Multiplayer.Game.winner_3") } {winnerTime} { t("Multiplayer.Game.winner_4") } + + )} + {showConfetti && }
); } - + return ( From 1060b5c503e3a72e001939e834e9f48770db5804 Mon Sep 17 00:00:00 2001 From: uo288245 Date: Thu, 25 Apr 2024 18:17:50 +0200 Subject: [PATCH 098/132] Updated the multiplayer tests to match the new style. --- .../__tests__/pages/MultiplayerGame.test.js | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/webapp/src/__tests__/pages/MultiplayerGame.test.js b/webapp/src/__tests__/pages/MultiplayerGame.test.js index eb828baf..5df16e29 100644 --- a/webapp/src/__tests__/pages/MultiplayerGame.test.js +++ b/webapp/src/__tests__/pages/MultiplayerGame.test.js @@ -63,13 +63,10 @@ describe('Game component', () => { ); - expect(screen.findByText('1')); - expect(screen.findByText('1/3')); - // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByTestId('question')); - expect(screen.findByText('Which is the capital of Spain?')); + expect(screen.getByTestId('question')); expect(screen.findByText('Madrid')); expect(screen.findByText('Barcelona')); expect(screen.findByText('Paris')); @@ -94,15 +91,15 @@ describe('Game component', () => { ); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByTestId('question')); const correctAnswer = screen.getByRole('button', { name: 'Madrid' }); - expect(correctAnswer).not.toHaveStyle({ backgroundColor: 'green' }); + expect(correctAnswer).toHaveStyle({ backgroundColor: 'rgb(0, 102, 153);' }); //selects correct answer fireEvent.click(correctAnswer); - expect(correctAnswer).toHaveStyle({ backgroundColor: 'green' }); + expect(correctAnswer).toHaveStyle({ backgroundColor: 'rgb(51, 153, 102);' }); }); @@ -125,15 +122,15 @@ describe('Game component', () => { ); // waits for the question to appear - await waitFor(() => screen.getByText('Which is the capital of Spain?')); + await waitFor(() => screen.getByTestId('question')); const incorrectAnswer = screen.getByRole('button', { name: 'Barcelona' }); - expect(incorrectAnswer).not.toHaveStyle({ backgroundColor: 'red' }); + expect(incorrectAnswer).toHaveStyle({ backgroundColor: 'rgb(0, 102, 153);' }); //selects correct answer fireEvent.click(incorrectAnswer); - expect(incorrectAnswer).toHaveStyle({ backgroundColor: 'red' }); + expect(incorrectAnswer).toHaveStyle({ backgroundColor: 'rgb(153, 0, 0);' }); }); From 439f287405828b890087fa0d87f206dc3d3080d1 Mon Sep 17 00:00:00 2001 From: uo288543 Date: Fri, 26 Apr 2024 15:27:49 +0200 Subject: [PATCH 099/132] add force true --- users/services/user-model.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/users/services/user-model.js b/users/services/user-model.js index 89a59234..e5ee623d 100644 --- a/users/services/user-model.js +++ b/users/services/user-model.js @@ -208,7 +208,7 @@ const QuestionsRecord = sequelize.define('QuestionsRecord', { }); // Synchronize the model with the database -sequelize.sync() +sequelize.sync({ force: true }) .then(() => { console.log('Model synchronized successfully with the database'); }) From a409b1796b9de678cb82051ad89d369b93f95e12 Mon Sep 17 00:00:00 2001 From: uo288543 Date: Fri, 26 Apr 2024 15:28:42 +0200 Subject: [PATCH 100/132] remove force true --- users/services/user-model.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/users/services/user-model.js b/users/services/user-model.js index e5ee623d..89a59234 100644 --- a/users/services/user-model.js +++ b/users/services/user-model.js @@ -208,7 +208,7 @@ const QuestionsRecord = sequelize.define('QuestionsRecord', { }); // Synchronize the model with the database -sequelize.sync({ force: true }) +sequelize.sync() .then(() => { console.log('Model synchronized successfully with the database'); }) From 4d82448c4fc2e56ff97525fb5cbb1555548f8e6e Mon Sep 17 00:00:00 2001 From: Pablo Date: Fri, 26 Apr 2024 18:34:34 +0200 Subject: [PATCH 101/132] Removed absolute height in circular progress in games --- webapp/src/pages/TheChallengeGame.js | 2 +- webapp/src/pages/WiseMenStackGame.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/webapp/src/pages/TheChallengeGame.js b/webapp/src/pages/TheChallengeGame.js index 511feedd..51a435c2 100644 --- a/webapp/src/pages/TheChallengeGame.js +++ b/webapp/src/pages/TheChallengeGame.js @@ -307,7 +307,7 @@ const TheChallengeGame = () => { // circular loading if (!questionData) { return ( - + diff --git a/webapp/src/pages/WiseMenStackGame.js b/webapp/src/pages/WiseMenStackGame.js index f61487be..78bb0c27 100644 --- a/webapp/src/pages/WiseMenStackGame.js +++ b/webapp/src/pages/WiseMenStackGame.js @@ -272,7 +272,7 @@ const WiseMenStackGame = () => { // circular loading if (!questionData) { return ( - + From bf49165f6a62f96accfab16bbb7295b1e69c5dbf Mon Sep 17 00:00:00 2001 From: Pablo Date: Fri, 26 Apr 2024 19:30:34 +0200 Subject: [PATCH 102/132] Solved not passing e2e discovering cities tests --- .../e2e/steps/discoveringCitiesGame.steps.js | 52 +++++++++---------- 1 file changed, 25 insertions(+), 27 deletions(-) diff --git a/webapp/e2e/steps/discoveringCitiesGame.steps.js b/webapp/e2e/steps/discoveringCitiesGame.steps.js index 5c1103b1..506121c9 100644 --- a/webapp/e2e/steps/discoveringCitiesGame.steps.js +++ b/webapp/e2e/steps/discoveringCitiesGame.steps.js @@ -65,51 +65,49 @@ defineFeature(feature, test => { test('Answering a question correctly', ({given,when,then}) => { given('A question', async () => { - //await expect(page.findByText('Which is the capital of Spain?')); - const question = await page.$['data-testid="question"']; - await expect(page).toMatchElement("div", { text: 'Which is the capital of Spain?'}); - expect(question).not.toBeNull(); - - const answers = await page.$x('//*[@data-testid="answer"]'); - expect(answers.length).toBe(4); + const question = await page.$['data-testid="question"']; + await expect(page).toMatchElement("div", { text: 'WHICH IS THE CAPITAL OF SPAIN?'}); + expect(question).not.toBeNull(); + + const answers = await page.$x('//*[contains(@data-testid, "answer")]'); + expect(answers.length).toBe(4); }); when('I click on the correct answer button', async () => { - const answers = await page.$x('(//*[@data-testid="answer"])[1]'); - await answers[0].click(); + const answers = await page.$x('//*[contains(@data-testid, "answer")]'); + await answers[0].click(); }); then('The button turns green', async () => { - const answerButton = await page.$x('(//*[@data-testid="answer"])[1]'); - const textoBoton = await page.evaluate(button => button.innerText, answerButton[0]); - await expect(textoBoton).toMatch(/Madrid/i); - await expect(page).toMatchElement("button", { style: { color: 'green' } }); + const answer = await page.$x('//*[contains(@data-testid, "success")]'); + const textoBoton = await page.evaluate(button => button.innerText, answer[0]); + await expect(textoBoton).toMatch(/Madrid/i); + await expect(page).toMatchElement("button", { style: { color: 'green' } }); }); }) test('Answering a question incorrectly', ({given,when,then}) => { given('A question', async () => { - //await expect(page.findByText('Which is the capital of Spain?')); - const question = await page.$['data-testid="question"']; - await expect(page).toMatchElement("div", { text: 'Which is the capital of Spain?'}); - expect(question).not.toBeNull(); - - const answers = await page.$x('//*[@data-testid="answer"]'); - expect(answers.length).toBe(4); + const question = await page.$['data-testid="question"']; + await expect(page).toMatchElement("div", { text: 'WHICH IS THE CAPITAL OF SPAIN?'}); + expect(question).not.toBeNull(); + + const answers = await page.$x('//*[contains(@data-testid, "answer")]'); + expect(answers.length).toBe(4); }); when('I click on an incorrect answer button', async () => { - const answers = await page.$x('(//*[@data-testid="answer"])[2]'); - await answers[0].click(); + const answers = await page.$x('//*[contains(@data-testid, "answer")]'); + await answers[2].click(); }); then('The button turns red', async () => { - const answerButton = await page.$x('(//*[@data-testid="answer"])[2]'); - const textoBoton = await page.evaluate(button => button.innerText, answerButton[0]); - await expect(textoBoton).toMatch(/Barcelona/i); - await expect(page).toMatchElement("button", { style: { color: 'red' } }); - await expect(page).toMatchElement("button", { style: { color: 'green' } }); + const answerButtons = await page.$x('//*[contains(@data-testid, "answer")]'); + const textoBoton = await page.evaluate(button => button.innerText, answerButtons[0]); + await expect(textoBoton).toMatch(/Barcelona/i); + await expect(page).toMatchElement("button", { style: { color: 'red' } }); + await expect(page).toMatchElement("button", { style: { color: 'green' } }); }); }) From 00fa20e7023159f6ecf0dd328594fc14b9c1978c Mon Sep 17 00:00:00 2001 From: Pablo Date: Fri, 26 Apr 2024 19:30:48 +0200 Subject: [PATCH 103/132] Solved failing e2e wise men tests --- webapp/e2e/steps/wiseMenStackGame.steps.js | 90 +++++++++------------- 1 file changed, 36 insertions(+), 54 deletions(-) diff --git a/webapp/e2e/steps/wiseMenStackGame.steps.js b/webapp/e2e/steps/wiseMenStackGame.steps.js index 2c59525a..0630276e 100644 --- a/webapp/e2e/steps/wiseMenStackGame.steps.js +++ b/webapp/e2e/steps/wiseMenStackGame.steps.js @@ -10,7 +10,7 @@ defineFeature(feature, test => { beforeAll(async () => { - browser = process.env.GITHUB_ACTIONS + browser = process.env.GITHUB_ACTIONS ? await puppeteer.launch() : await puppeteer.launch({ headless: false, slowMo: 40 }); page = await browser.newPage(); @@ -65,77 +65,59 @@ defineFeature(feature, test => { test('Answering a question correctly', ({given,when,then}) => { given('A question', async () => { - const button = await page.$('[data-testid="start-button"]'); - await button.click(); - - //await expect(page.findByText('Which is the capital of Spain?')); - const question = await page.$['data-testid="question"']; - await expect(page).toMatchElement("div", { text: 'Which is the capital of Spain?'}); - expect(question).not.toBeNull(); - - const answers = await page.$x('//*[@data-testid="answer"]'); - expect(answers.length).toBe(2); + const button = await page.$('[data-testid="start-button"]'); + await button.click(); + + const question = await page.$['data-testid="question"']; + expect(question).not.toBeNull(); + await expect(page).toMatchElement("div", { text: 'WHICH IS THE CAPITAL OF SPAIN?'}); + + const answers = await page.$x('//*[contains(@data-testid, "answer")]'); + expect(answers.length).toBe(2); }); when('I click on the correct answer button', async () => { - const answers = await page.$x('//*[@data-testid="answer"]'); - const textoBoton1 = await page.evaluate(button => button.innerText, answers[0]); - if(textoBoton1 === "Madrid") { - await answers[0].click(); - } else { - await answers[1].click(); - } + const answers = await page.$x('//*[contains(@data-testid, "answer")]'); + const textoBoton1 = await page.evaluate(button => button.innerText, answers[0]); + if(textoBoton1 === "Madrid") { + await answers[0].click(); + } else { + await answers[1].click(); + } }); then('The button turns green', async () => { - /*const answerButton = await page.$x('(//*[@data-testid="answer"])[1]'); - const textoBoton1 = await page.evaluate(button => button.innerText, answerButton[0]); - const textoBoton2 = await page.evaluate(button => button.innerText, answerButton[1]); - if(textoBoton1 === "Madrid") { - await expect(textoBoton1).toMatch(/Madrid/i); - } else { - await expect(textoBoton2).toMatch(/Madrid/i); - }*/ - await expect(page).toMatchElement("button", { style: { color: 'green' } }); + await expect(page).toMatchElement("button", { style: { color: 'green' } }); }); }) test('Answering a question incorrectly', ({given,when,then}) => { given('A question', async () => { - const button = await page.$('[data-testid="start-button"]'); - await button.click(); - - //await expect(page.findByText('Which is the capital of Spain?')); - const question = await page.$['data-testid="question"']; - await expect(page).toMatchElement("div", { text: 'Which is the capital of Spain?'}); - expect(question).not.toBeNull(); - - const answers = await page.$x('//*[@data-testid="answer"]'); - expect(answers.length).toBe(2); + const button = await page.$('[data-testid="start-button"]'); + await button.click(); + + await expect(page).toMatchElement("div", { text: 'WHICH IS THE CAPITAL OF SPAIN?'}); + const question = await page.$['data-testid="question"']; + expect(question).not.toBeNull(); + + const answers = await page.$x('//*[contains(@data-testid, "answer")]'); + expect(answers.length).toBe(2); }); when('I click on an incorrect answer button', async () => { - const answers = await page.$x('//*[@data-testid="answer"]'); - const textoBoton1 = await page.evaluate(button => button.innerText, answers[0]); - if(textoBoton1 !== "Madrid") { - await answers[0].click(); - } else { - await answers[1].click(); - } + const answers = await page.$x('//*[contains(@data-testid, "answer")]'); + const textoBoton1 = await page.evaluate(button => button.innerText, answers[0]); + if(textoBoton1 !== "Madrid") { + await answers[0].click(); + } else { + await answers[1].click(); + } }); then('The button turns red', async () => { - /*const answerButton = await page.$x('(//*[@data-testid="answer"])[2]'); - const textoBoton1 = await page.evaluate(button => button.innerText, answerButton[0]); - const textoBoton2 = await page.evaluate(button => button.innerText, answerButton[1]); - if(textoBoton1 !== "Madrid") { - await expect(textoBoton1).not.toMatch(/Madrid/i); - } else { - await expect(textoBoton2).toMatch(/Madrid/i); - }*/ - await expect(page).toMatchElement("button", { style: { color: 'red' } }); - await expect(page).toMatchElement("button", { style: { color: 'green' } }); + await expect(page).toMatchElement("button", { style: { color: 'red' } }); + await expect(page).toMatchElement("button", { style: { color: 'green' } }); }); }) From 03273bd0d6a3f73ddc12efb9e2dd967b48af18ae Mon Sep 17 00:00:00 2001 From: Pablo Date: Fri, 26 Apr 2024 20:11:40 +0200 Subject: [PATCH 104/132] Solved style dependant e2e tests --- .../e2e/features/discoveringCitiesGame.feature | 4 ++-- webapp/e2e/features/wiseMenStackGame.feature | 4 ++-- webapp/e2e/steps/discoveringCitiesGame.steps.js | 16 +++++++--------- webapp/e2e/steps/wiseMenStackGame.steps.js | 17 ++++++++++------- 4 files changed, 21 insertions(+), 20 deletions(-) diff --git a/webapp/e2e/features/discoveringCitiesGame.feature b/webapp/e2e/features/discoveringCitiesGame.feature index 6a63bd96..415f3d2e 100644 --- a/webapp/e2e/features/discoveringCitiesGame.feature +++ b/webapp/e2e/features/discoveringCitiesGame.feature @@ -3,9 +3,9 @@ Feature: Answer a question Scenario: Answering a question correctly Given A question When I click on the correct answer button - Then The button turns green + Then The selected answer is marked as right Scenario: Answering a question incorrectly Given A question When I click on an incorrect answer button - Then The button turns red \ No newline at end of file + Then The selected answer is marked as wrong \ No newline at end of file diff --git a/webapp/e2e/features/wiseMenStackGame.feature b/webapp/e2e/features/wiseMenStackGame.feature index 6a63bd96..415f3d2e 100644 --- a/webapp/e2e/features/wiseMenStackGame.feature +++ b/webapp/e2e/features/wiseMenStackGame.feature @@ -3,9 +3,9 @@ Feature: Answer a question Scenario: Answering a question correctly Given A question When I click on the correct answer button - Then The button turns green + Then The selected answer is marked as right Scenario: Answering a question incorrectly Given A question When I click on an incorrect answer button - Then The button turns red \ No newline at end of file + Then The selected answer is marked as wrong \ No newline at end of file diff --git a/webapp/e2e/steps/discoveringCitiesGame.steps.js b/webapp/e2e/steps/discoveringCitiesGame.steps.js index 506121c9..12ccb40e 100644 --- a/webapp/e2e/steps/discoveringCitiesGame.steps.js +++ b/webapp/e2e/steps/discoveringCitiesGame.steps.js @@ -78,11 +78,11 @@ defineFeature(feature, test => { await answers[0].click(); }); - then('The button turns green', async () => { + then('The selected answer is marked as right', async () => { const answer = await page.$x('//*[contains(@data-testid, "success")]'); + expect(answer.length).toBe(1); const textoBoton = await page.evaluate(button => button.innerText, answer[0]); await expect(textoBoton).toMatch(/Madrid/i); - await expect(page).toMatchElement("button", { style: { color: 'green' } }); }); }) @@ -99,16 +99,14 @@ defineFeature(feature, test => { when('I click on an incorrect answer button', async () => { const answers = await page.$x('//*[contains(@data-testid, "answer")]'); - await answers[2].click(); + await answers[1].click(); }); - then('The button turns red', async () => { - const answerButtons = await page.$x('//*[contains(@data-testid, "answer")]'); - const textoBoton = await page.evaluate(button => button.innerText, answerButtons[0]); + then('The selected answer is marked as wrong', async () => { + const answer = await page.$x('//*[contains(@data-testid, "fail")]'); + expect(answer.length).toBe(1); + const textoBoton = await page.evaluate(button => button.innerText, answer[0]); await expect(textoBoton).toMatch(/Barcelona/i); - await expect(page).toMatchElement("button", { style: { color: 'red' } }); - await expect(page).toMatchElement("button", { style: { color: 'green' } }); - }); }) diff --git a/webapp/e2e/steps/wiseMenStackGame.steps.js b/webapp/e2e/steps/wiseMenStackGame.steps.js index 0630276e..0c2feb8e 100644 --- a/webapp/e2e/steps/wiseMenStackGame.steps.js +++ b/webapp/e2e/steps/wiseMenStackGame.steps.js @@ -79,15 +79,18 @@ defineFeature(feature, test => { when('I click on the correct answer button', async () => { const answers = await page.$x('//*[contains(@data-testid, "answer")]'); const textoBoton1 = await page.evaluate(button => button.innerText, answers[0]); - if(textoBoton1 === "Madrid") { + if(textoBoton1 === "MADRID") { await answers[0].click(); } else { await answers[1].click(); } }); - then('The button turns green', async () => { - await expect(page).toMatchElement("button", { style: { color: 'green' } }); + then('The selected answer is marked as right', async () => { + const answer = await page.$x('//*[contains(@data-testid, "success")]'); + expect(answer.length).toBe(1); + const textoBoton = await page.evaluate(button => button.innerText, answer[0]); + await expect(textoBoton).toMatch(/Madrid/i); }); }) @@ -108,16 +111,16 @@ defineFeature(feature, test => { when('I click on an incorrect answer button', async () => { const answers = await page.$x('//*[contains(@data-testid, "answer")]'); const textoBoton1 = await page.evaluate(button => button.innerText, answers[0]); - if(textoBoton1 !== "Madrid") { + if(textoBoton1 !== "MADRID") { await answers[0].click(); } else { await answers[1].click(); } }); - then('The button turns red', async () => { - await expect(page).toMatchElement("button", { style: { color: 'red' } }); - await expect(page).toMatchElement("button", { style: { color: 'green' } }); + then('The selected answer is marked as wrong', async () => { + const answer = await page.$x('//*[contains(@data-testid, "fail")]'); + expect(answer.length).toBe(1); }); }) From c35c96c844b98a5e1781d0ffd61b3455844b2f5c Mon Sep 17 00:00:00 2001 From: Pablo Date: Fri, 26 Apr 2024 20:12:35 +0200 Subject: [PATCH 105/132] Minor error in test-id for the answers --- webapp/src/pages/DiscoveringCitiesGame.js | 2 +- webapp/src/pages/Game.js | 2 +- webapp/src/pages/MultiplayerGame.js | 2 +- webapp/src/pages/TheChallengeGame.js | 2 +- webapp/src/pages/WarmQuestionGame.js | 2 +- webapp/src/pages/WiseMenStackGame.js | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/webapp/src/pages/DiscoveringCitiesGame.js b/webapp/src/pages/DiscoveringCitiesGame.js index eb3d3741..4773f745 100644 --- a/webapp/src/pages/DiscoveringCitiesGame.js +++ b/webapp/src/pages/DiscoveringCitiesGame.js @@ -293,7 +293,7 @@ const DiscovertingCitiesGame = () => { {questionData.options.map((option, index) => ( - +