GOAL = 21
MIN_MOVE = 1
MAX_MOVE = 3

DESCRIPTION = 




def best_move(total)
  move = rand(1..3)
  MIN_MOVE.upto(MAX_MOVE) do |i|
    move = i if (total + i - 1) % (MAX_MOVE + 1) == 0
  end
  MIN_MOVE.upto(MAX_MOVE) do |i|
    move = i if total + i == GOAL
  end
  move
end




def get_move
  print 
  answer = gets
  move = answer.to_i
  until move.between?(MIN_MOVE, MAX_MOVE)
    exit if answer.chomp == 'q'
    print 'Invalid choice. Try again: '
    answer = gets
    move = answer.to_i
  end
  move
end




def restart?
  print 'Do you want to restart (y/n)? '
  restart = gets.chomp
  until ['y', 'n'].include?(restart)
    print 'Your answer is not a valid choice. Try again: '
    restart = gets.chomp
  end
  restart == 'y'
end






def game(player)
  total = round = 0
  while total < GOAL
    round += 1
    puts 
    player = (player + 1) % 2
    if player == 0
      move = best_move(total)
      puts 
    else
      move = get_move
    end
    total += move
    puts 
  end
  if player == 0
    puts 'Sorry, the computer has won!'
    return false
  end
  puts 'Well done, you have won!'
  true
end


puts DESCRIPTION
run = true
computer_wins = human_wins = 0
games_counter = player = 1
while run
  puts 
  player = (player + 1) % 2
  if game(player)
    human_wins += 1
  else
    computer_wins += 1
  end
  puts 
  games_counter += 1
  run = restart?
end
puts 'Good bye!'