Added new Question-Type: TextAnswers!

This commit is contained in:
Mawoka
2022-12-29 16:16:09 +01:00
parent 1633d56299
commit 7614420d0c
10 changed files with 257 additions and 39 deletions
+8 -8
View File
@@ -115,21 +115,19 @@ class QuizQuestionType(str, Enum):
RANGE = "RANGE" RANGE = "RANGE"
VOTING = "VOTING" VOTING = "VOTING"
SLIDE = "SLIDE" SLIDE = "SLIDE"
class SlideElementTypes(str, Enum):
TEXT = "TEXT" TEXT = "TEXT"
HEADLINE = "HEADLINE"
IMAGE = "IMAGE"
RECTANGLE = "RECTANGLE" class TextQuizAnswer(BaseModel):
CIRCLE = "CIRCLE" answer: str
case_sensitive: bool
class QuizQuestion(BaseModel): class QuizQuestion(BaseModel):
question: str question: str
time: str # in Secs time: str # in Secs
type: None | QuizQuestionType = QuizQuestionType.ABCD type: None | QuizQuestionType = QuizQuestionType.ABCD
answers: list[ABCDQuizAnswer] | RangeQuizAnswer | list[VotingQuizAnswer] | str answers: list[ABCDQuizAnswer] | RangeQuizAnswer | list[TextQuizAnswer] | list[VotingQuizAnswer] | str
image: str | None = None image: str | None = None
@validator("answers") @validator("answers")
@@ -140,6 +138,8 @@ class QuizQuestion(BaseModel):
raise ValueError("Answer must be from type RangeQuizAnswer if type is RANGE") raise ValueError("Answer must be from type RangeQuizAnswer if type is RANGE")
if values["type"] == QuizQuestionType.VOTING and type(v[0]) != VotingQuizAnswer: if values["type"] == QuizQuestionType.VOTING and type(v[0]) != VotingQuizAnswer:
raise ValueError("Answer must be from type VotingQuizAnswer if type is VOTING") raise ValueError("Answer must be from type VotingQuizAnswer if type is VOTING")
if values["type"] == QuizQuestionType.TEXT and type(v[0]) != TextQuizAnswer:
raise ValueError("Answer must be from type TextQuizAnswer if type is TEXT")
if values["type"] == QuizQuestionType.SLIDE and type(v[0]) != str: if values["type"] == QuizQuestionType.SLIDE and type(v[0]) != str:
raise ValueError("Answer must be from type SlideElement if type is SLIDE") raise ValueError("Answer must be from type SlideElement if type is SLIDE")
return v return v
+15 -2
View File
@@ -209,6 +209,7 @@ class RangeQuizAnswerWithoutSolution(BaseModel):
class ReturnQuestion(QuizQuestion): class ReturnQuestion(QuizQuestion):
answers: list[ABCDQuizAnswerWithoutSolution] | RangeQuizAnswerWithoutSolution | list[VotingQuizAnswer] answers: list[ABCDQuizAnswerWithoutSolution] | RangeQuizAnswerWithoutSolution | list[VotingQuizAnswer]
type: QuizQuestionType = QuizQuestionType.ABCD
@validator("answers") @validator("answers")
def answers_not_none_if_abcd_type(cls, v, values): def answers_not_none_if_abcd_type(cls, v, values):
@@ -226,7 +227,7 @@ class ReturnQuestion(QuizQuestion):
async def set_question_number(sid, data: str): async def set_question_number(sid, data: str):
# data is just a number (as a str) of the question # data is just a number (as a str) of the question
session = await sio.get_session(sid) session = await sio.get_session(sid)
print("set_question_number", data, session) # print("set_question_number", data, session)
if session["admin"]: if session["admin"]:
game_pin = session["game_pin"] game_pin = session["game_pin"]
game_data = PlayGame.parse_raw(await redis.get(f"game:{session['game_pin']}")) game_data = PlayGame.parse_raw(await redis.get(f"game:{session['game_pin']}"))
@@ -246,7 +247,8 @@ async def set_question_number(sid, data: str):
if game_data.questions[int(float(data))].type == QuizQuestionType.VOTING: if game_data.questions[int(float(data))].type == QuizQuestionType.VOTING:
for i in range(len(temp_return["answers"])): for i in range(len(temp_return["answers"])):
temp_return["answers"][i] = VotingQuizAnswer(**temp_return["answers"][i]) temp_return["answers"][i] = VotingQuizAnswer(**temp_return["answers"][i])
print("emitting") temp_return["type"] = game_data.questions[int(float(data))].type
# print("emitting")
await sio.emit( await sio.emit(
"set_question_number", "set_question_number",
{ {
@@ -301,6 +303,17 @@ async def submit_answer(sid: str, data: dict):
answer_right = True answer_right = True
elif game_data.questions[int(float(data.question_index))].type == QuizQuestionType.VOTING: elif game_data.questions[int(float(data.question_index))].type == QuizQuestionType.VOTING:
answer_right = False answer_right = False
elif game_data.questions[int(float(data.question_index))].type == QuizQuestionType.TEXT:
answer_right = False
for q in game_data.questions[int(float(data.question_index))].answers:
if q.case_sensitive:
if data.answer == q.answer:
answer_right = True
break
else:
if data.answer.lower() == q.answer.lower():
answer_right = True
break
else: else:
raise NotImplementedError raise NotImplementedError
latency = int(float((await sio.get_session(sid))["ping"])) latency = int(float((await sio.get_session(sid))["ping"]))
+15
View File
@@ -248,6 +248,21 @@
</div> </div>
{/each} {/each}
</div> </div>
{:else if quiz_data.questions[selected_question].type === QuizQuestionType.TEXT}
{#if timer_res === '0'}
<div class="grid grid-cols-2 gap-2 w-full p-4">
{#each quiz_data.questions[selected_question].answers as answer, i}
<div class="rounded-lg h-fit flex bg-[#B07156]">
<span class="text-center text-2xl px-2 py-4 w-full text-black"
>{answer.answer}</span
>
<span class="pl-4 w-10" />
</div>
{/each}
</div>
{:else}
<p>Enter your answer into the input field!</p>
{/if}
{/if} {/if}
{/if} {/if}
{/if} {/if}
@@ -0,0 +1,136 @@
<!--
- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
-->
<script lang="ts">
import { fade } from 'svelte/transition';
import type { EditorData, TextQuizAnswer } from '$lib/quiz_types';
import { getLocalization } from '$lib/i18n';
import { reach } from 'yup';
import { TextQuestionSchema } from '$lib/yupSchemas';
export let selected_question: number;
export let data: EditorData;
const { t } = getLocalization();
if (!Array.isArray(data.questions[selected_question].answers)) {
data.questions[selected_question].answers = [];
}
for (let i = 0; i < data.questions[selected_question].answers.length; i++) {
data.questions[selected_question].answers[i] = {
answer: data.questions[selected_question].answers[i].answer,
case_sensitive: false
};
}
const get_empty_answer = (): TextQuizAnswer => {
return {
answer: '',
case_sensitive: false
};
};
</script>
<div class="grid grid-cols-2 gap-4 w-full px-10">
{#if Array.isArray(data.questions[selected_question].answers)}
{#each data.questions[selected_question].answers as answer, index}
<div
out:fade={{ duration: 150 }}
class="p-4 rounded-lg flex justify-center w-full transition relative"
class:dark:bg-gray-500={answer.answer}
class:bg-gray-300={answer.answer}
class:bg-yellow-500={!reach(TextQuestionSchema, 'answer').isValidSync(
answer.answer
)}
>
<button
class="rounded-full absolute -top-2 -right-2 opacity-70 hover:opacity-100 transition"
type="button"
on:click={() => {
data.questions[selected_question].answers.splice(index, 1);
data.questions[selected_question].answers =
data.questions[selected_question].answers;
}}
>
<svg
class="w-6 h-6 bg-red-500 rounded-full"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
</button>
<input
bind:value={answer.answer}
type="text"
class="border-b-2 border-dotted w-5/6 text-center rounded-lg"
placeholder="Empty..."
/>
<button
type="button"
on:click={() => {
answer.case_sensitive = !answer.case_sensitive;
console.log(answer.case_sensitive);
}}
>
{#if answer.case_sensitive}
<svg
class="w-6 h-6 inline-block"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
{:else}
<svg
class="w-6 h-6 inline-block"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
{/if}
</button>
</div>
{/each}
{/if}
{#if data.questions[selected_question].answers.length < 4}
<button
class="p-4 rounded-lg bg-transparent border-gray-500 border-2 hover:bg-gray-300 transition dark:hover:bg-gray-600"
type="button"
in:fade={{ duration: 150 }}
on:click={() => {
data.questions[selected_question].answers = [
...data.questions[selected_question].answers,
{ ...get_empty_answer() }
];
}}
>
<span class="italic text-center">{$t('editor_page.add_an_answer')}</span>
</button>
{/if}
</div>
+7
View File
@@ -182,6 +182,7 @@
<option value={QuizQuestionType.RANGE}>{$t('words.range')}</option> <option value={QuizQuestionType.RANGE}>{$t('words.range')}</option>
<option value={QuizQuestionType.ABCD}>{$t('words.multiple_choice')}</option> <option value={QuizQuestionType.ABCD}>{$t('words.multiple_choice')}</option>
<option value={QuizQuestionType.VOTING}>{$t('words.voting')}</option> <option value={QuizQuestionType.VOTING}>{$t('words.voting')}</option>
<option value={QuizQuestionType.TEXT}>{$t('words.text')}</option>
</select> </select>
</div> </div>
<div class="flex justify-center py-10 w-full"> <div class="flex justify-center py-10 w-full">
@@ -199,6 +200,12 @@
{:then c} {:then c}
<svelte:component this={c.default} bind:data bind:selected_question /> <svelte:component this={c.default} bind:data bind:selected_question />
{/await} {/await}
{:else if data.questions[selected_question].type === QuizQuestionType.TEXT}
{#await import('$lib/editor/TextEditorPart.svelte')}
<Spinner my_20={false} />
{:then c}
<svelte:component this={c.default} bind:data bind:selected_question />
{/await}
{/if} {/if}
</div> </div>
</div> </div>
+17
View File
@@ -72,6 +72,8 @@
}); });
}; };
let text_input = '';
let slider_value = [0]; let slider_value = [0];
if (question.type === QuizQuestionType.RANGE) { if (question.type === QuizQuestionType.RANGE) {
slider_value[0] = (question.answers.max - question.answers.min) / 2 + question.answers.min; slider_value[0] = (question.answers.max - question.answers.min) / 2 + question.answers.min;
@@ -187,6 +189,21 @@
</button> </button>
</div> </div>
{/await} {/await}
{:else if question.type === QuizQuestionType.TEXT}
<input bind:value={text_input} />
<div class="flex justify-center">
<button
class="bg-[#B07156] hover:bg-amber-700 text-white font-bold py-2 px-4 rounded disabled:opacity-50 disabled:cursor-not-allowed mt-2"
type="button"
disabled={!text_input}
on:click={() => {
selectAnswer(text_input);
}}
>
{$t('words.submit')}
</button>
</div>
{/if} {/if}
{:else if question.type === QuizQuestionType.ABCD} {:else if question.type === QuizQuestionType.ABCD}
{#if solution === undefined} {#if solution === undefined}
+30 -1
View File
@@ -39,6 +39,7 @@
} }
let slider_values = [question.answers.min_correct ?? 0, question.answers.max_correct ?? 0]; let slider_values = [question.answers.min_correct ?? 0, question.answers.max_correct ?? 0];
let text_input;
timer(question.time); timer(question.time);
</script> </script>
@@ -125,7 +126,7 @@
</div> </div>
<div class="flex justify-center"> <div class="flex justify-center">
<button <button
class="w-1/2 text-3xl bg-[#B07156] my-2 disabled:opacity-60 border border-white" class="w-1/3 text-3xl bg-[#B07156] my-2 disabled:opacity-60 rounded-lg p-1 transition"
disabled={selected_answer !== undefined} disabled={selected_answer !== undefined}
on:click={() => { on:click={() => {
selected_answer = slider_value[0]; selected_answer = slider_value[0];
@@ -158,5 +159,33 @@
<svelte:component this={c.default} bind:question /> <svelte:component this={c.default} bind:question />
</div> </div>
{/await} {/await}
{:else if question.type === QuizQuestionType.TEXT}
{#if timer_res === '0'}
{#each question.answers as answer, i}
<div
class="p-2 rounded-lg flex justify-center w-full transition bg-gray-200 my-5 text-black"
>
{answer.answer}
</div>
{/each}
{:else}
<div class="flex justify-center mt-2">
<input
type="text"
bind:value={text_input}
class="bg-gray-50 focus:ring text-gray-900 rounded-lg focus:ring-blue-500 block w-full p-2 dark:bg-gray-700 dark:text-white dark:focus:ring-blue-500 outline-none transition text-center"
/>
</div>
<div class="flex justify-center">
<button
disabled={!text_input}
class="w-1/3 text-3xl bg-[#B07156] my-2 disabled:opacity-60 rounded-lg p-1 transition"
on:click={() => {
selected_answer = text_input;
timer_res = '0';
}}>{$t('words.submit')}</button
>
</div>
{/if}
{/if} {/if}
</div> </div>
+8 -2
View File
@@ -29,7 +29,8 @@ export enum QuizQuestionType {
ABCD = 'ABCD', // eslint-disable-line no-unused-vars ABCD = 'ABCD', // eslint-disable-line no-unused-vars
RANGE = 'RANGE', // eslint-disable-line no-unused-vars RANGE = 'RANGE', // eslint-disable-line no-unused-vars
VOTING = 'VOTING', // eslint-disable-line no-unused-vars VOTING = 'VOTING', // eslint-disable-line no-unused-vars
SLIDE = 'SLIDE' // eslint-disable-line no-unused-vars SLIDE = 'SLIDE', // eslint-disable-line no-unused-vars
TEXT = 'TEXT' // eslint-disable-line no-unused-vars
} }
export interface RangeQuizAnswer { export interface RangeQuizAnswer {
@@ -39,12 +40,17 @@ export interface RangeQuizAnswer {
max_correct: number; max_correct: number;
} }
export interface TextQuizAnswer {
answer: string;
case_sensitive: boolean;
}
export interface Question { export interface Question {
time: string; time: string;
question: string; question: string;
type?: QuizQuestionType; type?: QuizQuestionType;
image?: string; image?: string;
answers: Answer[] | RangeQuizAnswer | VotingAnswer[] | string; answers: Answer[] | RangeQuizAnswer | VotingAnswer[] | string | TextQuizAnswer[];
} }
export interface Answer { export interface Answer {
+20 -25
View File
@@ -35,17 +35,17 @@ export const RangeQuestionSchema = yup.object({
max_correct: yup.number() max_correct: yup.number()
}); });
export const SlideQuestionSchema = yup.array().of( export const TextQuestionSchema = yup
yup.object({ .array()
type: yup.string().required(), .of(
x: yup.number(), yup.object({
y: yup.number(), case_sensitive: yup.boolean().required(),
height: yup.number(), answer: yup.string().required('You need an answer')
width: yup.number(), })
data: yup.string().optional(), )
id: yup.number().required() .min(2, 'You need at least 2 answers')
}) .max(16, "You can't have more than 16 answers");
);
export const dataSchema = yup.object({ export const dataSchema = yup.object({
public: yup.boolean().required(), public: yup.boolean().required(),
type: yup.string(), type: yup.string(),
@@ -75,20 +75,15 @@ export const dataSchema = yup.object({
.lowercase(), .lowercase(),
answers: yup.lazy((v) => { answers: yup.lazy((v) => {
if (Array.isArray(v)) { if (Array.isArray(v)) {
try { if (typeof v[0].right === 'boolean') {
if (typeof v[0].right === 'boolean') { console.log('ABCDQuestionSchema');
console.log('ABCDQuestionSchema'); return ABCDQuestionSchema;
return ABCDQuestionSchema; } else if (typeof v[0].case_sensitive === 'boolean') {
} else if (v[0].answer !== undefined) { console.log('TextQuestionSchema');
console.log('VotingQuestionSchema'); return TextQuestionSchema;
return VotingQuestionSchema; } else if (v[0].answer !== undefined) {
} else { console.log('VotingQuestionSchema');
console.log('SlideQuestionSchema'); return VotingQuestionSchema;
return yup.string().required().nullable();
}
} catch {
console.log('SlideQuestionSchema');
return yup.string().required("The slide mustn't be empty").nullable();
} }
} else if (typeof v === 'string' || v instanceof String) { } else if (typeof v === 'string' || v instanceof String) {
return yup.string().required("The slide mustn't be empty").nullable(); return yup.string().required("The slide mustn't be empty").nullable();
@@ -218,7 +218,7 @@
and {question.answers.max_correct} are correct, where numbers between {question and {question.answers.max_correct} are correct, where numbers between {question
.answers.min} and {question.answers.max} can be selected. .answers.min} and {question.answers.max} can be selected.
</p> </p>
{:else if question.type === QuizQuestionType.VOTING} {:else if question.type === QuizQuestionType.VOTING || question.type === QuizQuestionType.TEXT}
<div class="grid grid-cols-2 gap-4 m-4 p-6"> <div class="grid grid-cols-2 gap-4 m-4 p-6">
{#each question.answers as answer, index_answer} {#each question.answers as answer, index_answer}
<div class="p-1 rounded-lg py-4 dark:bg-gray-500 bg-gray-300"> <div class="p-1 rounded-lg py-4 dark:bg-gray-500 bg-gray-300">