Class: RockPaperScissors

Inherits:
Object
  • Object
show all
Defined in:
lib/rps_telwell/rps.rb

Overview

Controls the overall game

Instance Method Summary collapse

Constructor Details

#initializeRockPaperScissors

Set initial variables



4
5
6
7
8
9
10
# File 'lib/rps_telwell/rps.rb', line 4

def initialize
  @player_1 = Human.new
  @player_2 = Computer.new
  @board = Board.new
  # Could use a constant (or @@class variable) for this
  @moves = ["rock","paper","scissors"]
end

Instance Method Details

#get_winner(player_1_move, player_2_move) ⇒ Object

Get winner



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rps_telwell/rps.rb', line 52

def get_winner(player_1_move, player_2_move)
  moves = [player_1_move,player_2_move]
  # This means we have a draw
  if moves[0] == moves[1]
    nil
  # Scenario for P1 rock 
  elsif moves[0] == 1
    return 1 if moves[1] == 3
    return 2
  # Scenario for P1 paper
  elsif moves[0] == 2
    return 1 if moves[1] == 1
    return 2
  # Scenario for P1 scissors
  elsif moves[0] == 3
    return 1 if moves[1] == 2
    return 2
  end
end

#output_winnerObject

Output winner



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rps_telwell/rps.rb', line 39

def output_winner
  if @winner.nil?
    puts "We had a draw! #{@moves[@player_1_move-1]} ties #{@moves[@player_2_move-1]}"
  elsif @winner == 1
    puts "Player 1 wins! #{@moves[@player_1_move-1]} beats #{@moves[@player_2_move-1]}"
    @player_1.wins=(@player_1.wins+1)
  else
    puts "Player 2 wins! #{@moves[@player_2_move-1]} beats #{@moves[@player_1_move-1]}"
    @player_2.wins=(@player_2.wins+1)
  end
end

#startObject

Start the game!



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rps_telwell/rps.rb', line 13

def start
  # Begin the loop
  loop do
    # Display board
    @board.render(@player_1.wins, @player_2.wins)

    # Get player_1 selection
    @player_1_move = @player_1.get_move

    # Get player_2 selection
    @player_2_move = @player_2.get_move

    # Who won? Returns 1 for player 1, 2 for player 2, or nil for a draw
    @winner = get_winner(@player_1_move,@player_2_move)

    # Output winner
    output_winner

    # What next?
    puts "What next? 1 to play again, 2 to quit"
    input = gets.chomp.to_i
    break if input == 2
  end
end