CM3050 Lab 4604: Alert Quiz
import { StatusBar } from 'expo-status-bar';
import { Alert, StyleSheet, Text, View, Button } from 'react-native';
import {useState} from 'react';
let TRIVIA = [
{
"question":"A polar bear's hair is transparent, not white.",
"answers":[
"True",
"False"
],
"correct":0
},
{
"question":"What is Sweden's capital city?",
"answers":[
"Malmö",
"Stockholm"
],
"correct":1
}
]
export default function App() {
const [score, setScore] = useState(-1);
const startQuiz = (index, internalScore) => {
if(index === 0) {
setScore(0);
}
let question = TRIVIA[index];
let buttons = question.answers.map((answer, i) => (
{"text": answer,
onPress: () => {
if (i === question.correct) {
internalScore ++;
setScore(internalScore)
}
if (index < TRIVIA.length - 1) {
startQuiz(index + 1, internalScore);
} else {
Alert.alert(
`Well done!`,
`You scored ${internalScore}`,
[
{
"text": "Start again",
onPress: () => setScore(-1),
"style": "cancel"
}
]
);
}
}}));
Alert.alert(
`Question ${index+1}`,
`${question.question}`,
buttons
);
}
if (score == -1) {
return (
<View style={styles.container}>
<Text style={styles.welcomeHeader}>Trivia Quiz</Text>
<Text style={styles.welcomeMessage}>Are you ready for some trivia?</Text>
<Button title="I'm ready" onPress={() => startQuiz(0,0)} />
<StatusBar style="auto" />
</View>
);
} else {
return (
<View style={styles.gameContainer}>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
welcomeHeader: {
fontWeight: "bold",
fontSize: 40,
fontFamily: "Helvetica"
},
welcomeMessage: {
marginTop: "2%",
marginBottom: "2%"
},
gameContainer: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "flex-end",
marginBottom: 100
}
});