LoginSignup
1
3

More than 3 years have passed since last update.

Reactの公式チュートリアルを進化させる(1)

Posted at

はじめに

Reactの公式チュートリアルでは,三目並べゲームの実装方法が紹介されていますが,このページの最後にこんな記述があります.

まだ時間がある場合や、今回身につけた新しいスキルを練習してみたい場合に、あなたが挑戦できる改良のアイデアを以下にリストアップしています。後ろの方ほど難易度が上がります:
1. 履歴内のそれぞれの着手の位置を (col, row) というフォーマットで表示する。
2. 着手履歴のリスト中で現在選択されているアイテムをボールドにする。
3. Board でマス目を並べる部分を、ハードコーディングではなく 2 つのループを使用するように書き換える。
4. 着手履歴のリストを昇順・降順いずれでも並べかえられるよう、トグルボタンを追加する。
5. どちらかが勝利した際に、勝利につながった 3 つのマス目をハイライトする。
6. どちらも勝利しなかった場合、結果が引き分けになったというメッセージを表示する。

やるしかないですね.

てことで,実装したので課題ごとに載せていこうと思います.
本記事では課題1のみ記載します.
当方React初心者ですので,何かあればアドバイスいただけると幸いです.

なお,この記事はReactの公式チュートリアルを終えていることを前提に書いています.
公式チュートリアルで解説されていることについては詳しく触れないのでご承知おきください.

課題内容

最初の課題内容はこちらです.

  1. 履歴内のそれぞれの着手の位置を (col, row) というフォーマットで表示する。

公式チュートリアルでは,着手の履歴を保存しておくことにより,過去のターンに戻ってやり直せるタイムトラベル機能を実装しています.

チュートリアルでは,下画像のように「Go to move #(ターン)」という形式で表示されたボタンをクリックすることで戻ることができるのですが,
before.png
下画像のように,そのターンで選択したマスを(列,行)という形式で表示することで分かりやすくしなさい,という主旨の課題のようです.
after.png

実装

チュートリアルでは,着手の履歴として盤面の状態のみを保存していましたが,選択したマスの位置も保存することにします.

Gameコンポーネントのstate
  this.state = {
    history: [{ // 着手の履歴を保存
      squares: Array(9).fill(null), // 盤面の状態
      position: null,  // [追加行] 選択したマスの位置(squaresのindex)
    }],
    stepNumber: 0, // ターン数
    xIsNext: true, // 手番
  };

これに伴い,stateの更新を行うhandleClickメソッドも以下のように変更します.
handleClickメソッドは,盤面のマスがクリック(選択)された際の処理です.

GameコンポーネントのhandleCkick
  handleClick(i) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1); // 着手の履歴
    const current = history[history.length - 1]; // 現在の状態
    const squares = current.squares.slice(); // 現在の盤面
    if (calculateWinner(squares) || squares[i]) { // 決着がついている or 既に選択されたマス だったら
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O'; // 手番でXかOか決める
    this.setState({ // stateの更新
      history: history.concat([{
        squares: squares,
        position: i, // [追加行]
      }]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext,
    });
  }

JSXの生成を行っているmovesの内容も変更します.

Gameコンポーネントrenderメソッドのmoves
    const moves = history.map((value, index) => {
      const desc = index ?
        `Go to move #${index} 
         (${(value.position % 3) + 1},${Math.floor(value.position / 3) + 1})`: // [変更行] (列,行)
        'Go to game start';
      return (
        <li key={index}>
          <button onClick={() => this.jumpTo(index)}>{desc}</button>
        </li>
      );
    });

positionは,9個のマスに対して0~8の通し番号を左上から振った場合の位置を表しているため,
列番号はvalue.position % 3) + 1
行番号はMath.floor(value.position / 3) + 1
とすることで表せます.

チュートリアルでは,mapのコールバック関数の引数として,(step, move)を使用していましたが,個人的に分かりづらかったので(value, index)に変更しています.(step, move)のままでも構いません.

実装例

課題1終了時点のコードを載せておきます.

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

// Square関数コンポーネント
function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}


// Boardクラスコンポーネント
class Board extends React.Component {
  renderSquare(i) {
    return <Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)} />;
  }

  render() {
    return (
      <div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}


// Gameクラスコンポーネント
class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [{
        squares: Array(9).fill(null),
        position: null,
      }],
      stepNumber: 0,
      xIsNext: true,
    };
  }

  handleClick(i) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1);
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      history: history.concat([{
        squares: squares,
        position: i,
      }]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext,
    });
  }

  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: (step % 2) === 0,
    });
  }

  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);

    const moves = history.map((value, index) => {
      const desc = index ?
        `Go to move #${index} (${(value.position % 3) + 1},${Math.floor(value.position / 3) + 1})`:
        'Go to game start';
      return (
        <li key={index}>
          <button onClick={() => this.jumpTo(index)}>{desc}</button>
        </li>
      );
    });

    let status;
    if (winner) {
      status = 'Winner: ' + winner;
    } else {
      status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
    }

    return (
      <div className="game">
        <div className="game-board">
          <Board squares={current.squares} onClick={(i) => this.handleClick(i)}/>
        </div>
        <div className="game-info">
          <div>{status}</div>
          <ol>{moves}</ol>
        </div>
      </div>
    );
  }
}


// calculateWinner関数コンポーネント
function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
}

// ========================================

ReactDOM.render(
  <Game />,
  document.getElementById('root')
);


1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3