last day (16 days later) » 
15:00 - 19:0019:00 - 21:00

3:23 PM
1
Q: Swift: Algorithm To Change A Random Number After Multiple Loops

Lukas KöhlI want to let the zombies move 30 times in one random direction and after that change the direction of every zombie individual. I have multiple zombie. All of them should NOT move in the same direction. I am sure I am missing something stupid. My code: for zombie in Zombies{ if(zombieCounter >...

 
@Arc676 If not every zombie would have the same direction which I don't want.
@Arc676 I updated the question
 
It could be the lines like zombie.position.y += step. What is step? It might be your issue.
 
@CalebKleveter Step is not the issue. So I am using SpiteKit and step is basically the step the zombie should take on the screen. So it moves the zombie on the screen by 5px. And I dont want to repeat this movement 30 times into the same direction.
 
I want to see the whole function. Because what I see now is the For loop is run and the if statement is checked, the counter is more then 30 (I assume you probably start it at 30 so the direction is randomly selected) so the direction is randomly created the zombie moves then the loops end and the counter is incremented, then the code is over. Thus the zombies move just once.
 
@CalebKleveter I added the whole function. Not this function is called by SpriteKit before each frame is rendered (60 times a second).
 
3:23 PM
The function is called every time the screen is rendered? Here is what I see: This line zombie.position.y += stepZombie (or the one's like it) are only called if(zombieCounter >= 25) So you add 1 to zombie counter after the if statement is run, but the zombie only moves if the counter is equal to or more then 25. Am I missing something?
 
@CalebKleveter No this is correct. Every time the function is called (60 times a second) it should move the zombie then. Moving it 60 times a second make the zombie really fast. To slow it down the movement get triggered every 25th run.
 
Are we going to move to chat?
 
@CalebKleveter If you could send me a hyperlink to the chat. I am currently on my phone. But do you understand what I am trying to get?
 
Yes, I get it.
 
Perfect.
 
3:26 PM
I have a feeling the issue is else were. I'll keep looking though.
 
Its the only code I have regarding to the movement.
Let me simplify even more. The random direction should be choosen every 30th time the code enters the if-statement.
I tried to archive this for over a hour now. It seems simple for me but I cannot get it to work.
 
3:46 PM
Can I see were you call the function and the relating code?
 
Well. This is all the code. I do not call the function. The function get called by itself. Its build into SpriteKit.
 
4:36 PM
Hey Lukas, how much code did you change since our last conversation?
 
None
 
ok, because you mentioned direction 0 in your code (Which is North now), but we are changing that to mean no movement
 
Ah yes I do remember. This was part of my old code.
 
I don't know how to get those fancy characters in your name on a US keyboard btw
 
This is a simple fix
let direction = Int(arc4random_uniform(4))+1
So my intention is to make the zombies run smoothly as the player. Before they just jumped on the position.
 
4:43 PM
A lot of your code involving behaviors of your sprites I would like to help you change, giving you an easier and better understanding of your code
 
If you got time for that
 
4:56 PM
Or later in 2-3 hours?
 
well its going to take some time, because I want you to understand the code as well, thats the important part
 
Are you writing the code now?
 
oh ok. just tell me when you have time
 
I have time
 
4:58 PM
Fine. Wanna start now?
 
sure
can you get me the latest build so that I am working with the same code as you
 
ok I got it
lets clean up some of this code, and give your classes some life
 
Maybe more in the wall class?
 
Now Gamescene is going to be your most complicated area, so it is a good idea to take out any code that should not belong in it
so I think we should start with taking some logic that belongs to your sprites out of it
 
5:08 PM
Well the only logic would be the update function or the movement
 
there are a few
we can start with cleaning up the update function
notice how moving a sprite or a zombie seems like a big mess in the update function?
 
Is not that of a big mess but yes
 
when you see how we clean it up, you will think differently lol
Open up MovingSprite.swift
 
Do I need to be here anymore?
 
5:13 PM
No I don't thinks so.
 
Okay. Bey and have fun!
 
Are you in MovingSprite.swift yet?
 
Yes sure Knight. I wait for you to resume.
 
I opened up MovingSprite.swift
 
5:16 PM
oh ok, well having direction be a number is a bad thing
 
Better use a string?
 
it is very easy to get things confused. so instead, we are going to make an enum
 
oh well. never used one of these
 
enum Direction : Int
{
case None
case North
case West
case South
case East
}
place that above class MovingSprite for now
this will make our code become more readable
 
Done
 
5:17 PM
direction = .North reads a lot better than direction = 1
ok. now lets change the variable declaration
var direction = Direction.None
 
Will
direction = .West be direction = 2?
 
in our case yes, you can manually define the values as well
case None = 0
case North = 1
 
so before 2 was south
 
you can change the order
I didnt know what your ordinals were
 
case None
case North
case South
case West
case East
thats what i have now
 
5:24 PM
thats fine
ok, now you know we will get errors, so lets go to gamescene and clean it up
 
first of all the didBeginContact
Will this be the correct solution? case Direction.North:
and so on
 
And will it still be: switch(player.direction){ ?
 
Ok I also updated the Direction.--- in the update function
 
5:31 PM
ok
you should be fine up to the point of the zombie area
 
I used /* ZombieMovement */
 
thats all going to change in a bit
right now your code should be failing at the let direction inside the zombie loop
 
No it isn't :D
 
did you change the case to case .North
 
5:34 PM
well, when you do, it will fail lol
 
Well still not
switch direction{
case .North: zombie.position.y += stepZombie
zombie.direction = Direction.North
case .South: zombie.position.y -= stepZombie
zombie.direction = Direction.South
case .West: zombie.position.x -= stepZombie
zombie.direction = Direction.West
case .East: zombie.position.x += stepZombie
zombie.direction = Direction.East
default:()
}
Or do i also need to write direction
 
you need the let direction above that line
it should be let direction = Int(arc....)
 
ya. there is no error
Instead in every case there is one
 
right
we need to make direction a different type
do do that, we do let direction = Direction(rawValue: Int(arc.....))!
to do*
 
There are still 4 errors.
Enum case North not found in type Direction?
 
5:39 PM
did you do .North
 
yes
 
paste the code
 
if(zombieCounter >= 25){
zombieCounter = 0
for zombie in Zombies{
let direction = Direction(rawValue:Int(arc4random_uniform(4))+1)
switch direction{
case Direction.North: zombie.position.y += stepZombie
zombie.direction = Direction.North
case .South: zombie.position.y -= stepZombie
zombie.direction = Direction.South
case .West: zombie.position.x -= stepZombie
zombie.direction = Direction.West
case .East: zombie.position.x += stepZombie
zombie.direction = Direction.East
default:()
}
}
}
I also tried the Direction.North but same error
 
what the heck...
it works fine here
 
which Xcode version do you use
 
5:42 PM
can you paste your entire gamescene
 
are you sure?
 
yeah
this is 7.1.1
 
//
// GameScene.swift
// DeineMamma
//
// Created by Lukas Köhl on 10.11.15.
// Copyright (c) 2015 Lukas Köhl. All rights reserved.
//

import SpriteKit

struct PhysicsCategory{
static let Wall:UInt32 = 0x1 << 0
static let Player:UInt32 = 0x1 << 1
static let Zombie:UInt32 = 0x1 << 2

}

class GameScene: SKScene, SKPhysicsContactDelegate {
var ax = Int()
var ay = Int()

var gameOver = false

let buttonUp = SKSpriteNode(imageNamed: "button_up")
let buttonLeft = SKSpriteNode(imageNamed: "button_left")
 
oh
you didnt type the ! at the end
 
Ah ya.
 
5:45 PM
Direction(rawValue:Int(arc4random_uniform(4))+1) !
 
Did not see this guy
 
ok, cool, we now have better readable code
 
thats true
 
now, lets make some reusable code
gee, it looks like zombie and player have the same movement code
so lets go back to MovableSprite
and make a new function
func move(direction:Direction,step:Int)
 
DONE
done sorry
 
5:50 PM
func move(direction:Direction, step:Int)
{
switch direction{
case .North:
self.position.y += step
self.direction = Direction.North
case .South:
self.position.y -= step
self.direction = Direction.South
case .West:
self.position.x -= step
self.direction = Direction.West
case .East:
self.position.x += step
self.direction = Direction.East
default:()
}
}
we took the moving code out of the for loop, and moved it into the class
 
it needs to be
func move(direction:Direction, step:Int)
{
switch direction{
case .North:
self.position.y += step
self.direction = Direction.North
case .South:
self.position.y -= step
self.direction = Direction.South
case .West:
self.position.x -= step
self.direction = Direction.West
case .East:
self.position.x += step
self.direction = Direction.East
default:()
}
}
func move(direction:Direction, step:CGFloat)
{
switch direction{
case .North:
self.position.y += step
self.direction = Direction.North
case .South:
self.position.y -= step
self.direction = Direction.South
case .West:
self.position.x -= step
self.direction = Direction.West
case .East:
self.position.x += step
self.direction = Direction.East
default:()
}
}
Sorry
 
yes, you are write
right*
now go back to gamescene, and replace that switch with zombie.move(direction,step:stepZombie)
 
done
 
finally lets update the player code to now use it as well
let direction = Direction.None
if(timeSinceLastUpdate >= delay){
if pressedButtons.indexOf(buttonUp) != nil {
direction = Direction.North
timeSinceLastUpdate = 0

}
if pressedButtons.indexOf(buttonDown) != nil {
direction = Direction.South
timeSinceLastUpdate = 0
}

if pressedButtons.indexOf(buttonLeft) != nil {
player!.direction = Direction.West
timeSinceLastUpdate = 0
}

if pressedButtons.indexOf(buttonRight) != nil {
player!.direction = Direction.East
timeSinceLastUpdate = 0

}
player!.move(direction,step:step);
use var direction = Direction.None not let
 
wait. Why is it direction =.. in the first 2 and player!.direction in the last 2
 
5:58 PM
i forgot to delete them
see, good catch
 
also in player!.move?
 
that should be there
we are saying we want to move the player
 
Ok
Ya. otherwise the self in MovingSprite would not make sense
 
uh oh, looks like we need to now account for direction.None in the movesprite
switch direction{
case .North:
self.position.y += step
case .South:
self.position.y -= step
case .West:
self.position.x -= step
case .East:
self.position.x += step
default:()
}
self.direction = direction;
lets take out the self.direction from each of the cases, and apply it to the bottom
now we handle all directions, and the sprite will only move based on a direction other than none
 
yes
 
6:02 PM
ok, now lets get the zombie counter out of the game scene
because who knows, in the future you may want the zombies to behave differently
 
But do you know how i would like to have the zombie movement?
 
that all depends on you
if you want all zombies to move 20 steps then change, thats fine
but maybe you want zombie 1 to move 5 steps then change, and zombie 2 move 10 steps
or maybe you want zombies to move 10 steps, and skeletons to move 5 steps
 
They should just move slow and steady instead of "teleport"
 
we will get to that
they teleport because your step is 20
 
Ya and i want them to move 4 times 5 in the same direction
 
6:05 PM
ok, we will get to that point
 
So it will look like an animation like the movement of the player
Ok fine
 
after we establish the counter system, they will move like that
so in the gamescene, lets remove that global zombieCounter variable
 
also direction and directionZombie?
 
no
oh
are those not needed
yeah remove them
 
direction was before we set up the enum
So ya
 
6:17 PM
var moveCounter : Int = 30
{
didSet{
if(self == 0)
{
direction = Direction(rawValue: Int(arc4random_uniform(4)) + 1)!
moveCounter = 30
}
}
}
I had to update my answer
 
As an function or how do the setter work
 
change 30 to 4
what this is, is called a property
you have getters and setters with a property
 
Oh well I can pretty much posts this everywhere.
Lets use 30 at the beginning
 
you want 4 you said
4 movements of 5
 
To have the same affect as the teleport. this would be half of a field. To make the zombies move better I think 4 fields of movement are better. I need to test this out later
 
6:20 PM
yeah you can change it to whatever value you want
just not that the '30' is how many times it will move in a straight line
note*
 
I am like a woman. No clear answer
 
eventually you are probably going to want random
 
Really? But thats what I wanted.
 
what random?
 
I want to pick a random direction and then go 30 times in this direction in a straight line. Then pick another random direction and so on
 
6:22 PM
that is what we are doing now
when you play your game a little bit, I have a feeling you want a random direction, then go a random distance in a straight line, then another random direction
makes your AI less predictable
 
Oh well random distance would be nice too
This game will just be on the app store for my IT class :D
 
its fine, you will keep poking and changing your mind on things
 
In our greenfoot game it didn't choose a random distance but i like it
 
i have been there
did you add that property yet?
 
ya like this
class MovingSprite: SKSpriteNode{
var healthPoints: Int
var attack: Int
var direction = Direction.None

var moveCounter : Int = 30
{
didSet{
if(self == 0)
{
direction = Direction(rawValue: Int(arc4random_uniform(4)) + 1)!
moveCounter = 30
}
}
}

init(name: String, healthPoints: Int, attack: Int){
 
6:25 PM
yes that is fine
now we have a problem
that darn move function gets in our way
so, lets take the move call from game sprite, and move it into our didSet function
 
you meant gamescene?
 
yes gamescene
sorry, getting tired lol
 
just the move or also the direction
 
we can delete the direction
 
No problem. I know this
ah i see it already in there
 
6:27 PM
should be an empty for loop now (we will fill this)
 
var moveCounter : Int = 30
    {
    didSet{
        if(self == 0)
        {
            direction = Direction(rawValue: Int(arc4random_uniform(4)) + 1)!
            zombie.move(direction,step:stepZombie)
            moveCounter = 30
        }
    }
}
 
did we move it in yet?
ok good
oh shoot, now that pesky stepZombie is in the way
 
ya
so we make a didGet?
 
(I already know the answers to what I am saying, I am just trying to play along so you understand)
no
 
Ya i already realized this ^^
 
6:29 PM
I notice that both zombies and players have a step function
step variable
 
And this can be combined
 
wouldnt it be nice if we assigned it inside a class somewhere
 
class MovingSprite: SKSpriteNode{
var healthPoints: Int
var attack: Int
var direction = Direction.None
let step = 5

var moveCounter : Int = 30
{
didSet{
if(self == 0)
{
direction = Direction(rawValue: Int(arc4random_uniform(4)) + 1)!
zombie.move(direction)
moveCounter = 30
}
}
}
 
What if we took the step variable, and placed it inside MovingSprite
 
like this?
 
6:31 PM
good job
 
so we can also remove the param step in move
 
excellent
 
Ah well it should be
let step: CGFloat = 5
 
now there is still the error in here
zombie.move(direction)
 
6:33 PM
what do you think it is
 
well i already tried self and it isnt
MovingSprite?
 
because self is moveCounter
 
well or simply just move(direction)
 
you just do move(direction)
 
6:34 PM
yup
 
Same class...
 
yes, you should only have 1 error now
unless you cleaned it up
and that is in update of gamescene
 
the for loop in gamescene
 
did you clean up player?
 
player!.move(direction);
 
6:35 PM
ok cool
we still need a way to decrease the counter
so we need to make an update function in enemy
func update()
{
moveCounter--
}
 
yap
I need to say. these classes from yesterday are very helpful
 
put that in the for loop
yup
that is how you should be thinking when programming
 
Ya. In the beginning of classes I had a big problem of accessing because I don't know which class should extend which
* of using classes
 
now your code should be compilable
 
I still don't now which i need to put in the forloop
 
6:40 PM
zombie.update()
 
done
 
ok does it compile
 
yes
 
cool
lets now add func changeHealthPoints(points: Int) {
healthPoints -= points
print(healthPoints)
if(healthPoints <= 0){
removeFromParent()
}
} to moving sprite
 
Done
 
6:43 PM
we can now remove the 2 functions from gamescene
since we are now going to attach it to the sprite
 
func didBeginContact(contact: SKPhysicsContact) {
let firstBody = contact.bodyA.node as! SKSpriteNode
let secondBody = contact.bodyB.node as! SKSpriteNode
let player = ((firstBody.physicsBody!.categoryBitMask <= secondBody.physicsBody!.categoryBitMask) ? firstBody: secondBody) as! MovingSprite
let enemy = ((firstBody.physicsBody!.categoryBitMask > secondBody.physicsBody!.categoryBitMask) ? firstBody: secondBody) as! MovingSprite

switch(player.direction){
case Direction.North:
if(enemy.position.y > player.position.y){
this is how we now use the function
 
done
 
finally, to fix gameover
add this to gamescene
func didFinishUpdate() {
if(player?.healthPoints < 0)
{
gameOver = true
}
}
 
you forgot override?
 
6:49 PM
yeah
ok lets run this mofo and see what we forgot
I can already tell you zombies probably wont move
 
let me get my iPhone started
my pc is to slow for an emulator
and you're true
*right
 
and thats because we never set an initial direction
 
ya its none
 
so in the init of enemy, you want to copy what didSet does
didSet will not get called in the init function, only after
basically direction = random. followed by move
 
init(name: String, healthPoints: Int, attack: Int){
    self.healthPoints = healthPoints
    self.attack = attack

    let texture = SKTexture(imageNamed:name)
    super.init(texture:texture, color: UIColor.clearColor(),size:texture.size())

    self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width/2)
    self.physicsBody!.affectedByGravity = false
    self.name = name

    direction = Direction(rawValue: Int(arc4random_uniform(4)) + 1)!
    move(direction)
    moveCounter = 30
}
they don't move :D
oh of enemy
well still no movement
 
6:55 PM
yup
because we now have an update function
so we need to take move out of didset, and move that to update
 
move(Direction) into the update of game scene?
 
no
enemy
 
but the move from the didSet in MovingSprite?
 
no that should be in enemy also
enemy should have movecounter
inside the movecounter didset
 
import Foundation
import SpriteKit

class Enemy: MovingSprite{

override init(name:String,healthPoints: Int, attack: Int){
super.init(name: name,healthPoints: healthPoints, attack:attack)

self.physicsBody!.categoryBitMask = PhysicsCategory.Zombie
self.physicsBody!.contactTestBitMask = PhysicsCategory.Player
self.physicsBody!.collisionBitMask = PhysicsCategory.Zombie | PhysicsCategory.Player | PhysicsCategory.Wall

direction = Direction(rawValue: Int(arc4random_uniform(4)) + 1)!
move(direction)
import Foundation
import SpriteKit

enum Direction : Int
{
case None
case North
case South
case West
case East
}

class MovingSprite: SKSpriteNode{
var healthPoints: Int
var attack: Int
var direction = Direction.None
let step: CGFloat = 5

var moveCounter : Int = 30
{
didSet{
if(self == 0)
{
direction = Direction(rawValue: Int(arc4random_uniform(4)) + 1)!
moveCounter = 30
}
}
}

init(name: String, healthPoints: Int, attack: Int){
self.healthPoints = healthPoints
self.attack = attack

let texture = SKTexture(imageNamed:name)
 
6:58 PM
oh, movecounter should be in enemy. not moving
player does not have AI
 
so like this
import Foundation
import SpriteKit

class Enemy: MovingSprite{
var moveCounter : Int = 30
{
didSet{
if(self == 0)
{
direction = Direction(rawValue: Int(arc4random_uniform(4)) + 1)!
move(direction)
moveCounter = 30
}
}
}

override init(name:String,healthPoints: Int, attack: Int){
super.init(name: name,healthPoints: healthPoints, attack:attack)

self.physicsBody!.categoryBitMask = PhysicsCategory.Zombie
self.physicsBody!.contactTestBitMask = PhysicsCategory.Player
self.physicsBody!.collisionBitMask = PhysicsCategory.Zombie | PhysicsCategory.Player | PhysicsCategory.Wall
 
15:00 - 19:0019:00 - 21:00

  last day (16 days later) »