React + TypeScriptでスネークゲーム

初投稿です．

[200行のVue.jsでスネークゲームを作った](https://qiita.com/miyauchoi/items/f753e5fa0209ab2034dd)というとても面白い記事を読んだので，React + TypeScriptでも書いてみました．リポジトリは[こちら](https://github.com/Catminusminus/snake)．

元記事のコードの改変なのでライセンスを記事の最後に表示してあります．
まずhtmlの方です．

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Snake</title>
    <style>
        /* グリッドレイアウト */
        #map {
            --grid-size: 10;    /* 10 x 10 マス（CSS変数） */
            display: grid;
            grid-template-columns: repeat(var(--grid-size), 30px);  /* 10列 幅30px */
            grid-template-rows: repeat(var(--grid-size), 30px); /* 10行 高さ30px */
        }
        /* セルの色 */
        .cell {
            border: 1px solid white;
            background: whitesmoke;
        }
        /* ヘビの体の色 */
        .cell.body {
            background: darkgray;
        }
        /* フルーツの色 */
        .cell.fruit {
            background: orangered;
        }
        /* ヘビの頭の色 */
        .cell.head {
            background: dimgray;
        }
    </style>
</head>
<body>
    <div id="root"></div>
    <script src="./main.tsx"></script>
</body>
</html>
```

で，main.tsxが140行くらいです．なのでhtmlと合わせて200行くらいですね．

```tsx
import React from 'react'
import ReactDOM from 'react-dom'

const gridSize = 10

const useSnake = (): [(number | null)[], number | null, number, boolean] => {
  const [fruitIndex, setFruitIndex] = React.useState(
    Math.floor(Math.random() * gridSize * gridSize),
  )
  const [headPos, setHeadPos] = React.useState({ x: 1, y: 3 })
  const [bodyIndexes, setBodyIndexes] = React.useState([30] as (
    | number
    | null)[])
  const [direction, setDirection] = React.useState('→')
  const [speed] = React.useState(400)

  const isFrameout =
    headPos.x < 0 ||
    gridSize <= headPos.x ||
    headPos.y < 0 ||
    gridSize <= headPos.y
  const snakeHeadIndex = !isFrameout ? headPos.y * gridSize + headPos.x : null
  const isEatingFruit = snakeHeadIndex === fruitIndex
  const isSuicided = bodyIndexes.includes(snakeHeadIndex)
  const isGameover = isFrameout || isSuicided

  const growUpSnake = () => {
    setBodyIndexes(preBodyIndexes =>
      (() => {
        preBodyIndexes.unshift(preBodyIndexes[0])

        return preBodyIndexes
      })(),
    )
  }

  const directionRef = React.useRef(direction)
  directionRef.current = direction

  const forwardSnake = () => {
    setBodyIndexes(preBodyIndexes =>
      ((body, head) => {
        body.shift()
        body.push(head)

        return body
      })(preBodyIndexes, snakeHeadIndex),
    )
    switch (directionRef.current) {
      case '←':
        setHeadPos(preHeadPos => ({ ...preHeadPos, x: preHeadPos.x - 1 }))
        break
      case '↑':
        setHeadPos(preHeadPos => ({ ...preHeadPos, y: preHeadPos.y - 1 }))
        break
      case '→':
        setHeadPos(preHeadPos => ({ ...preHeadPos, x: preHeadPos.x + 1 }))
        break
      case '↓':
        setHeadPos(preHeadPos => ({ ...preHeadPos, y: preHeadPos.y + 1 }))
        break
    }
  }

  const timeGoes = () => {
    if (!isGameover) {
      forwardSnake()
    }
  }

  React.useEffect(() => {
    const id = setTimeout(timeGoes, speed)

    return () => clearTimeout(id)
  }, [speed, isGameover, headPos, directionRef])

  React.useEffect(() => {
    if (isEatingFruit) {
      growUpSnake()
      setFruitIndex(Math.floor(Math.random() * gridSize * gridSize))
    }
  }, [isEatingFruit])

  React.useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      switch (e.keyCode) {
        case 37: // 「←」キーが押された
          if (direction !== '→') setDirection('←')
          break
        case 38: // 「↑」キーが押された
          if (direction !== '↓') setDirection('↑')
          break
        case 39: // 「→」キーが押された
          if (direction !== '←') setDirection('→')
          break
        case 40: // 「↓」キーが押された
          if (direction !== '↑') setDirection('↓')
          break
      }
    }

    window.addEventListener('keydown', onKeyDown)

    return () => window.removeEventListener('keydown', onKeyDown)
  }, [direction])

  return [bodyIndexes, snakeHeadIndex, fruitIndex, isGameover]
}

const App = () => {
  const [bodyIndexes, snakeHeadIndex, fruitIndex, isGameover] = useSnake()

  return (
    <div>
      <p>SCORE: {bodyIndexes.length - 1}</p>
      <div id="map">
        {Array.from({ length: gridSize * gridSize }, (_, i) => i).map(v => (
          <div
            className={`cell ${snakeHeadIndex === v ? 'head' : ''} ${
              bodyIndexes.includes(v) ? 'body' : ''
            } ${fruitIndex === v ? 'fruit' : ''}`}
          ></div>
        ))}
      </div>
      <>
        {isGameover && (
          <p>
            Gameover
            <br />
            <button onClick={() => location.reload()}>RETRY</button>
          </p>
        )}
      </>
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))
```
元記事のコードがベースなので特記することはなさそうですが，`forwardSnake`には`direction`ではなく，`directionRef`を渡すことに気を付けましょう．
useReducer版．前者よりこっちの方がよいと思いますが，100行くらい増えてしまった．

```tsx
import React from 'react'
import ReactDOM from 'react-dom'

enum Direction {
  LEFT = 37,
  DOWN = 38,
  RIGHT = 39,
  UP = 40,
}

const isOppsite = (dir1: Direction, dir2: Direction) => {
  switch (dir1) {
    case Direction.LEFT:
      return dir2 === Direction.RIGHT
    case Direction.RIGHT:
      return dir2 === Direction.LEFT
    case Direction.DOWN:
      return dir2 === Direction.UP
    case Direction.UP:
      return dir2 === Direction.DOWN
  }
}

interface Pos {
  x: number
  y: number
}

interface State {
  gridSize: number
  fruitIndex: number
  snake: {
    headPos: Pos
    bodyIndexes: (number | null)[]
    direction: Direction
    speed: number
  }
}

const genRandomIndex = (size: number) => Math.floor(Math.random() * size * size)
const initGridSize = 10

const initialState: State = {
  gridSize: initGridSize,
  fruitIndex: genRandomIndex(initGridSize),
  snake: {
    headPos: {
      x: 1,
      y: 3,
    },
    bodyIndexes: [30],
    direction: Direction.RIGHT,
    speed: 400,
  },
}

const setFruitIndex = (fruitIndex: number) =>
  ({
    type: 'SET_FRUIT_INDEX',
    payload: fruitIndex,
  } as const)

const moveHead = (direction: Direction) =>
  ({
    type: 'MOVE_HEAD',
    payload: direction,
  } as const)

const moveBody = (snakeHeadIndex: number | null) =>
  ({
    type: 'MOVE_BODY',
    payload: snakeHeadIndex,
  } as const)

const setDirection = (direction: Direction) =>
  ({
    type: 'SET_DIRECTION',
    payload: direction,
  } as const)

const growUpSnake = () =>
  ({
    type: 'GROW_UP_SNAKE',
  } as const)

type Action =
  | ReturnType<typeof setFruitIndex>
  | ReturnType<typeof setDirection>
  | ReturnType<typeof growUpSnake>
  | ReturnType<typeof moveHead>
  | ReturnType<typeof moveBody>

const reducer = (state: State = initialState, action: Action) => {
  switch (action.type) {
    case 'SET_FRUIT_INDEX':
      return {
        ...state,
        fruitIndex: action.payload,
      }
    case 'SET_DIRECTION':
      return {
        ...state,
        snake: {
          ...state.snake,
          direction: action.payload,
        },
      }
    case 'MOVE_BODY': {
      const body = state.snake.bodyIndexes
      body.shift()
      body.push(action.payload)

      return {
        ...state,
        snake: {
          ...state.snake,
          bodyIndexes: body,
        },
      }
    }
    case 'MOVE_HEAD':
      switch (action.payload) {
        case Direction.RIGHT:
          return {
            ...state,
            snake: {
              ...state.snake,
              headPos: {
                ...state.snake.headPos,
                x: state.snake.headPos.x + 1,
              },
            },
          }
        case Direction.LEFT:
          return {
            ...state,
            snake: {
              ...state.snake,
              headPos: {
                ...state.snake.headPos,
                x: state.snake.headPos.x - 1,
              },
            },
          }
        case Direction.UP:
          return {
            ...state,
            snake: {
              ...state.snake,
              headPos: {
                ...state.snake.headPos,
                y: state.snake.headPos.y + 1,
              },
            },
          }
        case Direction.DOWN:
          return {
            ...state,
            snake: {
              ...state.snake,
              headPos: {
                ...state.snake.headPos,
                y: state.snake.headPos.y - 1,
              },
            },
          }
        default: {
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          const _: never = action.type

          return state
        }
      }
    case 'GROW_UP_SNAKE': {
      const bodyIndexes = state.snake.bodyIndexes
      bodyIndexes.unshift(bodyIndexes[0])

      return {
        ...state,
        snake: {
          ...state.snake,
          bodyIndexes: bodyIndexes,
        },
      }
    }
    default: {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      const _: never = action.type

      return state
    }
  }
}

const useSnake = (): [
  number,
  (number | null)[],
  number | null,
  number,
  boolean,
] => {
  const [state, dispatch] = React.useReducer(reducer, initialState)
  const { gridSize, fruitIndex, snake } = state
  const { headPos, bodyIndexes, direction, speed } = snake

  const isFrameout =
    headPos.x < 0 ||
    gridSize <= headPos.x ||
    headPos.y < 0 ||
    gridSize <= headPos.y
  const snakeHeadIndex = !isFrameout ? headPos.y * gridSize + headPos.x : null
  const isEatingFruit = snakeHeadIndex === fruitIndex
  const isSuicided = bodyIndexes.includes(snakeHeadIndex)
  const isGameover = isFrameout || isSuicided

  const directionRef = React.useRef(direction)
  directionRef.current = direction

  const forwardSnake = () => {
    dispatch(moveBody(snakeHeadIndex))
    dispatch(moveHead(directionRef.current))
  }

  const timeGoes = () => {
    if (!isGameover) {
      forwardSnake()
    }
  }

  React.useEffect(() => {
    const id = setTimeout(timeGoes, speed)

    return () => clearTimeout(id)
  }, [speed, isGameover, headPos, directionRef])

  React.useEffect(() => {
    if (isEatingFruit) {
      dispatch(growUpSnake())
      dispatch(setFruitIndex(genRandomIndex(gridSize)))
    }
  }, [isEatingFruit])

  React.useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      if (!isOppsite(e.keyCode, direction)) dispatch(setDirection(e.keyCode))
    }
    window.addEventListener('keydown', onKeyDown)

    return () => window.removeEventListener('keydown', onKeyDown)
  }, [direction])

  return [gridSize, bodyIndexes, snakeHeadIndex, fruitIndex, isGameover]
}

const App = () => {
  const [
    gridSize,
    bodyIndexes,
    snakeHeadIndex,
    fruitIndex,
    isGameover,
  ] = useSnake()

  return (
    <div>
      <p>SCORE: {bodyIndexes.length - 1}</p>
      <div id="map">
        {Array.from({ length: gridSize * gridSize }, (_, i) => i).map(v => (
          <div
            className={`cell ${snakeHeadIndex === v ? 'head' : ''} ${
              bodyIndexes.includes(v) ? 'body' : ''
            } ${fruitIndex === v ? 'fruit' : ''}`}
          ></div>
        ))}
      </div>
      <>
        {isGameover && (
          <p>
            Gameover
            <br />
            <button onClick={() => location.reload()}>RETRY</button>
          </p>
        )}
      </>
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root')
```
こちらは...`dispatch`を書き忘れないようにしましょう．私はよくactionだけ書いて`dispatch`し忘れます...`setSpeed`とか実装して，段々速くしていくと面白いのかなと思ったり．なので`speed`は`State`に入っていますが，`gridSize`は変更したいかどうか迷ってしまったので上と下で扱いが変わってます．`useSnake`の引数にサイズを渡すのが良さそう？でも初スネークゲームで満足したので寝ます．

最後になりますが，本記事では元記事のコードの改変を含むので，元のライセンスを表示します．ありがとうございました．

```
MIT License

Copyright (c) 2019 猫チーズ（neko cheese）

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```