1 | Havaldar | Knapp | Zheng | Kemp |
2 | Hoiberg | Bursa | Steinbrick | McPherson |
3 | Zeng | Haas | Chawla | Waldoch |
4 | Bowler | Heberton | Tessler | Bailey |
5 | Lowen | James | Gurel | Martin |
6 | Li | O'Neil | Colcolough | Edupuganti |
We're going to build a game!
Groups will work together, but elect one typer.
Create variables to hold the hero's:
String
)FixNum
)FixNum
)Array<String>
)FixNum
)Create variables to hold the monster's:
String
)FixNum
)FixNum
)String
, one of "Dragon"
, "Goblin"
, "Salman"
)Time: 1 minute
Our game needs more monsters.
Make a monsters
array with 3.
Time: 1 minute
Attacking subtracts the attacker's power from the defendant's health.
def method_name(hero, monster)
...
end
Time: 1 minute
def attack(hero, monster)
monster[:health] -= hero[:power]
end
Use your method to have the hero attack the first monster.
attack(hero, monsters[0])
Does it need to be different?
def attack(attacker, defendant)
defendant[:health] -= attacker[:power]
end
When a hero attacks, s/he gains EXP.
Modify the function: attacker gains 1 EXP with each attack.
Time: 1 minute
def attack(attacker, defendant)
defendant[:health] -= attacker[:power]
attacker[:exp] += 1
end
Does it need to be different? Monsters don't gain exp
...
...and there's still so much to do!
* Don't repeat yourself
Objects let us group related properties and methods.
health
)attack
)What are other examples?
initialize
class Hero
def initialize(name, health, power)
@name = name
@health = health
@power = power
@items = []
@exp = 0
end
end
To denote an instance variable, prefix it with an @
Remember, this can be referred to anywhere in the class.
Which of these are instance variables and which are local variables?
@name
hercules
@power
items
he@lth
What should go in the ???
class Hero
def initialize(name, health, power)
...
end
# Teach your hero how to attack
def attack(monster)
monster[:health] -= ???
end
end
Modify Hero
's attack
method to also increment exp
.
Time: 1 minute
hero = Hero.new("hal", 20, 10)
hero.attack(monsters[1])
As a group, create a class called Monster
.
Write a constructor for it, and also an attack
method.
Challenge: if the monster's type is "Salman", have the attack do nothing :P
Time: 5 minutes
class Apartment
... # contains initialize method, among others
end
apartment = Apartment.new
apartment.add_resident('Bilbo Baggins')
Without classes: heroes.rb
With classes: heroes_with_classes.rb