Reputation: 29
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
Reputation: 5155
There are a few issues with your code:
rockPaperScissors
array has only 3 elements (you should use your array's length
).Math.floor
).rockPaperScissors
in your state, although it never changes (only use the state for storing data that changes over time and affects the view).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