建立Tic Tac Toe游戏以学习OOP,但我的游戏板没有更新

时间:2015-12-01 08:18:49

标签: ruby oop

这些是不完整的代码,但它至少应该更新游戏板,直到它填满并出错。我不知道为什么它没有更新电路板。它确实在注册我的输入以及计算机,因为游戏确实打印了我的坐标。有人可以帮我弄清楚我做错了吗?

class Board
attr_reader :grid
  def initialize
    @grid = Array.new(3) { Array.new(3) }
    @human = HumanPlayer.new
    @computer = ComputerPlayer.new
    @game = Game.new
  end

  def place_mark(pos)
    if (pos[0] < 0 || pos[0] > 2) || (pos[1] < 0 || pos[1] > 2)
      puts "Invalid coordinates! Please try again!"
      @game.play
    elsif empty?(pos)
      if @game.current_player == "human"
        puts "Player 1 goes: #{pos}"
        @grid[pos[0]][pos[1]] = 'X'
      elsif @game.current_player == "computer"
        puts "Computer goes: #{pos}"
        @grid[pos[0]][pos[1]] = "O"
      end
      if winner
        puts "Congratulations! #{@game.current_player} wins!"
      else
        @game.switch_players!
      end
    else
      puts "Space Taken! Please Try Again!"
      @game.play
    end
  end

  def empty?(pos)
    @grid[pos[0]][pos[1]].nil?
  end

  def winner
    #Need to set winning combinations
    false
  end

  def over?
    false #for now, it will go until all spaces are filled. Still need to set end game condition.
  end

end


class HumanPlayer

  def display
    p Board.new.grid
  end

  def get_move
    puts "Please enter your the quadrant you wish to place your mark."
    pos = gets.chomp.scan(/[0-9]/).map!(&:to_i)
    Board.new.place_mark(pos)
  end

end


class ComputerPlayer

  def get_move
    x = rand(3).round
    y = rand(3).round
    Board.new.place_mark([x,y])
  end
end


class Game
  @@turn_tracker = 0
  def current_player
    @@turn_tracker.even? ? "human" : "computer"
  end

  def switch_players!
    @@turn_tracker += 1
    play
  end

  def play_turn
    if current_player == "human"
      HumanPlayer.new.display
      Board.new.place_mark(HumanPlayer.new.get_move)
    elsif current_player == "computer"
      ComputerPlayer.new.get_move
    end
  end

  def play
    play_turn until @@turn_tracker == 9 #Still need to set win conditions
  end

end

board = Game.new
board.play
  • 1)游戏以游戏#new#play
  • 开始
  • 2)#play将运行游戏,直到9轮过去(临时 条件)。它被传递给#play_turn
  • 3)#play_turn通过使用the来计算轮到它

    current_player。

  • 4)然后传递给HumanPlayer.get_move或 ComputerPlayer#get_move。这两个将决定每个的动作 玩家并将其传递给Board#place_mark。
  • 5)#place_mark将使用#empty确定移动是否有效?如果 有效,它应该更新网格。然后传递到 游戏#switch_players!
  • 6)#switch_players!将更改播放器并传回#play。
  • 7)它应该遍历这个循环。

1 个答案:

答案 0 :(得分:1)

你总是会产生一个新的棋盘,然后当然会再次使用起始位置:

class HumanPlayer

  def display
    p Board.new.grid
  end
...
end

如果你想学点东西,我不会给你一个解决方案。