请原谅我的全局变量,这是我正在研究的一个Hangman项目。除了这个方法的一部分外,一切都正常。
def choice(n)
$random_word2.each_with_index do |i,index|
if i == n
$cipher[index] = i
end
end
if n == $random_word
puts "You win"
end
if $random_word2.include?(n) == false
$counter -= 1
display
puts "incorrect guess"
end
puts $cipher.join
end
特别是这些行。因为它是打印$ random_word所以你会知道它是什么,因为它是随机的。如果你输入整个单词,它应该打印“你赢了!”但它跳过最后一个“如果”并接受它作为一个不正确的猜测。我尝试了不同的变量并且它有效,所以这让我相信$ random_word变量在某个时候变成了一个不同的随机单词?我输了,它打印出来的字,我输入完全相同的东西,不知怎的,它不是==。
if n == $random_word
puts "You win"
这是整个计划。
load 'display.rb'
class Hangman
attr_accessor :name
@name = name
def initialize
puts "What is your name?"
@name = gets.chomp
puts "
################################################
HANGMAN
################################################
_________
|
| |
| O
| /|\\
| |
| / \\
|
-----------------
Welcome #{@name} to Hangman. The computer will generate
a 5-12 letter random word. You will try to guess
that word one letter at a time. Try to solve the
puzzle before time runs out!
"
Gameplay.new
end
end
class Gameplay
def initialize
$array = []
File.foreach('5text.txt') do |x| $array << x if (x.chomp.length >= 5 and x.chomp.length <= 12) end
$random_word = $array.sample
$random_word2 = $random_word.split(//)
puts $random_word2.join
$cipher = $random_word.gsub(/[a-z]/, '*').split(//)
puts $cipher.join
def choice(n)
$random_word2.each_with_index do |i,index|
if i == n
$cipher[index] = i
end
end
if n == $random_word2.join.to_s
puts "You win"
end
if $random_word2.include?(n) == false
$counter -= 1
display
puts "incorrect guess"
end
if $counter == 0
puts "you lose!!!!!!"
puts "would you like to start another game? Y/N"
new_game = gets.chomp
if new_game == "Y"
Hangman.new
end
end
puts $cipher.join
end
$counter = 5
while $counter > 0
choice(gets.chomp)
end
end
end
Hangman.new
答案 0 :(得分:0)
更改为
File.foreach('5text.txt') do |x|
chomped = x.chomp
$array << chomped if (chomped.length >= 5 and chomped.length <= 12)
end
因为您的原始程序中的单词\n
没有被限制。