저는 프로그래밍에 익숙하지 않지만 배우기를 열심히하니이 질문을 용서하십시오. 나는 OOP를 배우는 것을 돕기 위해이 게임을 만들었고 나는 그것의 일부로 문제를 겪고있다. 다음은 문제의 원인입니다.Ruby> 다른 클래스의 메서드 내에서 한 클래스의 메서드를 사용하려면 어떻게해야합니까?
두 클래스가 있습니다. Player 클래스의 3 번 줄에는 약간 잘못된 코드가 있지만 기본적으로 플레이어가받는 피해를 수정하기 위해 갑옷을 사용하고 있습니다. "NilClass (NoMethodError)에 대한 정의되지 않은 메소드 '보호'
다른 클래스의 Armor가 있습니다.이 문제는 @ armor.protection을 호출한다는 사실과 관련이 있다고 생각합니다. Armor와 Armor에 보호 기능이 언급되어있을 때 Player에서 언급되었지만이를 해결하는 방법이 확실하지 않습니다. 아래 질문과 관련이 있다고 생각되는 코드를 모두 추가했습니다. 그렇게 멍청한 놈이 이해할 수있는 용어를 사용하십시오
class Player
def equip(armor)
@armor = armor
end
def hit(damage)
#damage = damage - @armor.protection
@health -= damage
end
end
class Armor
def initialize(name, protection)
@protection = protection
end
end
편집 :.. 내가 해명을 진행 뭘 찾았는지 모두 표시하기 위해 추가 코드를 추가 을 나는 사람이 내가했습니다 무엇을 모두 읽을 기대하지 않습니다 있어, 그래도. : S 그것은 아마도 두렵고 무서운 것입니다. : P
class Player
def initialize(name, health)
@name = name
@health = health
end
def equip(armor)
@armor = armor
end
def health
@health
end
def health=(value)
@health = value
end
def hit(damage)
damage = damage - @armor.protection
@health -= damage
end
def dead?
if @health <= 0
return true
elsif @health > 0
return false
end
end
def name
@name
end
def attack(target)
damage = rand(30)
puts "#{@name} attacks #{target.name}"
target.hit(damage)
puts "#{@name} hits #{target.name} for #{damage} damage."
end
end
class Armor
def initialize(name, protection)
@protection = protection
end
end
player1 = Player.new("Melanie", 100)
player2 = Player.new("a Monster", 200)
shirt = Armor.new('shirt', 4)
player1.equip(shirt)
while player1.dead? == false && player2.dead? == false
player1.attack(player2)
if player2.health > 0
puts "#{player2.name}'s health is at #{player2.health}."
elsif player2.health <= 0
puts "#{player2.name} has no health."
end
player2.attack(player1)
if player1.health > 0
puts "#{player1.name}'s health is at #{player1.health}."
elsif player1.health <= 0
puts "#{player1.name} has no health."
end
end
if player1.health > player2.health
puts "#{player2.name} is dead."
puts "#{player1.name} wins."
elsif player2.health > player1.health
puts "#{player1.name} is dead."
puts "#{player2.name} wins."
elsif player2.health == player1.health
puts "#{player1.name} and #{player2.name} killed each other."
end
현재,이 프로그램은 갑옷을 말하면,이 플레이어의 경우 셔츠라는 것을 알지 못합니다. 내가 armor, 소문자 a, damage = damage 외에도[email protected] armor.protection은 Player 클래스에 장비에 대한 정의가있는 유일한 언급입니다. 두 번째 예제를 처리하려고했지만 두 경우 모두 여전히 동일한 오류가 발생했습니다. 나는 내 머리를 조금 넘는 것을 알고 있지만, 나는 그것을 많이 이해하고 있으며 그것은 분명히 학습 경험이다. : S –
@Melanie : 우선 보호 장치에 대해 언급했을 때 실수로 갑옷을 입력했기 때문에 코드가 잘못되었습니다. 작동하지 않습니다. 이제는 그것을 고쳤으며'@ armor'를 사용하는 메소드를 호출하기 전에'equip'을 호출하면 작동 할 것입니다. – sepp2k
'equip' 호출을 요구하는 더 좋은 해결책은'Player' 클래스'initialize' 메소드에서'Armor' 클래스를 'Armor' 클래스 인스턴스로 초기화하는 것입니다. 그렇게하면 플레이어가 갑옷없이 시작하면 걱정할 필요가 없습니다. –