0

在我的第一个 Objective C 项目中,我正在处理游戏 Mastermind 的一般形式的代码。我目前有一个程序可以让计算机生成六种随机“颜色”中的四种计算机,然后打印一个序列(一个“.”代表每个正确的猜测,一个“o”代表每个错误的猜测)。

#import "Gameplay.h"
int main(int argc, const char * argv[])
{

@autoreleasepool {
    Gameplay * gp = [[Gameplay alloc] init];

}
return 0;
}


 #import <Foundation/Foundation.h>

 @interface Gameplay : NSObject
 -(NSMutableArray *) board;

 @end


@implementation Gameplay
- (id)init {
self = [super init];
if (self)
{
    [self board];
}
return self;
}
-(NSMutableArray *) board{
NSMutableArray *colors = [NSMutableArray arrayWithObjects:@"r",@"b",@"y",@"g",@"o",@"p", nil];

NSMutableArray *choose = [[NSMutableArray alloc] initWithCapacity:4];

for (int i = 0; i < 4; i++) {
    int randomize = arc4random()%[colors count];
    NSString *turn = [[NSString alloc] initWithString:[colors objectAtIndex: randomize]];
    [choose addObject: turn];
    [colors removeObjectAtIndex: randomize];
}
NSFileHandle(

for(int i = 0;i < 4;i++){
    NSLog(@"%@",[choose objectAtIndex:i]);
}
return choose;
}
@end



#import "Gameplay.h"
int main(int argc,
@autoreleasepool {
    Gameplay * gp = [[Gameplay alloc] init];

}
return 0;
}


#import <Foundation/Foundation.h>

@interface Gameplay : NSObject
-(NSMutableArray *) board;

@end


 @implementation Gameplay
 - (id)init {
self = [super init];
if (self)
{
    [self board];
}
return self;
}
-(NSMutableArray *) board{
NSMutableArray *colors = [NSMutableArray arrayWithObjects:@"r",@"b",@"y",@"g",@"o",@"p", nil];

NSMutableArray *choose = [[NSMutableArray alloc] initWithCapacity:4];

for (int i = 0; i < 4; i++) {
    int randomize = arc4random()%[colors count];
    NSString *turn = [[NSString alloc] initWithString:[colors objectAtIndex: randomize]];
    [choose addObject: turn];
    [colors removeObjectAtIndex: randomize];
}
NSFileHandle(

for(int i = 0;i < 4;i++){
    NSLog(@"%@",[choose objectAtIndex:i]);
}
return choose;
}
@end
4

1 回答 1

-1

我没有得到你想要达到的目标。但是我希望您建议随机排列您的可变数组,请尝试如下所示,每当您执行代码时,您的可变数组的顺序将随机更改,因此您可以在此基础上获取值并相应地编写检查器根据用户输入。:--

NSMutableArray *mutArr=[NSMutableArray arrayWithObjects:@"red",@"green",@"blue",@"white",nil];
int i=0;
for (i=0; i<[mutArr count]; i++)
{
NSUInteger rand= (arc4random() %[mutArr count]);
    [mutArr exchangeObjectAtIndex:i withObjectAtIndex:rand];
    NSLog(@"%@",mutArr);
}
于 2013-10-04T06:13:36.907 回答