0

So I have a very simple game going here..., right now the AI is nearly perfect and I want it to make mistakes every now and then. The only way the player can win is if I slow the computer down to a mind numbingly easy level.

My logic is having a switch case statement like this:

int number = randomNumber

case 1:
computer moves the complete opposite way its supposed to
case 2:
computer moves the correct way

How can I have it select case 2 68% (random percentage, just an example) of the time, but still allow for some chance to make the computer fail? Is a switch case the right way to go? This way the difficulty and speed can stay high but the player can still win when the computer makes a mistake.

I'm on the iPhone. If there's a better/different way, I'm open to it.

nullArray
  • 145
  • 1
  • 1
  • 11
  • You probably ant to have some coefficient or other way to "scale" up based on user level/difficulty level – Tim Oct 13 '09 at 16:21
  • the person who can answer this question with something other than a qausi-random method should get a nobel prize. – pxl Oct 13 '09 at 18:27

3 Answers3

1

Generating Random Numbers in Objective-C

int randNumber = 1 + rand() % 100;

if( randNumber < 68 )
{
//68% path
}
else
{
//32% path
}
Community
  • 1
  • 1
Stefan Kendall
  • 66,414
  • 68
  • 253
  • 406
0
int randomNumber = GeneraRandomNumberBetweenZeroAndHundred()

if (randomNumber < 68) {
computer moves the complete opposite way its supposed to
} else {
computer moves the correct way
}
devoured elysium
  • 101,373
  • 131
  • 340
  • 557
0

Many PRNGs will offer a random number in the range [0,1). You can use an if-statement instead:

   n = randomFromZeroToOne()

   if n <= 0.68:
        PlaySmart()
   else: 
        PlayStupid()

If you're going to generate an integer from 1 to N, instead of a float, beware of modulo bias in your results.

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
  • I would expect with such a small number as 100, modulo bias would be almost unnoticeable. Usually it's only a factor when you get into much larger numbers. – rmeador Oct 13 '09 at 16:57
  • Yes, it would likely be unnoticeable with a value this small, in an application like a casual game; however, it is an issue that many programmers do not know about, so bringing that up might be helpful to someone else who comes across this question. – Mark Rushakoff Oct 13 '09 at 17:02