game on!

Ok, confession time:

It took me wayyyyyy to long to figure out how to update the win condition state in my Tic Tac Toe game. The problem I was having was a fairly straightforward one:


def win( board, win_condition )
	if board[0] == "X" and  board[1] == "X" and board[2] == "X"
		win_condition = true 
		return win_condition
	end 
end 

turn = 1
board = ["X", "X", "X"]
win_condition = false 

while win_condition != true and turn <= 9
	win(board, win_condition)
	turn += 1 
end 

puts win_condition					# false

In the above code, if we assume that the 3 X’s in the array are X’s that would be associated with the top row, and would qualify as a win condition so we need to check for the win condition and update the value to reflect that in order to break out of the while loop. This was essentially what I was implementing in my Tic Tac Toe code, because my thinking was that by returning the value that it would properly update the local variable win_condition upon the return being executed in the win function(s) if statement.

The problem here is though that although win_condition is updated and returned in the function, the value it is returning is not stored in anything. I assumed that such an update/storage would happen, but Ruby gladly proved me wrong.

The correct code looks like so:

def win( board, win_condition )
	if board[0] == "X" and  board[1] == "X" and board[2] == "X"
		win_condition = true 
		return win_condition
	end 
end 

turn = 1
board = ["X", "X", "X"]
win_condition = false 

while win_condition != true and turn <= 9
	win_condition = win(board, win_condition)
	turn += 1 
end 

puts win_condition				

The part that really confused me/tripped me out is that for some reason I assumed I was returning multiple variables even though I’m only returning one (win_condition). This assumption comes from the fact that I’m PASSING 2 variables, but this does not mean that I need to RETURN 2 variables.

The other interesting tidbit that I found out while researching this was that Ruby can return multiple variables, or at least give the appearance of it. As this post from rubyfleebie points out, if multiple things are returned, they are returned as an array which I was able to prove/find out with the following code:


def check(x, y)
	x = 888
	y = 1000
	return x, y
end 


x = "String" 
y = 1 

x = check(x, y)

puts x.class		# Array
puts x				# 888 1000

You find out something new every day, such is life.

Also, huge shout out to repl.it for allowing me to rapidly iterate through code as well as python tutor which actually takes you step by step through each part of your code and is an absolutely invaluable resource.

Written on October 7, 2016