Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS

Matthias Andriessen
Matthias Andriessen
928 Points

The code in the video is wrong

The enemy died two times in the example. And why does the inRange function need that much parameters?

I corrected the code (you're welcome)

struct Point {
    let x: Int
    let y: Int

    init(x: Int, y: Int) {
        self.x = x
        self.y = y
    }

    func surroundingPoints(withRange range: Int = 1) -> [Point] {

        var result: [Point] = []

        for xCoord in (self.x-range)...(self.x+range) {
            for yCoord in (self.y-range)...(self.y+range) {
                result.append(Point(x: xCoord, y: yCoord))
            }
        }

        return result

    }
}

class Enemy {
    var life: Int = 100
    var position: Point

    init(x: Int, y: Int) {
        self.position = Point(x: x, y: y)
    }

    func decraeseHealth(factor: Int) {
        life -= factor
    }
}

class Tower {
    let position: Point
    var range: Int = 1
    var strength: Int = 1

    init(x: Int, y: Int) {
        self.position = Point(x: x, y: y)
    }

    func fireAtEnemy(enemy: Enemy) {
        if(inRange(enemy)) {
            while enemy.life > 0 {
                enemy.decraeseHealth(self.strength)
                if (enemy.life == 0) {
                    print("Enemy died")
                }
            }
        } else {
            print("Enemy is out of range");
        }
    }

    func inRange(enemy: Enemy) -> Bool {

        let target = enemy.position
        let availabePosition = position.surroundingPoints(withRange: range)

        for point in availabePosition {
            if (point.x == target.x) && (point.y == target.y) {
                return true
            }
        }
        return false
    }


}

let tower = Tower(x: 2, y: 2)
let enemy = Enemy(x: 1, y: 2)

tower.fireAtEnemy(enemy)
Jake Adams
Jake Adams
1,608 Points

Can you share a link to the video in question?