Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from 'react';
- import { StyleSheet, Text, View, Button, Alert, TextInput, Image, AsyncStorage } from 'react-native';
- export default class App extends React.Component {
- constructor(props)
- {
- super(props);
- this.state = {number: 0, guess: '', text: '', counter: 0, highScore: 0}
- }
- componentDidMount()
- {
- // Call function to set initial high score here on load
- this.rerun()
- }
- // When game starts/is complete re-initialize the number to guess
- rerun = () =>
- {
- const current = Math.floor(Math.random() * 100) + 1;
- this.setState({
- number: current,
- counter: 0
- })
- }
- guess = () =>
- {
- const currentGuess = this.state.guess;
- const theNumber = this.state.number;
- if (theNumber > currentGuess)
- {
- this.setState({
- text: "Guess too low!",
- counter: (this.state.counter + 1)
- })
- }
- else if (theNumber < currentGuess)
- {
- this.setState({
- text: "Guess too high!",
- counter: (this.state.counter + 1)
- })
- }
- else
- {
- const totalTries = (this.state.counter + 1);
- let highScoreString = '';
- Alert.alert("Guess correct! It took you " + totalTries + " tries!");
- if(this.state.highScore > totalTries || this.state.highScore === 0)
- {
- this.setState({
- text: ""
- })
- highScoreString = String(totalTries)
- // Call Async function to save highScore as string key : value pair
- AsyncStorage.setItem('highScore', highScoreString)
- }
- else
- {
- this.setState({
- text: ""
- })
- }
- // Get data from AsyncStorage and set it to the state
- this.returnData()
- // Rerun game
- this.rerun()
- }
- }
- // Call data from async storage
- returnData = async () =>
- {
- try
- {
- let highScore = await AsyncStorage.getItem('highScore')
- console.log(highScore)
- this.setState({
- highScore: parseInt(highScore)
- })
- }
- catch(error)
- {
- Alert.alert("Whoops! something broke!")
- }
- }
- render() {
- return (
- <View style={styles.container}>
- <Text>Guess a number between 1-100!</Text>
- <Text id="text">{this.state.text}</Text>
- <TextInput style={{width: 200, borderColor: 'grey', borderWidth: 1}} onChangeText={(guess) => this.setState({guess})} keyboardType='numeric' value={this.state.guess}/>
- <Button onPress={this.guess} title="Guess "/>
- <Text>High Score: {this.state.highScore} </Text>
- </View>
- );
- }
- }
- const styles = StyleSheet.create({
- container: {
- flex: 1,
- backgroundColor: 'lightblue',
- alignItems: 'center',
- justifyContent: 'center',
- },
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement