如果我没有以正确的方式提出问题,请提前抱歉。
尝试使用这段Ruby代码。我不明白的是如何使底部的点击操作调用yield函数(它是一个交通信号灯),以便点击将循环通过yield选项。真实,虚假,虚假意味着光线是红色的,因为它在顶部,而底部的两个是假的。我也很难把我的脑袋缠绕在普查员身上。
class TrafficLight
include Enumerable
include TL
def each
yield [true, false, false]
yield [true, true, false]
yield [false, false, true]
yield [false, true, false]
end
end
class Bulb < Shoes::Shape
attr_accessor :stack
attr_accessor :left
attr_accessor :top
attr_accessor :switched_on
def initialize(stack, left, top, switched_on = false)
self.stack = stack #don't change.
self.left = left
self.top = top
self.switched_on = switched_on
draw left, top, bulb_colour
end
# HINT: Shouldn't need to change this method
def draw(left, top, colour
)
stack.app do
fill colour
stack.append do
oval left, top, 50
end
end
end
def bulb_colour
"#999999"
end
end
class GoBulb < Bulb
def bulb_colour
"#00FF30"
end
end
class WaitBulb < Bulb
def bulb_colour
"#FFFC00"
end
end
class StopBulb < Bulb
def bulb_colour
"#FF0000"
end
end
module TL
Go = "#00FF30"
Wait = "#FFFC00"
Stop = "#FF0000"
end
Shoes.app :title => "My Amazing Traffic Light", :width => 150, :height => 250 do
background "000", :curve => 10, :margin => 25
stroke black
@traffic_light = TrafficLight.new
@top = StopBulb.new self, 50, 40, true
@middle = Bulb.new self, 50, 100, true
@bottom = Bulb.new self, 50, 160, true
click do #make this switch on/off depending on what you click. Only 1 should be on
end
end
我用谷歌搜索和搜索,但我得到的调查员例子不允许我做我需要做的事情。非常感谢任何见解。
答案 0 :(得分:2)
包含当前版本的Shoes的Ruby(1.9.1)在Enumerator#next
上有一些意想不到的行为。调用此方法时会卡住。因此,您无法从Enumerator
迭代检索值。
TrafficLight
类必须重新编辑才能模仿Enumerator#next
。如果next
上没有此类错误,我们可以使用TraficLight.new.cycle
并在此循环调查员上重复调用`。
module TL
Go = "#00FF30"
Wait = "#FFFC00"
Stop = "#FF0000"
end
class TrafficLight
include TL
STATUS = [
[true, false, false],
[true, true, false],
[false, false, true],
[false, true, false]
]
def initialize; @index = 0; end
def current
STATUS[@index % STATUS.size]
end
def next
@index += 1
current
end
end
更新Bulb
,添加方法update(on)
以重绘灯泡。
def update(on = false)
self.switched_on = on
draw self.left, self.top, on ? self.bulb_colour : '#999999'
end
并更新Shoes.app
的主要逻辑以使用特定灯泡:
@traffic_light = TrafficLight.new
@top = StopBulb.new self, 50, 40, true
@middle = WaitBulb.new self, 50, 100, false
@bottom = GoBulb.new self, 50, 160, false
click do #make this switch on/off depending on what you click. Only 1 should be on
status = @traffic_light.next
[@top, @middle, @bottom].zip(status).each do |light, on|
light.update(on)
end
end