gpt4 book ai didi

ios - for循环疯狂

转载 作者:行者123 更新时间:2023-11-29 12:58:28 26 4
gpt4 key购买 nike

好的。我在这里疯了。我有一个 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 次迭代。

最佳答案

您正在使用 x 迭代循环,并将其用于循环的主体。拆分变量,使它们不会相互干扰,这样应该没问题。

关于ios - for循环疯狂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20390026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com