Untitled
user_9363972
javascript
a month ago
3.4 kB
2
Indexable
Never
import React, { useEffect, useState } from "react"; import { Image, ScrollView, Text, TextInput, TouchableOpacity, View, } from "react-native"; import { countryList, objectImageList, objectNameList } from "../data/Data"; function GuessTheCountry(props: any) { const [answer, setAnswer] = useState(""); const [index, setIndex] = useState<number>(); const [result, setResult] = useState<boolean>(false); const [life, setLife] = useState(3); const [score, setScore] = useState(0); const randomIndex = () => { const rnd = Math.floor(Math.random() * objectImageList.length); setIndex(rnd); }; const checkAnswer = () => { if (answer.toLowerCase() === countryList[index].toLowerCase()) { setResult(true); setScore(score + 10); } else { setResult(false); setLife(life - 1); } setTimeout(() => { setResult(false); setAnswer(""); randomIndex(); }, 500); }; useEffect(() => { if (life <= 0) { props.navigation.navigate("GameOver"); } if (score >= 30) { props.navigation.navigate("Win"); } }, [life, score]); useEffect(() => { props.navigation.addListener("focus", () => { randomIndex(); setScore(0); setLife(3); }); }, []); return ( <ScrollView contentContainerStyle={{ flexGrow: 1 }}> <View style={{ flex: 1, alignItems: "center", justifyContent: "center", }} > <Text style={{ textDecorationLine: "underline", fontSize: 28, fontFamily: "serif", marginBottom: 16, }} > Guess The Country </Text> <Image style={{ width: 250, height: 250, borderRadius: 10, }} source={{ uri: objectImageList[index] }} /> <View style={{ margin: 8, backgroundColor: "lavender", padding: 4, borderWidth: 1, }} > <Text style={{ fontSize: 18 }}>{objectNameList[index]}</Text> </View> <View style={{ flexDirection: "row", margin: 8, }} > <TextInput style={{ borderWidth: 1, width: "50%", }} value={answer} onChangeText={(text) => { setAnswer(text); }} placeholder="Write your answer" /> <TouchableOpacity style={{ borderWidth: 1, alignItems: "center", justifyContent: "center", borderRadius: 10, padding: 8, marginLeft: 8, marginBottom: 8, marginTop: 8, backgroundColor: "skyblue", }} onPress={() => checkAnswer()} > <Text style={{ fontSize: 18 }}>Submit</Text> </TouchableOpacity> </View> <Text>Result : {result ? "Correct" : "Wrong"}</Text> <Text>Score : {score}</Text> <Text>Life : {life}</Text> </View> </ScrollView> ); } export default GuessTheCountry;
Leave a Comment