2
\$\begingroup\$

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
asked Jun 27, 2013 at 4:56
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Some suggestions:

  1. Avoid flags. Oftentimes there are a hint that you can structure your code better
  2. Learn the available language constructs and methods (e.g. case/when or #any?)
  3. Avoid methods with side effects when you can better use a functional style. (E.g. a implement solutions method returning the solutions instead of a make_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
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.