創建了一個數組,其中包括紅黃綠(321)三個顏色,根據用戶點擊隨機選擇一個數字,然後在屏幕上顯示對應的顏色,然後系統選擇最後輸入的顏色,但是我寫的代碼沒有實現這樣的功能:
-(void)CreateEnemy:(ccTime)dt{
CCSprite *Enemy;
int a;
if (colorArray != nil) {
a = arc4random()% [colorArray count];
}
int y = [[colorArray objectAtIndex:a] integerValue];
if (y == 1) {
Enemy = [CCSprite spriteWithFile:@"GreenBall.png"];
int x = arc4random()%320;
Enemy.position = ccp(x, 530);
id action = [CCMoveTo actionWithDuration:3 position:ccp(x, -30)];
[Enemy runAction:[CCSequence actions:action, [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)], nil]];
[enemyArray addObject:Enemy];
[self addChild:Enemy z:2 tag:1];
NSLog(@"Green Enemy Attack!!");
}
else if (y == 2) {
Enemy = [CCSprite spriteWithFile:@"YellowBall.png"];
int x = arc4random()%320;
Enemy.position = ccp(x, 530);
id action = [CCMoveTo actionWithDuration:3 position:ccp(x, -30)];
[Enemy runAction:[CCSequence actions:action, [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)], nil]];
[enemyArray addObject:Enemy];
[self addChild:Enemy z:2 tag:1];
NSLog(@"Yellow Enemy Attack!!");
}
else if (y == 3) {
Enemy = [CCSprite spriteWithFile:@"RedBall.png"];
int x = arc4random()%320;
Enemy.position = ccp(x, 530);
id action = [CCMoveTo actionWithDuration:3 position:ccp(x, -30)];
[Enemy runAction:[CCSequence actions:action, [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)], nil]];
[enemyArray addObject:Enemy];
[self addChild:Enemy z:2 tag:1];
NSLog(@"Red Enemy Attack!!");
}
}
其中Y是一個隨機選擇數。
在這段代碼中
if (colorArray != nil) {
a = arc4random()% [colorArray count];
}
int y = [[colorArray objectAtIndex:a] integerValue];
[colorArray count]
很有可能沒有你需要的值, 因此arc4random
只能返回0 (或一組有限的值).
如果你在計算a
的值之前加上一個 NSLog跟蹤, 就可以估計[colorArray count]
的值了.