Car
Car

Reputation: 387

Using a Ruby while loop to access a class method

I'm creating a simple game of rock-paper-scissors that can be played in the console. The RPS game itself is stored in one class, and the console-player version is stored in another class. The RPS game is working and the console-player is working for one game, but when I try to loop through to allow the users to play 3 games I'm getting stuck. The users still aren't allowed to play more than three games, but the console no longer outputs the winner of the game.

Here's my code so far:

class Game
  attr_accessor :status

  def initialize(name1, name2)
    @name1 = name1
    @name2 = name2
    @status = []

  end

  def play(str1, str2)
    if @status.size == 3
      total = @status.inject(0) { |i, total| total += i }
      if total > 0
        "Game over, Player 2 wins"
      elsif total < 0
        "Game over, Player 1 wins"
        end
    else
      if (str1 == 'rock' && str2 == 'paper') || (str1 == 'scissors' && str2 == 'rock') || (str1 == 'paper' && str2 == 'scissors')
        @status << 1
        "Player 2 wins!"
      elsif (str2 == 'rock' && str1 == 'paper') || (str2 == 'scissors' && str1 == 'rock') || (str2 == 'paper' && str1 == 'scissors')
        @status << -1
        "Player 1 wins!"
      else
        "No winner"
      end
    end
  end
end


require 'io/console'

class RPSPlayer
  def start
    puts "Enter player 1 name"
    @player1 = gets.chomp
    puts "Enter player 2 name"
    @player2 = gets.chomp

    @new_game = Game.new(@player1, @player2)

    puts "#{@player1} challenges #{@player2} to an R-P-S showdown."

    player1_prompt = "#{@player1}:  what's your move?"
    player2_prompt = "#{@player2}:  what's your move?"

    while @new_game.status.size < 3
      puts player1_prompt
      str1 = gets.chomp
      puts player2_prompt
      str2 = gets.chomp

      @new_game.play(str1, str2)
   end
  end
end

If I delete the while loop in the console game (just prompting the players for input and inputting into @new_game) I get the winner name, but when I'm in the while loop the console just prompts the players for their move 3 times, without giving any output. Can anyone tell me why that would be?

Upvotes: 0

Views: 141

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37409

The method #play returns a string, it does not print it. To output the winner, you need to puts the result:

while @new_game.status.size < 3
  puts player1_prompt
  str1 = gets.chomp
  puts player2_prompt
  str2 = gets.chomp

  puts @new_game.play(str1, str2)
end

Upvotes: 0

Related Questions