Mitzko
Mitzko

Reputation: 29

React "Rock Paper Scissors" Game Not Working

I'm making a Rock Paper Scissors game. I have tested certain parts and they seem to work separately but not all together.

I don't know what to try but I've tried different ways to do the number generator.

constructor() {
    super();
    this.state = {
        rockPaperScissorsComputer: ['rock','paper','scissors'],
        random: null
    };
    this.handleClick = this.handleClick.bind(this);
}

handleClick() {
    const min = 1;
    const max = 100;
    const random = min + (Math.random() * (max - min));
    this.setState({ random })
}

render() {
    return (
        <div>
            <button value="Click me!" onClick={this.handleClick}>Click me</button>
            <h1> {this.state.rockPaperScissorsComputer[this.state.random]} </h1>
        </div>
    );
}

It should display rock/paper/scissors every time I click the button but nothing is displayed.

Upvotes: 0

Views: 117

Answers (1)

Yoav Kadosh
Yoav Kadosh

Reputation: 5155

There are a few issues with your code:

  1. You're generating a random number between 0 and 100, while your rockPaperScissors array has only 3 elements (you should use your array's length).
  2. You're generating a random number that may be a decimal, but array indexes should be whole numbers (you should use Math.floor).
  3. You're storing the rockPaperScissors in your state, although it never changes (only use the state for storing data that changes over time and affects the view).
  4. Using a class component for this is an overkill (you can convert it to a functional component with hooks and greatly reduce your code).

To generate a random whole number between min & max, you can do:

const index = Math.floor(Math.random() * (max - min)) + min;

So your final code should look like this:

const RockPaperScissors = () => {
  const [pick, setPick] = useState(null);

  const handleOnClick = useCallback(() => {
    const pool = ['rock','paper','scissors'];
    setPick(pool[Math.floor(Math.random() * pool.length)]);
  }, [setPick]);

  return (
    <div>
      <button value="Click me!" onClick={handleOnClick}>Click me</button>
      <h1>{pick}</h1>
    </div>
  );
};

Upvotes: 1

Related Questions