russian roulette odd way to count that confuses me - swift

so i'm making this game about russian roullette
it starts wit 5 bullets out of 6 chamber
then whenever the person lives
one bullet is removed
is my way of doing it mathematicly accurate
the bullet count is based on the amount of characther on my button
heres my code
#objc func clickedTrigger(){
attempts += 1
if GKRandomDistribution.d6().nextInt() > gunTrigger.title.count{
if gunTrigger.title.count == 1{
gunTrigger.title = "⁍⁍⁍⁍⁍"
NSSound(named: NSSound.Name(rawValue: "Glass"))?.play()
attempts = 0
appWindow.title = "you won the game"
}
else{
gunTrigger.title = String(gunTrigger.title.dropLast())
appWindow.title = "the person dodged a bullet."
}
}
else{
gunTrigger.title = "⁍⁍⁍⁍⁍"
appWindow.title = "the person saddly died."
}
}

Related

Combine if statement and for loop such that loop only gets executed once per every execution of if statement in swift

I'm trying to understand swift and therefore try to come up with simple command line games: in this game a player has to guess a secret word within 6 attempts by typing something in the command line, but every time he gets it wrong, a statement prints the number of his wrong attempts:
let response = readLine()
if response != "secret word" {
for n in 1...6 {
print(n)
}
}
else {
print("you are right!")
}
Now I know that my code will print all lines once the condition is not true, but I'm looking for a way to only print one item out of the four loop for every if statement consecutively.
I think a while loop works pretty well. Maybe something like this:
print("Welcome to the input game!\n\n\n\n")
var remainingTries = 5
let dictionary = ["apple", "grape", "pear", "banana"]
let secretWord = dictionary.randomElement()
print("Please guess a fruit")
while remainingTries > 0 {
remainingTries -= 1
let response = readLine()
if response == secretWord {
print("You got it!")
remainingTries = 0
} else if remainingTries <= 0 {
print("Too bad, you lose!")
remainingTries = 0
} else {
print("Incorrect. Tries remaining: \(remainingTries)")
}
}

Finding specific elements of array with images

I have a program that displays a random card when you click the screen, and then removes that card from the card deck. But I also want to check if the random card is either of the picture cards in the deck (so jack, king, queen or ace), and then do some stuff if it is one of those. Anyone know how I can do it? When I try to check if the random card is equal to for example cardDeck[0] (the first card in the deck is a picture card), I get an error:
Cannot assign value of type 'UIImage' to type 'Int'
Thanks for all help!
My code looks like this:
var cardDeck = [card1,card2,card2 etc....]
var randomCard: Int = 0
var cardPosition = 0
//row1card1
#IBAction func row1card1tapped(_ sender: UITapGestureRecognizer) {
randomCard = Int.random(in: 0...51)
if cardDeck.count > randomCard + 1 {
if randomCard == cardDeck[0] {
//do stuff here
} else {
row1card1.image = cardDeck[randomCard+1]
cardDeck.remove(at: randomCard)
print("removed:" + "\(cardDeck[randomCard])")
score += 2
currentPoints.text = "\(score)"
}
Your randomCard variable is an Int and you’re trying to compare that with an element from cardDeck which is an image. That’s why you are getting the above exception.
if randomCard == 0 {
//do stuff here
}

Retrieve Best Score Game Center Swift

I'm in trouble, I can't fix a bug related to the func for retrieve the best score from the Game Center. The function is working good if you have a score but it's crashing if the user doesn't have score.
Any suggestions? Code below:
func retrieveBestScore() {
if GKLocalPlayer.localPlayer().isAuthenticated {
// Initialize the leaderboard for the current local player
var gkLeaderboard = GKLeaderboard(players: [GKLocalPlayer.localPlayer()])
gkLeaderboard.identifier = leaderboardID
gkLeaderboard.timeScope = GKLeaderboardTimeScope.allTime
// Load the scores
gkLeaderboard.loadScores(completionHandler: { (scores, error) -> Void in
// Get current score
var currentScore: Int64 = 0
if error == nil {
if (scores?.count)! > 0 {
currentScore = (scores![0] ).value
//We also want to show the best score of the user on the main screen
if self.language.contains("it"){
self.labelBestScore.text = "Miglior Punteggio: " + String(currentScore)
self.bestScore = Int(currentScore)
}else{
self.labelBestScore.text = "Your Best Score: " + String(currentScore)
self.bestScore = Int(currentScore)
}
print("Punteggio attuale",currentScore)
}
}
})
}
}
Thank you!
Based on your code it looks like you may be encountering this issue due to force unwrapping your 'scores' array.
Try something like this in your closure:
var currentScore: Int64 = 0
if error == nil, let scores = scores {
if scores.count > 0 {
currentScore = scores[0].value
//We also want to show the best score of the user on the main screen
if self.language.contains("it"){
self.labelBestScore.text = "Miglior Punteggio: " + String(currentScore)
self.bestScore = Int(currentScore)
}else{
self.labelBestScore.text = "Your Best Score: " + String(currentScore)
self.bestScore = Int(currentScore)
}
print("Punteggio attuale",currentScore)
}
}
Here's a secondary approach that condenses your code even more, I think this should work as well but it's hard to say for sure without seeing more code, it might need a couple minor changes possibly.
guard error == nil, let scores = scores, let currentScore = scores.first?.value else {
print("GameCenter error or no scores: \(String(describing: error)))")
return
}
//We also want to show the best score of the user on the main screen
if self.language.contains("it"){
self.labelBestScore.text = "Miglior Punteggio: " + String(currentScore)
self.bestScore = Int(currentScore)
}else{
self.labelBestScore.text = "Your Best Score: " + String(currentScore)
self.bestScore = Int(currentScore)
}
print("Punteggio attuale",currentScore)

Swift - Space Invaders (Aliens Display Loop Not Working)

I'm currently trying to make a space invaders game, I've got my ship movement working and am currently working on my Alien Display loop.
I'm close but for some reason my screen keeps coming up blank, no aliens are being displayed. Can anyone help? Here's what I have so far.
//Add and display given amount of aliens...
while displayAliens == true {
aliens.append(SKSpriteNode(texture: SKTexture(imageNamed: "ClassicAlien")))
self.addChild(aliens[displayLoopCounter])
//Location
aliens[displayLoopCounter].position.x = 0
aliens[displayLoopCounter].position.y = 0
aliens[displayLoopCounter].position.x = CGFloat(displayLoopCounter + 25)
displayLoopCounter += 1
//Have we run out of aliens yet?
if displayLoopCounter > alienAmount {
displayAliens = false
}
}
}
Not %100 sure where the issue is, but your loop would be cleaner as :
//Add and display given amount of aliens...
while (alienAmount >= displayLoopCounter) {
aliens.append(SKSpriteNode(texture: SKTexture(imageNamed: "ClassicAlien")))
self.addChild(aliens[displayLoopCounter])
//Location
aliens[displayLoopCounter].position.y = 0
aliens[displayLoopCounter].position.x = CGFloat(displayLoopCounter + 25)
displayLoopCounter += 1
}

Monty Hall simulation only 44%

I just created a simulation for the Monty Hall problem, but my result (even with 10,000,000 tests) is strange. For strategy 1 (keep) the hits are in 1/3, and strategy 2 (switch) in 44,44%. Is there a mistake in the code?
Thanks everybody!
var hits1 = 0
var hits2 = 0
let testsNumber = 1000
for i in 0..<testsNumber {
var doors: [Int] = []
for i in 0..<3 {
doors.append(0) // Append closed door
}
doors[Int(arc4random_uniform(UInt32(doors.count)))] = 1 // Here's the car...
var selection = Int(arc4random_uniform(UInt32(doors.count))) // Select door
if doors[selection] == 1 {
hits1 += 1
}
// Open first closed door
for i in 0..<doors.count {
if doors[i] != 1 {
doors[i] = -1 // Open door
break
}
}
// Switch to next closed door
repeat {
selection = (selection + 1) % doors.count
} while(doors[selection] == -1)
if doors[selection] == 1 {
hits2 += 1
}
}
print("Hits: \(hits1), quote: \((Double) (hits1) / (Double) (testsNumber))")
print("Hits: \(hits2), quote: \((Double) (hits2) / (Double) (testsNumber))")
The Monty Hall problem says "pick a door; before I open it, I'll show what's behind one of the other doors (one that doesn't have a car) and let you stay with your initial selection or switch to the other closed door".
But consider:
for i in 0 ..< doors.count {
if doors[i] != 1 {
doors[i] = -1 // Open door
break
}
}
That effectively says "show the contestant what's behind the first door that doesn't have a car".
But, you're not considering the possibility that this door might be the one that the contestant already picked. That's changing the parameters of the game.
You meant to say "open a door that does not have a car and is not the door the contestant picked."
for i in 0 ..< doors.count {
if doors[i] != 1 && i != selection {
doors[i] = -1 // Open door
break
}
}
When you do that, your odds by always changing your selection (having been shown one of the other two doors that didn't have a car) goes up to 2/3rds.