在Objective-C中猜猜数字游戏的问题

时间:2012-07-12 18:28:05

标签: objective-c

我是Objective-C的新手,目前我正在为Iphone编写一个Guess the Number单视图应用程序。 “新游戏”按钮目前运行此代码。

- (IBAction)newGame:(id)sender {

NSString *guessANumber = @"Guess a number between 1 and 25!";
[output setText:guessANumber];
}

,随机方法目前看起来像这样

-(int)Random {
int num;

num=(arc4random() % ((unsigned)25 + 1));
while (num == 0) {
    if (num == 0)
    {
    num=(arc4random() % ((unsigned)25 + 1));
    }
}    

return num;
}

目前玩家提交猜测的方法是

- (IBAction)submitGuess:(id)sender {

int num = [self num];

for (int x = 1; x<=3;x++)
{

    if([textField.text intValue] > num)
        output.text=@"Too high.";
    else if([textField.text intValue] < num)
        output.text=@"Too low.";
    else if ([textField.text intValue] == num)
        output.text=@"You got it!";
    else 
        output.text= @"You lose. The number was %i.", num;


}

目前尚未实施转弯系统。

我是Objective-C的新手,我不知道如何将随机数输入到按下提交按钮时发生的操作。

抱歉新手问题。

编辑:感谢您的帮助,它现在正在运作。

1 个答案:

答案 0 :(得分:1)

您可以将num作为视图控制器的实例变量。类似的东西:

@interface MyViewController : UIViewController
{
   int num;
}

然后你的提交方法看起来像这样

- (IBAction)submitGuess:(id)sender {
    // access your random value here and do something with it.
    [self num];
}

这是一个关于学习目标的好pdf-c。 https://developer.apple.com/library/mac/documentation/cocoa/conceptual/objectivec/objc.pdf

此外,您可能希望更改生成随机数的方式。看看这个:Generating random numbers in Objective-C