You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

猜数字游戏开发求助:固定随机数及实现猜测次数统计

Fixing Your Number Guessing Game Issues

Hey there! I see exactly what's tripping you up—let's fix those two problems so your game works as expected.

Problem 1: Random Number Resets Every Time You Click Confirm

Right now, you're generating a new random number inside the confirm function every time the button is clicked. That means the target number changes with every guess, making it impossible to ever guess correctly! We need to generate the target number once when the component loads, not on each button press.

Problem 2: Guess Count Isn't Tracking

Your count variable is declared locally inside the confirm function, so it gets reset to 0 every time the function runs. We need to store this count in a component state to keep track of it across renders.

Here's the Fixed Code

import { useState, Alert, View, Text, TextInput, Button } from 'react-native'; // Ensure these imports are present

const Home = () => { 
  const [enteredValue, setEnteredValue] = useState(""); 
  const [confirmed, setConfirmed] = useState(false); 
  const [selectedNumber, setSelectedNumber] = useState(); 
  // New states for target number and guess tracking
  const [targetNumber, setTargetNumber] = useState(Math.floor(Math.random() * 100) + 1);
  const [guessCount, setGuessCount] = useState(0);

  const input = inputText => { 
    setEnteredValue(inputText.replace(/[^0-9]/g, "")); 
  }; 

  const reset = () => { 
    setEnteredValue(""); 
    setConfirmed(false); 
    // Reset target number and count for a new game
    setTargetNumber(Math.floor(Math.random() * 100) + 1);
    setGuessCount(0);
  }; 

  const confirm = () => { 
    // Early exit if input is empty (don't count this as a guess)
    if (!enteredValue) {
      Alert.alert("Please Enter a Number");
      return;
    }

    const chosenNum = parseInt(enteredValue); 
    setConfirmed(true); 
    setSelectedNumber(chosenNum); 
    setEnteredValue(""); 

    // Increment count for valid guesses
    setGuessCount(prevCount => prevCount + 1);

    // Compare with the fixed target number
    if (chosenNum > targetNumber) { 
      Alert.alert("Guess Lower"); 
    } else if (chosenNum < targetNumber) { 
      Alert.alert("Guess Higher"); 
    } else { 
      Alert.alert(`You Guessed Correctly! It took you ${guessCount + 1} tries.`); 
    } 
  }; 

  let confirmedOutput; 
  if (confirmed) { 
    confirmedOutput = ( 
      <View> 
        <Text style={styles.output}>Chosen Number: {selectedNumber}</Text> 
        <Text>Tries: {guessCount}</Text> 
      </View> 
    ); 
  }

  // Basic JSX structure (adjust to match your existing UI)
  return (
    <View style={{ padding: 20 }}>
      <TextInput
        value={enteredValue}
        onChangeText={input}
        keyboardType="numeric"
        placeholder="Enter a number 1-100"
      />
      <Button title="Confirm" onPress={confirm} />
      <Button title="Reset" onPress={reset} />
      {confirmedOutput}
    </View>
  );
};

// Example styles (match your existing styling)
const styles = {
  output: {
    fontSize: 18,
    marginVertical: 10,
  },
};

export default Home;

Key Changes Explained

  • Target Number State: We moved the random number generation into a useState initializer, so it only runs once when the component first loads. When the user resets the game, we generate a fresh target number.
  • Guess Count State: guessCount is now a state variable, so its value persists across renders. We use the functional update form (prevCount => prevCount + 1) to ensure we're always incrementing the latest count value.
  • Input Validation: We moved the empty input check to the start of the confirm function and added a return to stop execution if the input is empty—this prevents counting empty submissions as valid guesses.
  • Win Message: Updated the success alert to show how many tries it took, using guessCount + 1 (since we increment the count after processing the guess, the current count is one less than the total when they win).
  • Reset Function: Added resets for targetNumber and guessCount so starting a new game gives a fresh number and clean count.

内容的提问来源于stack exchange,提问作者Swap01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 15:22:51