I'm trying to make a guessing game in SpriteKit. My questions are images that I need to display once. I can't understand how to display them properly and only once. I have an array of them:
var pics = ["queston1","question2","question3","question4","question5"]
For that purpose I tried to show them with textures like that:
var pic = SKSpriteNode(imageNamed: "question1")
func setPics() {
pic.texture = SKTexture(imageNamed: "question1")
pic.name = pic.texture
addChild(pic)
}
Then I put setPics() at didMoveToView and loop through buttons:
case trueButton:
if pic.name == "question1"
//also tried if pic.texture == pic[0] {
print("true")
pic.texture = pic[1]
pic.removeAtIndex[0] //to prevent displaying it another time
// pic.texture = SKTexture(imageNamed: "question2"
}
if pic.texture == "question2" {
...
And so on. It doesn't work. And I understand that I'm doing it wrong, but I don't know how to do it better. This logic kind of worked when I tried to use random instead of hardcoding which question would be the next, but now it's completely wrong. But with random it was another problem. Textures layered on top of each other even though I was removing them from array.
How to make it right?
Related
So I'm practicing coding and I've set up an array of strings. What I want to happen is to have a function randomly select a string and if a certain string is selected, it would print out one message, and if any of the other strings are selected, it would print out a different one. I think setting up the messages could be done w/an if-else function, but I'm stuck on the earlier step of figuring out how to identify which string is called.
I did some searching and found this thread Get Random String from an Array and I copied the randomization code from it. I'm a bit overwhelmed with where to go from there.
What type of function/identifier etc would I need to set up so that the strings are uniquely identified?
class ViewController: UIViewController {
// Make collection of games and if Monsters is called, print "Take a break." If a diff string is called, print "Do your homework."
#IBAction func random(_ sender: UIButton) {
let games = ["Cards Against Humanity", "Mario Kart", "Halo", "Pixeljunk Monsters"]
let randomNumber = Int(arc4random_uniform(UInt32(games.count)))
_ = games[randomNumber]
}
} // end of class
Your expectation is not very clear from your question, but I guess you are beginner and need a help with processing randomly selected string.
#IBAction func random(_ sender: UIButton) {
let games = ["Cards Against Humanity", "Mario Kart", "Halo", "Pixeljunk Monsters"]
let randomNumber = Int(arc4random_uniform(UInt32(games.count)))
let randomlyPickedString = games[randomNumber]
if randomlyPickedString == "Cards Against Humanity" {
print("Print anything you want about Cards Against Humanity")
}
else if randomlyPickedString == "Mario Kart" {
print("Print anything you want about Mario Kart")
}
else if randomlyPickedString == "Halo" {
print("Print anything you want about Halo")
}
else {
print("Print anything you want about Pixeljunk Monsters")
}
}
If its a finite set of values in array, you can even decide to use switch
I have two UITextFields that get the placeHolder.text randomly from an array. The part I am stuck on, is having an element in an array of answers, correspond to the placeHolder text.
Meaning: placeHolder.text is a question, user text input is the answer, and we check that the user answer is the same as the hard coded value.
sample code:
let questionArray = ["name of your cat?", "name of your other cat?"]
let questionArray2 = { more stupid questions ]
let answerArray = ["cat damen", "diabetes"]
let answerArray2 = [ more stupid answers ]
var answerContainer: String()
var answerContainer2: String()
uitextField1.placeHolder = questionArray.randomElement()
uitextField2.placeHolder = questionArray2.randomElement()
Heres where I get stupid :
func answerGenerator {
if UItextField1.placeHolder == questionArray[0] {
answerContainer = answerArray[0]
}
}
func submit(_ sender: UIButton) {
if uitextField.text == answerContainer && uitextField2.text == answerContainer2 {
do good stuff
}
}
I tried using a dictionary, but got stuck. I also thought about an Enum / Switch Case, but also got stuck as I have two textFields that need the placeHolder generated randomly.
so what happens is the actual answer that's supposed to be allocated to its question, maybe it happens, but I'm not grabbing it correctly to compare what the user will type in the textfield.
Its so easy, but I'm overthinking this.
I'm using SpriteKit and Swift 3 to create a simple game.
I have an array of Rings/Circles:
mRings = [mRingOne, mRingTwo, mRingThree, mRingFour, mRingFive]
each object in the array has a different color, In some point in the game I want to change the color of each ring, but I have 2 condition for this to happen:
1. a ring should not have the color it had one iteration before.
2. each ring should be in a different color from the others.
for the first condition I did this:
func changeRingsColor(){
var previousColor: UIColor?
for ring in mRings {
previousColor = ring.fillColor
repeat{
ring.fillColor = hexStringToUIColor(hex: mColors[Int(arc4random_uniform(UInt32(5)))])
}while(ring.fillColor.isEqual(previousColor))
}
}
and it is working, however, I couldn't figure out a way to answer the second condition.
In Java I would probably do something like this:
for (int i=0; i<mRings.length; i++){
for( int j=1; j<mRings.length; j++){
if (ring[i].fillColor == ring[j].fillColor){
generate another color for 'j' ring.
}
}
}
but nothing I tried worked.
Hope you guys can help me, Thanks in advance!
btw, mColors is an array of 5 different colors, from there I pick the colors.
I'm going to ignore some of the implementation details and focus on the core of the question, which is:
Loop through an array
Within each loop, start a new loop at the current index to the end of the array.
Let me know if I'm misunderstanding the above. But I would do it like this:
for (index, ring) in mRings.enumerated() {
let remainingRings = mRings[index+1..<mRings.count]
for otherRing in remainingRings {
print("Now comparing \(ring) to \(otherRing)")
}
}
First, enumerated() gives you both the current ring, and the index, on each iteration of the first for loop. Then, we slice the array from the current index to the end (remainingRings), and loop through those.
It is possible to rewrite Java code in this way :
let mRings = ["mRingOne", "mRingTwo", "mRingThree", "mRingFour", "mRingFive"]
for (index, item) in mRings.enumerated() {
for item in index + 1..<mRings.count {
}
}
Something like this will work:
func changeRingsColor(){
// extract the previous colors
let colors = rings.map { $0.fillColor }
// the order in which the rings will pass color to each other
let passOrder = mRings.indices.shuffled()
for i in mRings.indices {
let previous = i == 0 ? mRings.count - 1 : i - 1
mRings[passOrder[i]].fillColor = colors[passOrder[previous]]
}
}
Using this implementation of shuffled
How does it work?
Instead of randomly choosing a color for each individual ring, I am randomly generating an order in which the rings will swap the colors (passOrder). Since every ring will pass its color to a different ring in that order, you can be sure no color will stay the same.
I'm making a simple game in swift and xcode and I ran into this problem that I can't figure out. Because I have so many levels, the code locks up indexing and slows down the whole program. I get a color wheel spinning for a few minutes but it never crashes. Just takes several minutes everytime I type in a few characters. Strange, but xcode has always had it's bugs right?
Each Button ("button1, button2..." below) gets a single number from "level1:Array". It's like a code that fills in the button's value for the game. There are only 4 buttons, but the numbers should be able to change as they each have their own variables.
I want to generate this for every level. I should be able to generate something like "button1 = level#[0]" where # is replaced by "userLevel". Changing to a string and doing something like "button1 = ("level(userLevel)") as! Array... doesn't seem to work. Look below and use my terminology when giving examples if you can. Thanks!
Here's the example:
let level1:Array = [9,7,4,1] // current puzzle, to go directly into button vars below (button1,button2,ect)
var userLevel = 1 // current user's level
if userLevel == 1 {
print("making Level 1, setting buttons to value from array")
button1 = level1[0]
button2 = level1[1]
button3 = level1[2]
button4 = level1[3]
}
Now, since level# is repeated so often (for each level as the number progresses) I would rather just make it something like this:
//this doesn't work in swift, but what else can I do?
if userLevel > 0 {
button1 = level\(userLevel)[0]
button2 = level\(userLevel)[1]
button3 = level\(userLevel)[2]
button4 = level\(userLevel)[3]
}
Is there an easy way to do this? Thanks!
-GG
Try using a for-in loop. Create an array of the buttons, and then
var index = 0
for button in buttons {
button = level1[index]
index++
}
EDIT since you want both the user level and the level number to increase, I suggest you define the levels like this. (Make sure that the number of buttons is equal to the number of userLevels, otherwise you will have problems)
var array = [1,2,3]
let levels = [1:[1,3,8],2:[3,6,4],3:[4,2,5]]
var index = 0
if array.count == levels.count {
for number in array {
array[index] = levels[index+1]![index]//The second index can be 0 if you want
index++
}
}
//array = [1,6,5]
// You could create a second index to match the number of levels within the main user level.
In this case, assume array to be your array of buttons
EDIT 2 :)
I've made a function that will allow you to assign all the levels to your array for a specific userLevel, since I see that is what you want
let levels = [1:[1,3,8],2:[3,6,4],3:[4,2,5]]
func assignValuesToArray(levelNo:Int) -> [Int] {
var array: [Int] = []
if (levelNo > 0) && (levelNo <= levels.count) {
for (level,levelArray) in levels {
if level == levelNo {
for value in levelArray {
array.append(value)
}
}
}
return array
} else {
print("This Level number does not exist")
return []
}
}
var finalArray = assignValuesToArray(2)
print(finalArray) // Returns [3,6,4]
As you can see from this example, you will return your array of buttons from the function, and you can assign the returned array values to whatever you like.
I'm a newbie to swift and believe me I've searched and searched for an answer already. I want to create UISliders that get their values from an array of numbers in Swift. Its a camera app so the example array should be obvious.
#IBAction func isoValueChanged(sender: UISlider) {
let isoArray = ["24", "32", "50","64","80","100","125","160","200","250","320","400","500","640","720","800","1000","1250","1600","1800"] // available iPhone 6s ISO settings I believe
let currentValue = // What do I need?
isoText.text = "\(currentValue)"
}
Even harder would be representing shutter speeds from 1/1000 - 32!
From what I see out there this is not an easy one because there is no mathematical representation to calc from the array. Is it even possible?
I'm not quite sure I understand what you want this for but I'm guessing this is right.
// Global Variable or something like this (accessible from multiple functions)
let isoArray = ["24", "32", "50","64","80","100","125","160","200","250","320","400","500","640","720","800","1000","1250","1600","1800"] // available iPhone 6s ISO settings I believe
func functionThatCreatesTheSliderYo(...) {
slider.minimumValue = 0
slider.maximumValue = isoArray.count
slider.continuous = false
}
#IBAction func isoValueChanged(sender: UISlider) {
// instead of Int(val) you may want to round(val) for a better UI
let currentValue = isoArray[Int(sender.value)]
isoText.text = "\(currentValue)"
}
This works for me
#IBAction func isoValueChanged(sender: UISlider) {
let isoArray = ["24", "32", "50","64","80","100","125","160","200","250","320","400","500","640","720","800","1000","1250","1600","1800"]
let currentValue = isoArray[Int(sender.value)]
isoText.text = "\(currentValue)"
}
So simple as it should be in Swift. Many thanks to Ty. Be sure to see the chat though.