Challenge C: Character battle

Utilize something called a static factory method to create a game of Wizards vs. Elves vs. Giants.

Add a file Characters.swift in the Sources folder of your playground. To begin:

  • Create an enum GameCharacterType that defines values for elf, giant, and

wizard.

  • Create a class protocol GameCharacter that has properties name, hitPoints and

attackPoints. Implement this protocol for every character type.

  • Create a struct GameCharacterFactory with a single static method make(ofType: GameCharacterType) -> GameCharacter.
  • Create a global function battle that pits 2 characters against each other — with the first character striking first! If a character reaches 0 hit points, they have lost.

Notes:

  • The playground should not be able to see the concrete types that implement

GameCharacter.

  • Elves have 3 hit points, and 10 attack points. Wizards have 5 hit points and 5 attack points. Giants have 10 hit points and 3 attack points.
  • The playground should know none of the above!

In your playground, you should use the following scenario as a test case:

let elf = GameCharacterFactory.make(ofType: .elf) let giant = GameCharacterFactory.make(ofType: .giant)

let wizard = GameCharacterFactory.make(ofType: .wizard)

battle(elf, vs: giant) // Both players still active! battle(wizard, vs: giant) // Giant defeated! battle(wizard, vs: elf) // Wizard defeated!

You’ve learned the basics of operator overloading in Chapter 17, “Protocols”, where you implemented the Equatable and Comparable protocols and added custom behavior to standard operators.

However, there are certain cases when overloading standard operators is simply just not enough. This chapter will show you how to create custom operators from scratch and define your very own subscripts, a special case of computed properties. You will use subscript overloading to declare your own shortcuts for accessing the elements of arrays and dictionaries.

results matching ""

    No results matching ""