When a gameOver() function is triggered, I would like all variables to reset to their original, unchanged values (as in, the values that are assigned in the ViewController file) when a user presses a Restart button. How can I do this?
Depending on the specific variables you have, one solution would be to create a struct with the fixed initial values and assign those to your active game variables in the Restart function.
You can define a function that reset the variables to the default value like this :
func resetGame(){
score = 0 // or default value
life = 3 // or default value
//.... and so on
}
Assume the restart button are connected to this function
#IBAction func restartGame(sender: UIButton){
gameOver()
resetGame()
}
you can call this function after calling gameOver() inside the restart button function.
If your question is about how to declare default values you can use struct as Jay said like this :
struct DefaultValues {
let score = 0
let lifes = 3
let level = 1
}
and resetGame() will be like this :
func resetGame(){
score = DefaultValues().score
life = DefaultValues().life
level = DefaultValues().devel
}
Related
I'm creating an app which chooses two random cards out of a 52-card deck. Then, if one of the card is strong (in my case, strong cards are "10" or stronger) I want it to show an image "yes" (tick). If both of the cards are weak, then I want it to show an image "no" (cross). I've been trying to find a problem, but every time I change something, a new type of error occurs.
I tried to set an unknown output type in func resultOfShuffle, I tried creating and naming an outlet for my UIImageView couple of times.
let cardArray = ["1.png", (...), "52.png"]
// All of the cards, from 2 to Ace (with every color). Number "33" is a card 10.
...
let cardResults = ["yes.png"]
...
#IBOutlet weak var theResult: UIImageView!
...
func randomizeCards() {
chooseCardOne = Int.random(in: 0 ... 51)
chooseCardTwo = Int.random(in: 0 ... 51)
...
func resultOfShuffle(firstCard : Int, secondCard : Int) -> UIImageView {
if firstCard > 33 {
return theResult.image = UIImage(named: cardResults)
}
}
And now, the return of the last func resultOfShuffle is wrong - telling me: Use of unresolved identifier 'theResult'. I also tried to find the solution to this problem, but it is kinda tricky and I don't get it.
That's how my app looks like:
https://imgur.com/a/kjdcqcO
Is every statement executed in the same ViewController?
It should recognize theResult as a UIImageView, then.
Update
The problem is, as solved in the comments, based on the scope of the function declaration. Since it is declared outside of the class where theResult is defined, it can't get access to it.
The solutions could be passing the variable as an argument to the function, or declaring the function in the same scope of the variable - inside the ViewController.
Other notes
You are, anyway, trying to return something with this line:
theResult.image = UIImage(named: cardResults)
which doesn't evaluate to a type, but simply sets the image of the view to what's in cardResults. Therefore, you shouldn't return anything, but merely using this function in order to update the content of the view - this means you should use a Void return type.
Furthermore, you are passing to the image initializer a [String] type, while you should just pass a String.
Try something like this:
func resultOfShuffle(firstCard : Int, secondCard : Int) {
if firstCard > 33 {
theResult.image = UIImage(named: cardResults[0])
}
}
Everyone,
I'm trying to understand why the exemple 1 return nil ( don't call a goooo function ), and the second exemple call it. Do I need to do something extra ?
Exemple 1 :
class A: UICollectionViewCell {
var exempleOneDetail: ExempleOneDetail?
...
}
func handleZoomTap(_ tapGesture: UITapGestureRecognizer) {
self.exempleOneDetail?.goooo(imageView)
}
=>> Result Nil
Exemple 2 :
func handleZoomTap(_ tapGesture: UITapGestureRecognizer) {
let exempleOneDetail = ExempleOneDetail()
exempleOneDetail?.goooo(imageView)
}
=>> Result : Call de function goooo
Thanks for help,
Regards
In example 1, you're never setting exempleOneDetail to anything before you call goooooo() on it, so it's nil.
In example 2, you're creating a local variable called exempleOneDetail and assigning an initialized object to it, and then calling goooooo(), so it does what you expect. However, be aware that your local copy, because it has the same name as the instance variable, is shadowing that variable, and if you try to use exempleOneLabel anywhere outside of handleZoomTap(), it will still be nil because you never assigned anything to it.
Im trying to end a funtion of an IBAction in an if statement, after validation input.
I've made a (global) function to check if the values of the variables which contain user input are Integers. Im trying to exit the functon by returning nothing, but the function doesn't end.
#IBAction func calculate(sender: AnyObject) {
var objects: [Int?] = [] // Contains an array of variables to be checked
//Global.checkInt returns true if all the variables in the array are int
//Global.throwLocalNot Global function to show a local notification
if Global.checkInt(objects) == false{
Global.throwLocalNot("Error", description: "Check your input!", viewController: self)
return
}
// Code to be executed if all variables are integers
...
}
This code works and throws a local notification if the input is not correct, but the return does not seem to work. What is the best way to stop a function from further execution?
I am using a simple function to call a random image when a view controller is loaded.
override func viewDidLoad() {
super.viewDidLoad()
var randomtest = ReturnRandom()
mainImage.image = UIImage(named: randomtest)
}
I want a button's action to be based on what image was displayed. For example
#IBAction func Button1(sender: AnyObject) {
switch randomtest {
case 1: //Do something here
case 2: //Do something different here
default:
}
However I can not figure out how to get the value of "randomtest" out of ViewDidLoad. I also can not seem to create the random number outside the ViewDidLoad then pass the variable in. Sorry I'm new to all this, iOS development is a long way away from php...
The reason I was having trouble declaring the result of my function as a instance variable is that my function is also an instance function. I can not call it, there has been no instance. So this
class ViewController : UIViewController {
var randomtest: Int = ReturnRandom();
Will return a "Missing argument for parameter #1 in call"
For more details please check out this very helpful thread on setting initial values. Since my function was so simple I just computed the property while setting the initial value, no need for an additional class level function.
dynamic var randomtest:String {
let imageNumber = arc4random_uniform(3)
var imageString = String(imageNumber)
return (imageString)}
Hope this helps someone.
I am working in between three files: Menu.swift, Main.swift and Game.swift.
In my Main.swift, I define the variable swipeNumber:
class Main {
var swipeNumber: Int = 0 {
didSet{
println("The new swipe number is \(swipeNumber)")
}
}
}
N.B. It is in a class so that I can reference the variable from other files, and the didSet property observer will function.
As you can see, its initial value (I think) is 0.
Then, in my Menu.swift, I retrieve the information from the Main class in Main.swift.
let main = Main()
I then have three buttons, which will, on touch, change the swipeNumber variable, based on which button was pressed.
class Menu: UIViewController {
#IBAction func pressedThreeSwipes(sender: AnyObject) {
main.swipeNumber = 3
}
#IBAction func pressedFiveSwipes(sender: AnyObject) {
main.swipeNumber = 5
}
#IBAction func pressedTenSwipes(sender: AnyObject) {
main.swipeNumber = 10
}
//...
}
When I run the program, my property observer appears to work, printing messages such as:
The new swipe number is 3
The new swipe number is 5
The new swipe number is 10
And in the Game class, (for troubleshooting purposes), I have another property observer, checking the integer of the variable swipeNumber when the button test is pressed:
class Game: UIView {
let main = Main()
func didMoveToView(view: UIView) {
/* Setup your scene here */
println("now")
println("\(main.swipeNumber)"
//Nothing happens here, suggesting that didMoveToView is failing
}
#IBAction func test(sender: AnyObject) {
println("\(main.swipeNumber)")
}
}
My func test prints a number, but sadly that number is not 3, 5, or 10. It's 0.
I think that the problem lies with my variable in Main.swift, however I am not sure.
Any advice or 'fixes', whether quick or lengthy, would be very greatly appreciated.
Thank you,
Will
You have different instances of your class Main, and they each carry a different value for the same properties.
You should try the Singleton pattern (see e.g. here or here).
When you call Main(), you are creating a new object...emphasis on NEW. It has no knowledge of what you've done to other objects of the same type. If you want to use the same object in different places, you need to make it a parameter and pass it into methods rather than creating a different object.