1

Ruby で数当てゲームを作ろうとしていますが、もう一度プレイしたいときに「はい」と入力すると、プログラムが終了します。キャッチアンドスローを使ってみましたが、うまくいきませんでした。助けてください。

これが私のコードです。

class Game
    def Play
        catch (:start) do
            $a=rand(11)
            puts ($a)
            until $g==$a
                puts "Guess the number between 0-10."
                $g=gets.to_i
                if $g>$a
                    puts "The number you guessed is too high."
                elsif $g==$a
                    puts "Correct you won!!!"
                    puts "Would you like to play again?"
                    $s=gets()
                    if $s=="yes"
                        $c=true
                    end
                    if $c==true
                        throw (:start) 
                    end
                elsif $g<$a
                    puts "The number you guessed is too low."
                end
            end
        end
    end
end
Game.new.Play

編集:提案を試した後の私の新しいコードは次のとおりです。

class Game
  def Play
    catch (:start) do
      $a=rand(11)
      puts ($a)
      while $s=="yes"
        until $g==$a
          puts "Guess the number between 0-10."
          $g=gets.chomp.to_i
          if $g>$a
            puts "The number you guessed is too high."
          elsif $g==$a
            puts "Correct you won!!!"
            puts "Would you like to play again?"
            $s=gets.chomp
            if $s=="yes"
              throw (:start)
            end
          elsif $g<$a
            puts "The number you guessed is too low."
          end
        end
      end
    end
  end
end
Game.new.Play
4

4 に答える 4

0

コードが機能しない理由についての質問には、これが実際には答えていないことはわかっていますが、投稿したコードを見た後、リファクタリングする必要がありました。どうぞ:

class Game
  def initialize
    @answer = rand(11)
  end

  def play
    loop do
      guess = get_guess
      display_feedback guess
      break if guess == @answer
    end
  end

  def self.play_loop
    loop do
      Game.new.play
      break unless play_again?
    end
  end

  private

  def get_guess
    puts "Guess the number between 0-10."
    return gets.chomp.to_i
  end

  def display_feedback(guess)
    if guess > @answer
      puts "The number you guessed is too high."
    elsif guess < @answer
      puts "The number you guessed is too low."
    elsif guess == @answer
      puts "Correct you won!!!"
    end
  end

  def self.play_again?
    puts "Would you like to play again?"
    return gets.chomp == "yes"
  end
end

Game.play_loop
于 2013-11-12T18:03:09.280 に答える