Ruby Hangman游戏,当我输入完整单词但仅在我输入一个字母时才起作用

时间:2016-04-01 20:18:44

标签: ruby command-line

运行我的代码你的ruby解释器,看看我的代码。然后,尝试猜出完整的单词。该程序会告诉您,您的猜测是正确的,但如果您逐个猜测整个单词而不是每个字母,它就不会结束游戏。

我还想在我的代码中添加一个词典,以便能够与计算机而不是我自己或朋友一起玩!

def clear_screen
  return system('cls') if Gem.win_platform?
  system('clear')
end

loop do

  incorrect_guesses = 0

  puts ''
  puts 'Welcome to Hangman, Win or lose your life!'
  puts ''
  puts 'Choose Category: It can be anything you desire!'
  player1_category = gets.chomp
  puts ''

  puts 'Player 1, Please enter your desired word'
  secret_word = gets.chomp.downcase
  clear_screen

  correct_guess = ['-'] * secret_word.length
  clear_screen
  puts "The category is: #{player1_category}"
  puts 'Player 2, Please enter your guess'

  loop do
    puts '_ ' * secret_word.length
    player2_guess = gets.chomp.downcase
    clear_screen


if secret_word.include? player2_guess
    secret_word.each_char.with_index do |letter, i|
    next unless letter == player2_guess
    correct_guess[i] = letter
  end
  puts "The category is: #{player1_category}"
  puts ''
  print 'Guess the word: '
  print correct_guess.join('')
  puts ''
  puts 'Correct. Keep trying!!'
  puts ''
else
  puts "The category is: #{player1_category}"
  puts ''
  print 'Guess the word: '
  print correct_guess.join('')
  puts ''
  puts "The word doesn't contain that letter '#{player2_guess.upcase}'"
  puts ''
  incorrect_guesses += 1
end
puts "Incorrect Guesses: #{incorrect_guesses}"
puts ''

if incorrect_guesses == 6
  puts ''
  puts '|---+---+- '
  puts  '|   |'
  puts  '|   0'
  puts  '|   |\\'
  puts  '|   /\\'
  puts  '-+----------'
  puts "The Secret Word is '#{secret_word.capitalize!}'"
  puts ''
  break
end

next unless secret_word == correct_guess.join('')
puts ''
puts '   (@)'
puts '  ^\\|'
puts '    |/^'
puts '____|_____'
puts ''
puts 'You Win!'
puts ''
puts "You correctly guessed the word '#{secret_word.capitalize!}'"
break
end
end

2 个答案:

答案 0 :(得分:0)

你的问题不是很清楚,但这里有一些评论/答案:

  1. 猜测整个单词:如果测试输入的长度,您可以将当前的if secret_word.include? player2_guess包装在另一个中。 (这假设所有单词都大于1个字母)。 if语句应该测试user_input.length > 1。如果是,请评估猜测是否正确,等等。

  2. 添加词典:最简单的方法是对可能的单词值进行硬编码。如果您希望它们与类别对应,您可以像这样{'category_1' => [word, word, word], 'category_2' => [word, word, word]}进行哈希。然后你可以从哈希(类别)中选择一个随机值,然后从相应的数组中选择一个随机值。

答案 1 :(得分:0)

除非测试,否则我必须对下一个更改进行操作:

  if secret_word.include? player2_guess
    secret_word.each_char.with_index do |letter, i|
      next unless player2_guess.include?  letter
      correct_guess[i] = letter
    end

您将整个条目与单个字符进行比较。 '吨' !='测试'

至于字典,this link中的答案应该有帮助