meecoder
meecoder

Reputation: 156

Ruby - Loop will not break

I have written this code in Ruby for something for The Odin Project (Tic Tac Toe) and it won't break when @won is true. I can confirm that @won is becoming true but it won't break. The full code is at http://pastebin.com/GNJYC0hc

b = Board.init
b.create_squares
b.display_board
loop do
  if @turn == "player"
    print "Your turn! "
    b.player_turn
    b.display_board
    b.check_for_win
    @turn = "computer"
  else
    sleep 1.2
    b.computer_turn
    b.display_board
    b.check_for_win
    @turn = "player"
  end
  break if @won
end

FIXED I changed the code to use 1 instance of Board and it seems to be working now.

Upvotes: 1

Views: 147

Answers (1)

glyuck
glyuck

Reputation: 3397

Your code is rather weird. You are creating 2 board objects - you calling .play on first instance, then create another one inside play method and all game logic is performed on second instance. So you should do break if b.won.

But better refactor your code so .play is not creating new instances.

Upvotes: 4

Related Questions