1
\$\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.

\$\endgroup\$
2
\$\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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.