A
A
AndRey8332020-06-17 16:45:18
JavaScript
AndRey833, 2020-06-17 16:45:18

How to choose one of two values ​​with a given probability?

I'm making a toy based on tic-tac-toe based on react. The playing field is 16 squares. You press the button and the square gets the color. Black or red. If there are 2 reds nearby, you lose. Something like this.

Instead of 0 and X, I want the block you click to turn red or black, with a 70 percent chance of black and a 30 percent chance of red.

Here is the code snippet responsible for this:

clickHandler = event => {

// data - номер квадрата по которому кликают
let data = event.target.getAttribute('data');
let currentScuares = this.state.squares;
console.log(currentScuares);
 

 //проверка
  if (currentScuares[data] === null){
  // выбор что добавлять х или о по состоянию счетчика
  currentScuares[data] = (this.state.count % 2 === 0) ? 'X':'O';
  // увеличение счетчика
  this.setState({ count: this.state.count + 1});
  // текущиц квадратик
  this.setState({ scuares:currentScuares});
  }
  else {
    alert ('Так нельзя');
  }
}


Here is the github link

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-06-17
@AndRey833

Get a random value with Math.random, depending on whether it is lower than your probability, take one or the other value:

class App extends React.Component {
  state = {
    cells: Array(16).fill(null),
    probability: 0.7,
  }

  onClick = e => {
    const index = +e.target.dataset.index;
    this.setState(({ cells, probability }) => ({
      cells: cells.map((n, i) => i === index && !n
        ? (Math.random() < probability ? 'black' : 'red')
        : n
      ),
    }));
  }

  render() {
    return (
      <div className="ColorS">
        {this.state.cells.map((n, i) => (
          <div
            className="ColorS-grid"
            style={n && { background: n }}
            data-index={i}
            onClick={this.onClick}
          />
        ))}
      </div>
    );
  }
}

P
Peter, 2020-06-17
@petermzg

Take the current time and the last digit from seconds, if this digit is less than three then red, otherwise black.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question