我有一个硬汉给你。
我有一个程序用“w”类型的 Tile 对象填充二维数组。然后程序在数组中选择一个随机点(中心)并尝试转动距离中心为 4 的半径内的所有对象。不知何故,程序没有这样做,我认为问题出在数学公式上,但我找不到错误。
class Map
def initialize(d1,d2)
@data = Array.new(d1) { Array.new(d2)}
end
def [](x, y)
@data[x][y]
end
def x(x)
@data[x]
end
def y(y)
@data[y]
end
def []=(x, y, value)
@data[x][y] = value
end
end
# TILES
class Tile
# Types = ["l", "w", "r"]
attr_accessor :type
def initialize(type)
@type = type
end
def set(string)
@type = string
end
def to_s
@type
end
end
# REAL ACTION HERE
def generate
h = 20
w = 20
i = 0
worldmap = Map.new(20, 20)
while i < h do
n = 0
while n < w do
worldmap.[] = (i, n, Tile.new("w"))
n = n + 1
end
i = i + 1
end
gen(worldmap)
look(worldmap)
end
def look(map)
z = 0
b = 0
c = 0
string = " "
while b < 20 do
while z < 20 do
string = string + map.[](b, z).to_s
z = z + 1
end
b = b + 1
puts string
c = c + 1
end
end
def gen(map)
circle_amount = 1
i = 0
x = 0
y = 0
while i < circle_amount do
#select a center
cy = (rand(1..20))
cx = (rand(1..20))
center = map.[](cx,cy)
center.set("C")
radius = 4
puts cy.to_s + " " + cx.to_s
while y < 20
while x < 20
offsetY = y - cy
offsetX = x - cx
distance = offsetY**2 + offsetX**2
if distance <= radius**2 then
tile = map.[](y, x)
tile.set("l") # I DID IT
end
x = x + 1
end
y = y + 1
end
i = i + 1
end
end
generate
以下是输出示例
wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww wwwwwwwwwwwwlllllwww
C:/Users/borya/Documents/NetBeansProjects/LearningPurporse/lib/main.rb:7:in
[]': >undefined method
[]' for nil:NilClass (NoMethodError)