Search code examples
rubyclassif-statementtic-tac-toe

Why does the else condition of my if-statement not work?


I wrote a tic-tac-toe program. The problem I am experiencing is that in my if statement, which allows the user enter his/her desired coordinate, my else condition is not working. The else condition is in place in case the user enters a coordinate not on the board.

This is my code:

class Game

  def initialize
    @board=Array.new
    @board[1]="1  __|"
    @board[2]="__"
    @board[3]="|__"
    @board[4]="\n2  __|"
    @board[5]="__"
    @board[6]="|__"
    @board[7]="\n3    |"
    @board[8]="  "
    @board[9]="|  "
    @turn="o"
    @win_status = false
  end

  def turn
    @turn
  end

  def show_board
    puts "   1  2  3"
    @board.each do |i|
      print i
    end
    puts ""
  end

  def set_turn #switches turns
    if @turn == "x"
      @turn = "o"
    else @turn == "o"
      @turn = "x"
    end
  end

  def make_move
    puts "Enter x coordinate"
    x=gets.to_i
    puts "Enter y coordinate"
    y=gets.to_i
    if y==1 && x==1
      @board[1]="1  _"+@turn+"|"
    elsif y==2 && x==1
      @board[2]="_"+@turn
    elsif  y==3 && x==1
      @board[3]="|_"+@turn
    elsif y==1 && x==2
      @board[4]="\n2  _"+@turn+"|"
    elsif y==2 && x==2
      @board[5]="_"+@turn
    elsif y==3 && x==2
      @board[6]="|_"+@turn
    elsif y==1 && x==3
      @board[7]="\n3   "+@turn+"|"
    elsif y==2 && x==3
      @board[8]=" "+@turn
    elsif y==3 && x==3
      @board[9]="| "+@turn+" \n"
    else
      "You entered an invalid coordinate"
    end

  end

  def win_combo
    return [[@board[1][4] + @board[2][1] + @board[3][2]], [@board[4][5] + @board[5][1] + @board[6][2]], [@board[7][5] + @board[8][1] + @board[9][2]],[@board[1][4] + @board[4][5] + @board[7][5]], [@board[2][1] + @board[5][1] + @board[8][1]], [@board[3][2] + @board[6][2] + @board[9][2]], [@board[1][4] + @board[5][1] + @board[9][2]], [@board[3][2] + @board[5][1] + @board[7][5]]]
  end

  def check_win
    #if some row or column or diagonal is "xxx" or "ooo" then set @win_status = true
    self.win_combo.each do |arr|
      str = arr.join
      if str == "xxx"
        puts "X Wins!"
        return true
      elsif str == "ooo"
        puts "O Wins!"
        return true
      end
    end
    return false
  end
  g = Game.new
  while g.check_win != true
    g.show_board
    g.set_turn
    g.make_move
  end
end

Solution

  • You are just returning the string: "You entered an invalid coordinate".

    I suspect that you want to display it using:

    puts "You entered an invalid coordinate"
    

    Otherwise it is passed as the result of g.make_move and then ignored.