游戏结束场景星级判断代码中else if条件未执行问题咨询
Hey there! I can spot exactly why your 3-star condition never runs—your if-else order is backwards. Let me break it down:
When gameScore is greater than 1000, it's also automatically greater than 500. Since your first condition checks gameScore > 500 first, that block will always trigger for scores over 500 (including those over 1000), and the else-if for 3 stars will never get evaluated.
Here's the corrected code:
var starImage = SKSpriteNode() if gameScore > 1000 { starImage = SKSpriteNode(imageNamed: "3_stars") print("You achieved 3 Stars") } else if gameScore > 500 { starImage = SKSpriteNode(imageNamed: "2_stars") print("You achieved 2 Stars") } else { starImage = SKSpriteNode(imageNamed: "1_star") print("You achieved 1 Star") } // Rest of your code for starImage...
A quick best practice tip:
To make your code more maintainable and readable, consider defining your score thresholds as constants at the top of your class or scene. This way, you can easily adjust them later without digging through conditionals:
let threeStarThreshold = 1000 let twoStarThreshold = 500 var starImage = SKSpriteNode() if gameScore > threeStarThreshold { starImage = SKSpriteNode(imageNamed: "3_stars") print("You achieved 3 Stars") } else if gameScore > twoStarThreshold { starImage = SKSpriteNode(imageNamed: "2_stars") print("You achieved 2 Stars") } else { starImage = SKSpriteNode(imageNamed: "1_star") print("You achieved 1 Star") }
This way, if you later decide 3 stars should be at 1500 instead of 1000, you just change one value instead of hunting through your conditionals.
内容的提问来源于stack exchange,提问作者user9611921

