How to make the computer choose between two Characters

Asked

Viewed 73 times

0

Guys, I’m doing an old game in winforms in C#, however, I have a problem, is the following with me pressing the first button I want the computer to choose between "O" or "X", I tried to use the class Andom, but I found some problems, because I am working with string.

  • 2

    Put the code you tried there in the question.

  • Joao Victor, please answer the question, thank you.

1 answer

4

Use Random, and test whether it is even or odd. And assign a matching Character, Ex: "X" when even, and "O" when odd.

Random from 0 to 99, 100 possibilities, equal probability.

Random r = new Random();
string Jogo =  r.Next(0, 99) % 2 ==0 ? "X" : "O";

Surely you should only do that on the first move.

  • 2

    It would not be easier to generate a random number between 0 and 1 no?

  • 1

    could yes, it was just an option of mine

  • Joao Victor, please mark as reply, Thank you.

  • @Francisco, the way you thought is also valid, you can put as a second option pro AP. Both solve the issue, and the AP still has 2 examples to choose the one you find most appropriate. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.