I have created a tic-tac-toe program in Ruby. I am having trouble with the part of the code which allows the game to end in a tie.
I wrote an if-statement to check for when a player wins the game. This is my else condition. When I try and run the program I get an error. What's wrong?
else
while @turn == "x" or "o"
@square_count -= 1 # I set empty_count to 9 in the initialize of the class
# of this program. This would minus 1 from empty) count_each every turn
end
if @square_count == 0 #when all the slots are taken, its a tie game
puts "Tie game!"
return true #this makes the program end
end
The error I am getting is:
tac.rb:89: warning: string literal in condition
tac.rb:88:in `block in check_win': undefined method `-' for nil:NilClass (NoMethodError)
from tac.rb:77:in `each'
from tac.rb:77:in `check_win'
from tac.rb:108:in `<class:Game>'
from tac.rb:1:in `<main>'
Replace
while @turn == "x" or "o"
with
while @turn == "x" or @turn == "o"
It looks like @square_count
might not be assigned a value, so you may be getting the error you indicate, as without an assignment, @square_count
will hold a nil value.
Also, your while statement may not be what you want, the while
statement will currently always evaluate as 'true' because of the value "o".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.