| 赞 | 72 |
| VIP | |
| 好人卡 | |
| 积分 | 23 |
| 经验 | |
| 最后登录 | 2022-3-9 |
| 在线时间 | 4033 小时 |
…あたしは天
- 梦石
- 0
- 星屑
- 2308
- 在线时间
- 4033 小时
- 注册时间
- 2010-10-4
- 回帖
- 10548
 
|
发表于 2016-7-31 10:37:18
|
显示全部楼层
本帖最后由 taroxd 于 2016-7-31 12:38 编辑
[pre lang="ruby"]def Slime
this = {
:hp => 10,
:mp => 10,
:tp => rand(5),
:exp => rand(5),
:lv => rand(5),
:atk => rand(5),
:def => rand(5),
:die => lambda { this[:hp] = 0 },
:bark => lambda {
if this[:hp] == 0
puts 'Uuuu...'
else
puts 'GaO!!'
end
}
}
end
slime1 = Slime()
slime1[:bark].call
slime1[:die].call
slime1[:bark].call[/pre]
不用 class 强行实现一下封装、继承、多态这些面向对象的特性w
[pre lang="ruby"]
def new(constructor, *args)
props = {}
this = -> action, *a {
if action == :props
props
else
constructor[this, action, *a]
end
}
constructor[this, :initialize, *args]
this
end
MyObject = -> this, action, *args {
raise NoMethodError.new("undefined method #{action}", action, args)
}
Barkable = -> parent {
-> this, action, *args {
case action
when :bark
if this[:hp] == 0
puts 'Uuuu...'
else
puts 'GaO!!'
end
else
parent[this, action, *args]
end
}
}
Slime = -> parent {
-> this, action, *args {
case action
when :initialize, :set_hp
this[:props][:hp], = args
when :hp
this[:props][:hp]
when :die
this[:set_hp, 0]
else
parent[this, action, *args]
end
}
}[Barkable[MyObject]]
GoldenSlime = -> parent {
-> this, action, *args {
case action
when :initialize
parent[this, action, 100]
when :bark
if this[:hp] > 50
puts 'Golden!'
else
parent[this, action]
end
else
parent[this, action, *args]
end
}
}[Slime]
slime1 = new GoldenSlime
slime1[:bark]
slime1[:die]
slime1[:bark]
[/pre] |
评分
-
查看全部评分
|