# GameManagerClassの実装

GameManagerClassを実装します。

## ゲームの進行知識を一つのクラスに

tic\_tac\_toe.rbから継続条件やゲーム板の更新などのゲームの管理の処理を抽出して

一つのクラスにまとめたいと思います。game\_manager.rbを作成していきましょう。

```ruby
# frozen_string_literal: true

require_relative "const"
require_relative "tic_tac_toe_input_error"
require_relative "tic_tac_toe_validator"

# ゲームの進行状況を管理する
class GameManager
  def initialize(player1:, player2:, board:)
    @player1 = player1
    @player2 = player2
    @current_player = @player1
    @board = board
  end

# 概要: ゲームが終了しているかどうかを返却する
# 引数: なし
# 戻り値: ゲームが続いている場合 => false
#        ゲームが終わった場合 => true
 def over?
    return false if @board.win?(opponent_player(@current_player).piece)
    return true if @board.can_plase_piece?

    false
  end

  # 概要: 現在プレイ中のプレイヤーと相手プレイヤーを入れ替える
  # 引数: なし
  # 戻り値: なし
  def change_to_opponent_turn
    @current_player = opponent_player(@current_player)
  end

  # 概要: ゲームの結果をコンソールに出力する
  # 引数: なし
  # 戻り値: なし
  def print_result
    if @board.win?(@player1.piece)
      puts "Player1が勝利しました!"
    elsif  @board.win?(@player2.piece)
      puts "Player2が勝利しました!"
    else
      puts "引き分けです!"
    end
  end

  # 説明: ゲーム板の状態をコンソールに出力する
  # 引数: なし
  # 戻り値: なし
  def print_board
    @board.print_board
  end

  # 説明: プレイヤーがコマを配置する場所を取得してターンを進める
  # 引数: なし
  # 戻り値: なし
  def player_turn
    row, col = @current_player.gets_piece_location
    @board.update(row, col, @current_player.piece)
  rescue TicTacToeInputError => e
    puts ""
    puts e.message
    puts ""
    player_turn
  rescue e
    raise e
  end

  private

  # 概要: 対戦中の相手プレイヤーを返却する
  # 引数: なし
  # 戻り値: PLAYER_1の時 => PLAYER_2
  #        PLAYER_2の時 => PLAYER_1
  def opponent_player(player)
    @player1.equal?(player) ? @player2 : @player1
  end
end

```

## テストの実装

ターンの更新や継続条件などを新たにgamter\_manager\_test.rbを作成してテストしてきましょう。

ほとんどのテストメソッドは既に実装しているはず！

{% hint style="info" %}
**課題コーナー**

&#x20;game\_manager\_test.rbを作成しテストを実装する
{% endhint %}

参考コードは以下のURLから参照してください

{% embed url="<https://github.com/Kashiwara0205/ruby-tic-tac-toe/blob/master/ch4/code/test/game_manager_test.rb>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kashiwara.gitbook.io/rubydesurufurusukuratchibe/rifakutaringu/gamemanagerclassno.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
