Add overview of open and completed quiz rounds

This commit is contained in:
2022-11-08 00:28:12 +01:00
parent b45114a2d1
commit 22deb8812a
8 changed files with 317 additions and 133 deletions

View File

@@ -2,54 +2,44 @@
<v-card> <v-card>
<ValidationObserver ref="observer" v-slot="{ invalid }"> <ValidationObserver ref="observer" v-slot="{ invalid }">
<form @submit.prevent="submit"> <form @submit.prevent="submit">
<v-card-title style="cursor: pointer;" @click="showBody = !showBody"> <v-card-text>
<span class="flex-grow-1 flex-shrink-0 text-subtitle-1 font-weight-medium">Eigene Quizfrage einreichen</span> <v-row>
<v-btn icon @click.stop="showBody = !showBody"> <v-col cols="12">
<v-icon>{{ showBody ? 'mdi-chevron-up' : 'mdi-chevron-down' }}</v-icon> <ValidationProvider v-slot="{ errors }" name="frage" rules="required">
</v-btn> <v-text-field v-model="question" required label="Frage" :error-messages="errors"></v-text-field>
</v-card-title> </ValidationProvider>
<v-expand-transition> </v-col>
<div v-show="showBody"> <v-col v-for="(n, index) in 4" :key="index" cols="6">
<v-card-text> <ValidationProvider v-slot="{ errors }" :name="`antwort${n}`" rules="required">
<v-row> <v-text-field v-model="answers[index]" required :label="`Antwort #${n}`" :error-messages="errors"></v-text-field>
<v-col cols="12"> </ValidationProvider>
<ValidationProvider v-slot="{ errors }" name="frage" rules="required"> </v-col>
<v-text-field v-model="question" required label="Frage" :error-messages="errors"></v-text-field> <v-col cols="12">
</ValidationProvider> <ValidationProvider v-slot="{ errors }" name="richtig" rules="required">
</v-col> <v-select v-model="correctAnswer" required :items="answers" label="Richtige Antwort" :error-messages="errors"></v-select>
<v-col v-for="(n, index) in 4" :key="index" cols="6"> </ValidationProvider>
<ValidationProvider v-slot="{ errors }" :name="`antwort${n}`" rules="required"> </v-col>
<v-text-field v-model="answers[index]" required :label="`Antwort #${n}`" :error-messages="errors"></v-text-field> <v-col cols="12">
</ValidationProvider> <v-text-field
</v-col> v-model="comment"
<v-col cols="12"> label="(Optional) Anmerkung"
<ValidationProvider v-slot="{ errors }" name="richtig" rules="required"> persistent-hint
<v-select v-model="correctAnswer" required :items="answers" label="Richtige Antwort" :error-messages="errors"></v-select> hint="Nur der Tutor kann deine Anmerkung sehen."
</ValidationProvider> >
</v-col> <template #message="{ message }">
<v-col cols="12"> <v-icon small>mdi-information</v-icon>
<v-text-field <span>{{ message }}</span>
v-model="comment" </template>
label="(Optional) Anmerkung" </v-text-field>
persistent-hint </v-col>
hint="Nur der Tutor kann deine Anmerkung sehen." </v-row>
> </v-card-text>
<template #message="{ message }"> <v-card-actions>
<v-icon small>mdi-information</v-icon> <v-btn v-if="$config.NODE_ENV !== 'production'" depressed color="warning" @click="addQuestionsForTesting">+10 Fragen</v-btn>
<span>{{ message }}</span> <v-spacer />
</template> <v-btn text color="primary" @click="clear">Reset</v-btn>
</v-text-field> <v-btn type="submit" depressed color="primary" :loading="loading" :disabled="invalid">Einreichen</v-btn>
</v-col> </v-card-actions>
</v-row>
</v-card-text>
<v-card-actions>
<v-btn v-if="$config.NODE_ENV !== 'production'" depressed color="warning" @click="addQuestionsForTesting">+10 Fragen</v-btn>
<v-spacer />
<v-btn text color="primary" @click="clear">Reset</v-btn>
<v-btn type="submit" depressed color="primary" :loading="loading" :disabled="invalid">Einreichen</v-btn>
</v-card-actions>
</div>
</v-expand-transition>
</form> </form>
</ValidationObserver> </ValidationObserver>
</v-card> </v-card>
@@ -76,7 +66,6 @@ export default {
}, },
data () { data () {
return { return {
showBody: false,
loading: false, loading: false,
question: '', question: '',
answers: [], answers: [],

View File

@@ -1,64 +0,0 @@
<template>
<v-card>
<v-card-title>
Spiele {{ games.won + games.lost + games.tie }}
</v-card-title>
<v-card-subtitle>
<div>Siege: {{ games.won }}</div>
<div>Unentschieden: {{ games.lost }}</div>
<div>Niederlagen: {{ games.tie }}</div>
<div>Fragen: {{ games.questionsCorrect + games.questionsIncorrect }}</div>
<div>Richtig: {{ questionsCorrectPercent }}%</div>
</v-card-subtitle>
<v-card-text>
{{ text }}
</v-card-text>
<v-card-text>
<v-btn depressed color="success" class="my-3" @click="playVersus">
<v-icon left>mdi-play</v-icon>
Spielen
</v-btn>
</v-card-text>
<v-divider></v-divider>
<AddClosedEndedQuestion />
</v-card>
</template>
<script>
export default {
name: 'ChallengeComponent',
props: {
courseId: {
type: String,
required: true
}
},
data () {
return {
}
},
computed: {
games () {
return this.$store.state.user.games[this.courseId]
},
questionsCorrectPercent () {
const percent = (this.games.questionsCorrect / (this.games.questionsCorrect + this.games.questionsIncorrect)) * 100
// percent will be NaN if the student hasn't played any games yet
return percent ? Math.round(parseFloat(percent)) : 100 // Convert to float, then round to closest int
},
text () {
if (this.questionsAnswered >= 20 && this.questionsCorrectPercent >= 90) {
return 'Du scheinst gut auf die Klausur vorbereitet zu sein. Viel Glück!'
} else {
return 'Wir empfehlen Dir noch ein wenig zu üben, bevor du zur Klausur antrittst.'
}
}
},
methods: {
playVersus () {
// TODO
this.$router.push(`${this.$route.path}/play`)
}
}
}
</script>

View File

@@ -0,0 +1,48 @@
<template>
<v-card width="500">
<v-row align="center">
<v-col cols="auto">
<v-icon size="48" color="amber">{{ icon }}</v-icon>
</v-col>
<v-col>
<div class="text-h6 text--primary">{{ title }}</div>
<div class="text-caption text--secondary">gegen {{ opponentName }}</div>
</v-col>
</v-row>
</v-card>
</template>
<script>
import { Game } from '~/plugins/game'
export default {
name: 'CompletedGameCard',
props: {
game: {
type: Game,
required: true
}
},
computed: {
result () {
return this.game.getResult()
},
playerNumber () {
return this.game.player1id === this.$auth.currentUser.uid ? 1 : 2
},
isWinner () {
return !this.result.tie && this.result.winner === this.playerNumber
},
title () {
if (this.result.tie) return 'Unentschieden'
else return this.isWinner ? 'Sieg' : 'Niederlage'
},
icon () {
return this.isWinner ? 'mdi-trophy' : 'mdi-trophy-broken'
},
opponentName () {
return this.game.player1id === this.$auth.currentUser.uid ? this.game.player2name : this.game.player1name
}
}
}
</script>

View File

@@ -0,0 +1,48 @@
<template>
<v-card outlined width="500">
<v-card-text>
<v-row align="center" justify="center" no-gutters class="text-subtitle-1">
<v-col cols="auto">
<div class="text--primary text-center">{{ game.player1name }}</div>
<v-icon
v-for="oneIndex, zeroIndex in game.questionIds.length" :key="'pl1'+zeroIndex"
small
:color="dotColor(game, 1, zeroIndex)"
>mdi-circle</v-icon>
</v-col>
<v-col cols="auto" class="mx-12">vs.</v-col>
<v-col cols="auto">
<div class="text--primary text-center">{{ game.player2name || '?' }}</div>
<v-icon
v-for="oneIndex, zeroIndex in game.questionIds.length" :key="'pl2'+zeroIndex"
small
:color="dotColor(game, 2, zeroIndex)"
>mdi-circle</v-icon>
</v-col>
</v-row>
</v-card-text>
</v-card>
</template>
<script>
import { Game } from '~/plugins/game'
export default {
name: 'OpenGameCard',
props: {
game: {
type: Game,
required: true
}
},
methods: {
dotColor (game, playerNumber, index) {
if (!game || index + 1 > game[`player${playerNumber}answers`].length) return ''
else {
const correct = game[`player${playerNumber}answers`][index].richtig
return correct ? 'success' : 'error'
}
}
}
}
</script>

View File

@@ -0,0 +1,153 @@
<template>
<v-card>
<v-card-title>Challenge</v-card-title>
<v-card-text>
<v-btn depressed color="success" class="my-3" @click="playVersus">
<v-icon left>mdi-play</v-icon>
Spielen
</v-btn>
</v-card-text>
<v-expansion-panels v-model="expPanel" accordion class="text-subtitle-1 font-weight-medium">
<v-expansion-panel>
<v-expansion-panel-header>
Offene Spiele ({{ openGames.length }})
</v-expansion-panel-header>
<v-expansion-panel-content>
<v-row>
<v-col v-for="(og, i) in openGames" :key="i" cols="12">
<OpenGameCard :game="og" />
</v-col>
</v-row>
</v-expansion-panel-content>
</v-expansion-panel>
<v-expansion-panel>
<v-expansion-panel-header>
Beendete Spiele ({{ completedGames.length }})
</v-expansion-panel-header>
<v-expansion-panel-content>
<v-row>
<v-col v-for="(cg, i) in completedGames" :key="i" cols="12">
<CompletedGameCard :game="cg" />
</v-col>
</v-row>
</v-expansion-panel-content>
</v-expansion-panel>
<v-expansion-panel>
<v-expansion-panel-header>
Persönliche Statistik
</v-expansion-panel-header>
<v-expansion-panel-content>
<v-card-title>
Spiele {{ games.won + games.lost + games.tie }}
</v-card-title>
<v-card-subtitle>
<div>Siege: {{ games.won }}</div>
<div>Unentschieden: {{ games.lost }}</div>
<div>Niederlagen: {{ games.tie }}</div>
<div>Fragen: {{ games.questionsCorrect + games.questionsIncorrect }}</div>
<div>Richtig: {{ questionsCorrectPercent }}%</div>
</v-card-subtitle>
<v-card-text>
{{ text }}
</v-card-text>
</v-expansion-panel-content>
</v-expansion-panel>
<v-expansion-panel>
<v-expansion-panel-header>
Neue Quizfrage einreichen
</v-expansion-panel-header>
<v-expansion-panel-content>
<AddClosedEndedQuestion />
</v-expansion-panel-content>
</v-expansion-panel>
</v-expansion-panels>
</v-card>
</template>
<script>
import { collection, query, where, orderBy, limit, getDocs } from 'firebase/firestore'
import { GameConverter } from '~/plugins/game'
export default {
name: 'QuizComponent',
props: {
courseId: {
type: String,
required: true
}
},
data () {
return {
openGames: [],
completedGames: [],
expPanel: 0
}
},
computed: {
games () {
return this.$store.state.user.games[this.courseId]
},
questionsCorrectPercent () {
const percent = (this.games.questionsCorrect / (this.games.questionsCorrect + this.games.questionsIncorrect)) * 100
// percent will be NaN if the student hasn't played any games yet
return percent ? Math.round(parseFloat(percent)) : 100 // Convert to float, then round to closest int
},
text () {
if (this.questionsAnswered >= 20 && this.questionsCorrectPercent >= 90) {
return 'Du scheinst gut auf die Klausur vorbereitet zu sein. Viel Glück!'
} else {
return 'Wir empfehlen Dir noch ein wenig zu üben, bevor du zur Klausur antrittst.'
}
}
},
created () {
// Get list of unfinished games from db
this.getOpenGames()
// Get list of completed games from db (limit to 10 most recent)
this.getCompletedGames()
},
methods: {
getOpenGames () {
const q = query(
collection(this.$db, `kurse/${this.courseId}/spiele`).withConverter(GameConverter),
where('abgeschlossen', '==', false),
where('spielerIds', 'array-contains', this.$auth.currentUser.uid),
orderBy('erstellt', 'desc')
)
getDocs(q).then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
this.openGames.push(doc.data())
})
}).catch((error) => {
// Query failed; display error message
this.$toast({ content: error, color: 'error' })
})
},
getCompletedGames () {
const q = query(
collection(this.$db, `kurse/${this.courseId}/spiele`).withConverter(GameConverter),
where('abgeschlossen', '==', true),
where('spielerIds', 'array-contains', this.$auth.currentUser.uid),
orderBy('erstellt', 'desc'),
limit(10)
)
getDocs(q).then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
this.completedGames.push(doc.data())
})
}).catch((error) => {
// Query failed; display error message
this.$toast({ content: error, color: 'error' })
})
},
playVersus () {
// TODO
this.$router.push(`${this.$route.path}/play`)
}
}
}
</script>

View File

@@ -42,7 +42,7 @@
<TutorPanel :course-id="courseID" /> <TutorPanel :course-id="courseID" />
</v-col> </v-col>
<v-col cols="12"> <v-col cols="12">
<Challenge :course-id="courseID" /> <QuizComponent :course-id="courseID" />
</v-col> </v-col>
<v-col cols="12"> <v-col cols="12">
<Coop :course-id="courseID" /> <Coop :course-id="courseID" />

View File

@@ -181,6 +181,7 @@ export default {
this.game.player2id = this.$auth.currentUser.uid this.game.player2id = this.$auth.currentUser.uid
this.game.player2name = this.$store.state.user.displayName this.game.player2name = this.$store.state.user.displayName
this.game.player2answers = [] this.game.player2answers = []
this.game.playerIds.push(this.game.player2id)
// Get a new write batch // Get a new write batch
const batch = writeBatch(this.$db) const batch = writeBatch(this.$db)
@@ -214,6 +215,7 @@ export default {
null, null,
rndQuestions.map(q => q.id), rndQuestions.map(q => q.id),
Date.now() / 1000, // Current UNIX timestamp in seconds Date.now() / 1000, // Current UNIX timestamp in seconds
false,
this.$auth.currentUser.uid, this.$auth.currentUser.uid,
this.$store.state.user.displayName, this.$store.state.user.displayName,
[], [],
@@ -252,7 +254,11 @@ export default {
// Update the user's given answers for the current game // Update the user's given answers for the current game
const gameRef = doc(this.$db, `kurse/${this.courseID}/spiele/${this.game.id}`) const gameRef = doc(this.$db, `kurse/${this.courseID}/spiele/${this.game.id}`)
batch.update(gameRef, { batch.update(gameRef, {
[`spieler${this.playerNumber}antworten`]: arrayUnion({ frage: this.selectedQuestion.id, antwort: this.submittedAnswer }) [`spieler${this.playerNumber}antworten`]: arrayUnion({
frage: this.selectedQuestion.id,
antwort: this.submittedAnswer,
richtig: this.answerCorrect
})
}) })
// Increment the number of correct/incorrect answers given by the user by 1 // Increment the number of correct/incorrect answers given by the user by 1
@@ -265,7 +271,11 @@ export default {
// Commit the batch // Commit the batch
batch.commit().then((empty) => { batch.commit().then((empty) => {
// Batch execution was successful // Batch execution was successful
this.game[`player${this.playerNumber}answers`].push({ frage: this.selectedQuestion.id, antwort: this.submittedAnswer }) this.game[`player${this.playerNumber}answers`].push({
frage: this.selectedQuestion.id,
antwort: this.submittedAnswer,
richtig: this.answerCorrect
})
}).catch((error) => { }).catch((error) => {
// Batch execution failed; display error message // Batch execution failed; display error message
this.$toast({content: error, color: 'error'}) this.$toast({content: error, color: 'error'})
@@ -319,6 +329,7 @@ export default {
}) })
}, },
completeGame () { completeGame () {
this.game.completed = true
const result = this.game.getResult() const result = this.game.getResult()
// Figure out which player won and which player lost, or if the game was a tie // Figure out which player won and which player lost, or if the game was a tie
@@ -345,6 +356,10 @@ export default {
const refPl2 = doc(this.$db, `benutzer/${this.game.player2id}`) const refPl2 = doc(this.$db, `benutzer/${this.game.player2id}`)
batch.update(refPl2, { [`spiele.${this.courseID}.${updateFieldPl2}`]: increment(1) }) batch.update(refPl2, { [`spiele.${this.courseID}.${updateFieldPl2}`]: increment(1) })
// Set the game's "completed" field to true
const refGame = doc(this.$db, `kurse/${this.courseID}/spiele/${this.game.id}`)
batch.update(refGame, { abgeschlossen: true })
// Commit the batch // Commit the batch
batch.commit().catch((error) => { batch.commit().catch((error) => {
// Batch execution failed; display error message // Batch execution failed; display error message

View File

@@ -1,31 +1,24 @@
export class Game { export class Game {
constructor (id, questions, created, player1id, player1name, player1answers, player2id, player2name, player2answers) { constructor (id, questions, created, completed, player1id, player1name, player1answers, player2id, player2name, player2answers) {
this.id = id this.id = id
this.questionIds = questions this.questionIds = questions
this.created = created this.created = created
this.completed = completed
this.player1id = player1id this.player1id = player1id
this.player1name = player1name this.player1name = player1name
this.player1answers = player1answers this.player1answers = player1answers
this.player2id = player2id this.player2id = player2id
this.player2name = player2name this.player2name = player2name
this.player2answers = player2answers this.player2answers = player2answers
this.playerIds = []
if (this.player1id) this.playerIds.push(this.player1id)
if (this.player2id) this.playerIds.push(this.player2id)
} }
getResult () { getResult () {
if (!this.questions) return {} const correctAnswersPl1 = this.player1answers.filter(a => a.richtig).length
const qs = this.questions const correctAnswersPl2 = this.player2answers.filter(a => a.richtig).length
function countCorrectAnswers(answersGiven) {
let i = 0
answersGiven.forEach(a => {
const q = qs.find(e => e.id === a.frage)
if (q && a.antwort === q.correctAnswer) i++
})
return i
}
const correctAnswersPl1 = countCorrectAnswers(this.player1answers)
const correctAnswersPl2 = countCorrectAnswers(this.player2answers)
return { return {
winner: correctAnswersPl1 > correctAnswersPl2 ? 1 : 2, winner: correctAnswersPl1 > correctAnswersPl2 ? 1 : 2,
@@ -43,18 +36,20 @@ export const GameConverter = {
return { return {
fragen: game.questionIds, fragen: game.questionIds,
erstellt: game.created, erstellt: game.created,
abgeschlossen: game.completed,
spieler1id: game.player1id, spieler1id: game.player1id,
spieler1name: game.player1name, spieler1name: game.player1name,
spieler1antworten: game.player1answers, spieler1antworten: game.player1answers,
spieler2id: game.player2id, spieler2id: game.player2id,
spieler2name: game.player2name, spieler2name: game.player2name,
spieler2antworten: game.player2answers spieler2antworten: game.player2answers,
spielerIds: game.playerIds
} }
}, },
fromFirestore: (snapshot, options) => { fromFirestore: (snapshot, options) => {
const data = snapshot.data(options) const data = snapshot.data(options)
return new Game( return new Game(
snapshot.id, data.fragen, data.erstellt, snapshot.id, data.fragen, data.erstellt, data.abgeschlossen,
data.spieler1id, data.spieler1name, data.spieler1antworten, data.spieler1id, data.spieler1name, data.spieler1antworten,
data.spieler2id, data.spieler2name, data.spieler2antworten data.spieler2id, data.spieler2name, data.spieler2antworten
) )