0

I'm trying to run the following code (my goal was to make a "game" where i make two objects and have them "fight" each other):

#player definition
Player=Struct.new(:health, :dmg)
active_player=Player.new(10, 2)

puts "test"

#monster definition
class Monster
    attr_accessor :health, :damage
    def initialize(health, damage)
        @health=health
        @damage=damage
    end
end
big_spider=Monster.new(4, 1)


player_win=false
monster_win=false

#the fight itself
while (!player_win) or (!monster_win)
    big_spider.health-=active_player.dmg
    active_player.health-=big_spider.damage
    if big_spider.health<=0
        player_win=true
    elsif active_player.health<=0
        monster_win=true
    end
end

#prints out who wins
case monster_win
    when true
        puts "the monster wins"
    when false
        puts "the player wins"
    else
        puts "error"
end

gets.chomp #is there to ensure that the program doesn't exit immediately after execution(yes i have tried removing it)

When I try to run that code (from Windows 10 PowerShell) it prints out "test" and then stops as if it was asking for input, however when I try to type anything it doesn't appear on the screen and I can't react with PowerShell in any other way than closing/minimising it (I even try pressing Ctrl+D as when exiting irb). I tried running the code in many other ways (through Notepad++, from file explorer, and through cmd.exe), yet i still ran into the same problem. When I comment out the lines from the "the fight itself" comment to the end of the code the program prints out "test",then asks for input and then stops executing. I haven't really found anyone with a similar issue anywhere.

0

1 Answer 1

3

That loop spins until BOTH win. With your current code, this is impossible. You want to change it to something like

while !player_win && !monster_win

Personally, I prefer to write such loops like this:

loop do
  break if player_win
  break if monster_win
  ...
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.