\$\begingroup\$
\$\endgroup\$
This is Tic-Tac-Toe using negamax for AI. Help me make it better!
Some sore points are:
def get_mark
good_mark = false
until good_mark
mark = gets.chomp
if mark =~ /x/i
chose_x
good_mark = true
elsif mark =~ /o/i
chose_y
good_mark = true
else
puts <<-EOS.gsub(/^ */, '')
What is this strange mark? please choose 'X' or 'O'!
EOS
end
end
end
and
def game_won?
@solutions.clear
make_solutions
won = false
@solutions.each do |solution|
if solution[0] != ' ' &&
solution[0] == solution[1] && solution[1] == solution[2]
won = true
end
end
return won
end
The rest of this is here.
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
Some suggestions:
- Avoid flags. Oftentimes there are a hint that you can structure your code better
- Learn the available language constructs and methods (e.g.
case/when
or#any?
) - Avoid methods with side effects when you can better use a functional style. (E.g. a implement
solutions
method returning the solutions instead of amake_solutions
method which modifies an instance variable with even has to be initialized before the call.) Among other things this improves reusability. You can still cache results in instance variables if needed.
Considering this you can write your provided code snippets a little neater:
def get_mark
while (mark = gets.chomp)
case mark
when /x/i then chose_x
when /o/i then chose_y
else
puts <<-EOS.gsub(/^ */, '')
What is this strange mark? please choose 'X' or 'O'!
EOS
continue
end
break
end
end
def game_won?
solutions.any? do |solution|
solution[0] != ' ' && solution[0] == solution[1] && solution[1] == solution[2]
end
end
I didn't dig through your git repo though. If you have more specific questions you should ask them.
answered Nov 11, 2013 at 21:32
lang-rb