Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Having hard time understand the concept behind 'points' func in swift

func points(inRange range: Int = 1) -> [Point] {
        var results: [Point] = []

        let lowerBoundOfXRange = x-range
        let upperBoundOfXRange = x+range

        let lowerBoundOfYRange = y-range
        let upperBoundOfYRange = y+range

        for xCooardinate in lowerBoundOfXRange...upperBoundOfXRange {
            for yCooardinate in lowerBoundOfYRange...upperBoundOfYRange {
                let cooardinatePoint = Point(x: xCooardinate, y: yCooardinate)
                results.append(cooardinatePoint)
            }
        }

        return results

I understand the initial idea & concept but not much the implementation Pasan Premaratne

Thanks for any replies in advance

Robert Conti
Robert Conti
23,274 Points

So the function, points, is passed a value for range, which is 1 by default. So if our tower can only shoot 1 grid space away from itself, it's range is 1. When we pass the range of the tower to points, the function does some simple math to create an array of x,y coordinates, telling us what coordinates our tower can fire upon.

Now why would we use this?

Because the game checks that array of x,y coordinates to see whether or not the tower and the enemy are within striking distance. So anytime you place a new tower at a new location, you can call points to see where that tower can fire upon.

If you want to create a new tower object with a greater range, for instance 2, then you can pass this value to the function and it will give you an array of coordinates for a tower with a range of 2. This makes our code flexible and reusable for different kinds of objects. Theoretically, you could use points for enemies to determine where they are allowed to move. So if they are only allowed to move one space at a time, then the range of the enemy would be 1. And so on...

2 Answers

Thank you so much for taking the time to answer my question, I've understood the concept behind it by re-watching the lessons again...and again... until it was clear

Robert Conti
Robert Conti
23,274 Points

Been there! No problem, best of luck!