行。我在这里疯了。我有一个for循环,但它应该停止。
我正在创建一个骰子游戏,并且骰子的数量经常变化所以我只有一个for循环生成骰子,但是在任何给定的掷骰都应该有很多骰子。这是循环:
for (int x = 0; x < numDice; x++) {
int dieNum = (arc4random() % 6) + 1;
SKSpriteNode *die;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
die = [SKSpriteNode spriteNodeWithImageNamed:[NSString stringWithFormat:@"dice-%i", dieNum]];
} else if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
die = [SKSpriteNode spriteNodeWithImageNamed:[NSString stringWithFormat:@"dice-%i_ipad", dieNum]];
}
die.name = @"die";
die.userData = [NSMutableDictionary dictionaryWithObject:@"YES" forKey:@"Rollable"];
[die.userData setObject:[NSString stringWithFormat:@"%i",dieNum] forKey:@"Die Number"];
[die.userData setObject:[NSString stringWithFormat:@"%i", rollNum] forKey:@"Roll Number"];
[die.userData setObject:@"YES" forKey:@"Movable"];
die.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:die.size];
die.physicsBody.affectedByGravity = NO;
die.physicsBody.categoryBitMask = dieCategory;
die.physicsBody.collisionBitMask = dieCategory;
int rotation = (arc4random() % 360) + 1;
die.zRotation = radians(rotation);
int x = (arc4random() % (int)self.frame.size.width) + (die.size.width / sinf(90.0));
int y = (arc4random() % (int)self.frame.size.height) + (die.size.height / sinf(90.0));
if (x < 1.75 * (die.size.width / sinf(90.0))) {
x = 1.75 * (die.size.width / sinf(90.0));
}
if (y < (die.size.height / sinf(90.0))) {
y = (die.size.height / sinf(90.0));
}
if (x > self.frame.size.width - (die.size.width / sinf(90.0))) {
x = self.frame.size.width - (die.size.width / sinf(90.0));
}
if (y > self.frame.size.height - (die.size.height / sinf(90.0))) {
y = self.frame.size.height - (die.size.height / sinf(90.0));
}
die.position = CGPointMake(x, y);
[self addChild:die];
}
现在我有一个NSLog在执行循环之前输出numDice变量,并且numDice变量在我的每一个测试中都是正确的。但是出于某种原因,for循环在某个测试期间产生了一个随机数量的额外骰子。所以我把NSLog输出x值并看到一些有趣的东西。在循环之后,日志会说出这样的话:
2013-12-04 19:50:03.334 DiceMania[21611:60b] numDice: 6
2013-12-04 19:50:03.338 DiceMania[21611:60b] x: 0
2013-12-04 19:50:03.338 DiceMania[21611:60b] x: 1
2013-12-04 19:50:03.341 DiceMania[21611:60b] x: 2
2013-12-04 19:50:03.346 DiceMania[21611:60b] x: 3
2013-12-04 19:50:03.350 DiceMania[21611:60b] x: 4
2013-12-04 19:50:03.352 DiceMania[21611:60b] x: 5
2013-12-04 19:50:03.359 DiceMania[21611:60b] x: 0
2013-12-04 19:50:03.363 DiceMania[21611:60b] x: 1
为什么地球上的循环将x重置为0然后再进行一次随机数的迭代? (我注意到x已经超过了预期的1到6次迭代。
答案 0 :(得分:1)
您正在使用x
迭代循环,并将其用于循环的内容。拆分变量,使它们不会互相干扰,你应该没事。