I'm attempting to build a Treasure Hunting game that is a 3x3 grid of clickable squares. When clicked, the revealed value can either be a "tree" or "treasure. There is only one "treasure".
The part I'm struggling with (at this point) is assigning my squares, a random element of the array. I have successfully altered my original array of 9 items to a random array of "tree"s and one "treasure". But how do I assign those array elements, that is shuffled each time the shuffle function is called, to random squares in my grid?
I attempted to map through the array of trees and my single treasure but failed to find a way to randomly assign those values to random squares as I want the game to have treasure in a different location most of the time.
I have pasted my full code below for reference.
Board.js
import React, { Component } from 'react';
import Square from './Square'
class Board extends Component {
constructor(props){
super(props)
this.state = {
spaces: [1, 2, 3, 4, 5, 6, 7, 8, 9],
boxOne: "?",
boxTwo: "?",
boxThree: "?",
boxFour: "?",
boxFive: "?",
boxSix: "?",
boxSeven: "?",
boxEight: "?",
boxNine: "?"
}
}
shuffle = (arr) => {
for(let i = arr.length - 1; i > 0; i--) {
const randomNum = Math.floor(Math.random() * (i + 1))
[arr[i], arr[randomNum] = arr[randomNum], arr[i]]
}
let newArr = []
arr.map(x => {
if (x === 7) {
newArr.push("Treasure")
} else {
newArr.push("Tree")
}
})
this.setState({spaces: newArr})
}
render() {
return (
<div className = "container">
<div className = "board">
<Square clickEvent={this.shuffle} boxOne={this.state.boxOne}
boxTwo={this.state.boxTwo}
boxThree={this.state.boxThree}
boxFour={this.state.boxFour}
boxFive={this.state.boxFive}
boxSix={this.state.boxSix}
boxSeven={this.state.boxSeven}
boxEight={this.state.boxEight}
boxNine={this.state.boxNine}
newSpaces={this.state.spaces}
/>
</div>
</div>
);
}
}
export default Board;
Square.js
import React, { Component } from 'react';
class Square extends Component {
render() {
return(
<div>
<div className = "box" onClick = {this.props.shuffle} >{this.props.boxOne}</div>
<div className = "box" onClick = {this.props.shuffle} >{this.props.boxTwo}</div>
<div className = "box" onClick = {this.props.shuffle} >{this.props.boxThree}</div>
<div className = "box" onClick = {this.props.shuffle} >{this.props.boxFour}</div>
<div className = "box" onClick = {this.props.shuffle} >{this.props.boxFive}</div>
<div className = "box" onClick = {this.props.shuffle} >{this.props.boxSix}</div>
<div className = "box" onClick = {this.props.shuffle} >{this.props.boxSeven}</div>
<div className = "box" onClick = {this.props.shuffle} >{this.props.boxEight}</div>
<div className = "box" onClick = {this.props.shuffle} >{this.props.boxNine}</div>
</div>
)
}
}
export default Square