# RandomComPlayerの追加

### Randomizerの実装

RandomPlayerにランダムに数値を渡すRandomizerを実装します。

```ruby
# frozen_string_literal: true

# 乱数生成クラス
class Randomizer
  class << self
    # 概要: ランダムに0~2の数値を生成する
    # 引数: なし
    # 戻り値: 0 or 1 0r 2
    def create
      [0, 1, 2].sample
    end
  end
end

```

### RandomComPlayerを追加する

ランダムにコマを配置しにいく挙動をするRandomComPlayerを追加します。

OrdelyComPlayerを実装した時と同様BasePlayerを継承して実装していきます。

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

BasePlayerClassを継承したRandomPlayerを作成する

コマを配置できなければComErrorを発生させる
{% endhint %}

私は、以下のように実装しました。

```ruby
# frozen_string_literal: true

require_relative "base_player"
require_relative "../const"
require_relative "../errors/com_error"
require_relative "../randomizer"

# ランダムにコマを配置するCOM
class RandomComPlayer < BasePlayer
  TRY_COUNT = 1000

  # 概要: ゲーム板を受け取りランダムに場所を決めて空いてたら、その行と列番号を返却する
  # 引数: board_state: ゲーム板の情報
  # 戻り値: 行と列の情報を配列に格納して返却する => [1, 1]
  def gets_piece_location(board_state)
    TRY_COUNT.times do
      i = Randomizer.create
      j = Randomizer.create
      return [i, j] if OPEN_SLOT == board_state[i][j]
    end

    raise ComError, "RandomComPlayerクラスで配置場所が決まりませんでした"
  end
end
```

### テストの追加

最後にテストを追加して完了となります。

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

raondom\_com\_player\_test.rbを実装して見てください
{% endhint %}

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

{% embed url="<https://github.com/Kashiwara0205/ruby-tic-tac-toe/blob/master/ch5/code/test/players/random_com_player_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/zui-zhong-zhang-ji-neng-zhui-jia/randomcomplayerno.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.
