views:

190

answers:

3

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.

+1  A: 

Generating Random Numbers in Objective-C

int randNumber = 1 + rand() % 100;

if( randNumber < 68 )
{
//68% path
}
else
{
//32% path
}
Stefan Kendall
That's actually wrong.
devoured elysium
This isn't perfect, of course, as rand() % 100 does not create a perfect distribution of values due to behavior near the upper end of INT.
Stefan Kendall
How is it wrong?
Stefan Kendall
the first path is the 32% path.
devoured elysium
I do believe you're mistaken.
Stefan Kendall
i am. and stoned. sorry, now i realise your example is equal to mine.
devoured elysium
Worked great, thanks. Or seems to....,
nullArray
Like mentioned below, there's a tiny bit of error related to using modulus, but a user wouldn't notice, and you probably wouldn't either. Don't use this method for your online gambling sites, at any rate :P.
Stefan Kendall
A: 
int randomNumber = GeneraRandomNumberBetweenZeroAndHundred()

if (randomNumber < 68) {
computer moves the complete opposite way its supposed to
} else {
computer moves the correct way
}
devoured elysium
A: 

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
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
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
lol i like your function names... playSmart/playStupid
pxl