我正在编写一个脚本,我必须创建一个橘子树,每次运行指定的方法时,树的高度都会上升,树的年龄会上升,并且树上的橙子数量会增加。树也增加了。但经过一段时间(它取决于我),这棵树应该死了。所以在我的程序中,我决定如果树是15英尺或更大,它应该死了。现在,每当我通过该方法时,橙子的高度,年龄和数量都会增加,一旦高度超过15英尺,我会收到一条消息说“树已经死了”#34;但身高不断增加。我希望它一旦树死了就停止。另外,每当用户运行方法进入下一年时,我如何添加不同的东西?例如,现在每年高度增加3,橙子数量增加4,年龄增加1。如何使橙子的高度和数量每年增加一个随机数? (不是太大)这是我的代码。
class OrangeTree
def initialize
@tree_height = 0
@no_oranges = 0
@tree_age = 0
end
def firstYear
if @tree_height >= 15 then
puts "Tree is dead"
end
@tree_height = @tree_height + 3
puts "Your orange tree is " + @tree_height.to_s + " feet tall!"
@tree_age = @tree_age + 1
puts "Your orange tree is " + @tree_age.to_s + " year old!"
@no_oranges = @no_oranges + 4
puts "Your orange tree has " + @no_oranges.to_s + " oranges!"
end
def pickOrange
if @no_oranges == 0 then
puts "You can't pick any oranges yet, you have to wait at least a year!" else
puts "How many oranges do you want to taste?" + " Remember you only have " + @no_oranges.to_s + " oranges on your tree!"
pick2 = gets.chomp.to_i
puts "The oranges taste delicious and very refreshing!"
@no_oranges = @no_oranges - pick2
end
end
def isDead
if @tree_height >= 15 then
return true else
return false
end
end
def countOranges
puts "Current number of oranges: " + @no_oranges.to_s
end
end
答案 0 :(得分:1)
您必须修改firstYear
类中的OrangeTree
方法,以获取橙色的高度和数量作为参数递增,并在树高达到某个值时从方法返回。
class OrangeTree
def initialize
@tree_height = 0
@no_oranges = 0
@tree_age = 0
end
def firstYear(tree_height_increment, fruit_increment)
if @tree_height >= 15 then
puts "Tree is dead"
return
end
@tree_height = @tree_height + tree_height_increment
puts "Your orange tree is " + @tree_height.to_s + " feet tall!"
@tree_age = @tree_age + 1
puts "Your orange tree is " + @tree_age.to_s + " year old!"
@no_oranges = @no_oranges + fruit_increment
puts "Your orange tree has " + @no_oranges.to_s + " oranges!"
end
end
现在,每当您调用firstYear
方法时,您都可以指定要增加树的高度和水果值的值。