Implement tictactoe with redux

This commit is contained in:
2019-10-14 21:24:50 +02:00
parent ad5ebc1bd9
commit ed39569828
16 changed files with 297 additions and 127 deletions

View File

@@ -45,7 +45,9 @@ module.exports = {
'function-paren-newline': 0,
'no-confusing-arrow': 0,
'react/jsx-props-no-spreading': 0,
'no-unused-vars': 'off',
'no-underscore-dangle': 0,
'no-unused-vars': 0,
'object-curly-newline': 0,
'@typescript-eslint/no-unused-vars': [
'error',
{

View File

@@ -9,7 +9,9 @@
"@types/react-dom": "16.9.1",
"react": "^16.10.2",
"react-dom": "^16.10.2",
"react-redux": "^7.1.1",
"react-scripts": "3.2.0",
"redux": "^4.0.4",
"styled-components": "^5.0.0-beta.9",
"typescript": "3.6.4"
},
@@ -35,6 +37,8 @@
]
},
"devDependencies": {
"@types/react-redux": "^7.1.4",
"@types/redux": "^3.6.0",
"@types/styled-components": "^4.1.19",
"@typescript-eslint/eslint-plugin": "^2.3.3",
"@typescript-eslint/parser": "^2.3.3",

View File

@@ -1,7 +1,10 @@
import React from 'react';
import { Action } from 'redux';
import { connect } from 'react-redux';
import styled from 'styled-components';
import Board from './components/Board';
import playerEnum from './types/playerEnum';
import { Player } from './types/Player';
import { actions, GameState } from './redux/game';
import GlobalStyle from './theming/GlobalStyle';
const StyledApp = styled.div`
@@ -16,19 +19,36 @@ const StyledApp = styled.div`
color: white;
`;
const App: React.FC = () => {
const [currentPlayer, setCurrentPlayer] = React.useState(playerEnum.X);
interface StateProps {
currentPlayer: Player;
}
const nextPlayer = (): void => {
setCurrentPlayer((c) => (c === playerEnum.X ? playerEnum.O : playerEnum.X));
};
interface ActionProps {
startGame: () => Action;
}
return (
<StyledApp>
<GlobalStyle />
<Board {...{ currentPlayer, nextPlayer }} />
</StyledApp>
);
type Props = StateProps & ActionProps;
const App: React.FC<Props> = ({ currentPlayer, startGame }) => (
<StyledApp>
<GlobalStyle />
<h1>{currentPlayer}</h1>
<button type="button" onClick={startGame}>
Reset Game
</button>
<Board />
</StyledApp>
);
const mapStateToProps = (state: GameState): StateProps => ({
currentPlayer: state.currentPlayer,
});
const mapActionsToProps = {
startGame: actions.startGame,
};
export default App;
export default connect<StateProps, ActionProps, {}, GameState>(
mapStateToProps,
mapActionsToProps,
)(App);

View File

@@ -1,10 +1,11 @@
import React from 'react';
import { connect } from 'react-redux';
import { Action } from 'redux';
import styled from 'styled-components';
import Cell from './Cell';
import { cellState, notSet } from '../types/cellState';
import playerEnum from '../types/playerEnum';
import { getBoardSummary, undetermined } from '../lib/scoring';
import { IBoard } from '../types/IBoard';
import { Player } from '../types/Player';
import { actions, IGameState } from '../redux/game';
import { Board } from '../types/Board';
const Table = styled.table`
border: 0;
@@ -29,68 +30,49 @@ const Row = styled.tr`
}
`;
export interface IProps {
currentPlayer: playerEnum;
nextPlayer: () => void;
export interface IStateProps {
board: Board;
currentPlayer: Player;
}
export const Board: React.FC<IProps> = ({ currentPlayer, nextPlayer }) => {
const [board, setBoard] = React.useState<IBoard>([
[notSet, notSet, notSet],
[notSet, notSet, notSet],
[notSet, notSet, notSet],
]);
const [activeGame, setActiveGame] = React.useState(true);
const [boardSummary, updateBoardSummary] = React.useState(getBoardSummary(board));
export interface IActionProps {
nextPlayer: () => void;
startGame: () => Action;
makeMove: (rowIndex: number, cellIndex: number, currentPlayer: Player) => void;
}
const updateBoard = (rowIndex: number, cellIndex: number): void => {
if (!activeGame) {
return;
}
const checkCell = (rI: number, cI: number, cell: cellState): cellState => {
if (rI !== rowIndex || cI !== cellIndex) {
return cell;
}
if (cell !== notSet) {
return cell;
}
return currentPlayer;
};
type IProps = IStateProps & IActionProps;
setBoard((brd) => [...brd.map((row, rI) => row.map((cell, cI) => checkCell(rI, cI, cell)))]);
const BoardComponent: React.FC<IProps> = ({ currentPlayer, board, makeMove }) => (
<Table>
<tbody>
{board.map((row, rowIndex) => (
<Row key={`row-${rowIndex + 100}`}>
{row.map((cell, cellIndex) => (
<Cell
key={`cell-${cellIndex + 100}`}
value={cell}
onClick={(): void => makeMove(rowIndex, cellIndex, currentPlayer)}
/>
))}
</Row>
))}
</tbody>
</Table>
);
nextPlayer();
};
const mapStateToProps = (state: IGameState): IStateProps => ({
board: state.board,
currentPlayer: state.currentPlayer,
});
React.useEffect(() => {
updateBoardSummary(getBoardSummary(board));
}, [board]);
React.useEffect(() => {
if (boardSummary.winner !== undetermined && activeGame) {
setActiveGame(false);
}
}, [boardSummary]);
console.log('boardSummary', boardSummary);
return (
<Table>
<tbody>
{board.map((row, rowIndex) => (
<Row key={`row-${rowIndex + 100}`}>
{row.map((cell, cellIndex) => (
<Cell
key={`cell-${cellIndex + 100}`}
value={cell}
onClick={(): void => updateBoard(rowIndex, cellIndex)}
/>
))}
</Row>
))}
</tbody>
</Table>
);
const mapActionsToProps: IActionProps = {
startGame: actions.startGame,
nextPlayer: actions.nextPlayer,
makeMove: actions.makeMove,
};
export default Board;
export default connect<IStateProps, IActionProps, {}, IGameState>(
mapStateToProps,
mapActionsToProps,
)(BoardComponent);

View File

@@ -1,18 +1,18 @@
import React from 'react';
import styled from 'styled-components';
import { cellState, notSet } from '../types/cellState';
import playerEnum from '../types/playerEnum';
import { Cell, empty } from '../types/Board';
import { Player } from '../types/Player';
export interface IProps {
value: cellState;
export interface Props {
value: Cell;
onClick: () => void | Boolean;
}
const renderPlayerSymbol = (value: cellState): string => {
if (value === playerEnum.X) {
const renderPlayerSymbol = (value: Cell): string => {
if (value === Player.X) {
return 'X';
}
if (value === playerEnum.O) {
if (value === Player.O) {
return 'O';
}
return '';
@@ -24,8 +24,8 @@ export const StyledCell = styled.td`
font-size: 2rem;
`;
const Cell: React.FC<IProps> = ({ value, onClick }) => (
<StyledCell onClick={(): void | Boolean => value === notSet && onClick()}>{renderPlayerSymbol(value)}</StyledCell>
const CellComponent: React.FC<Props> = ({ value, onClick }) => (
<StyledCell onClick={(): void | Boolean => value === empty && onClick()}>{renderPlayerSymbol(value)}</StyledCell>
);
export default Cell;
export default CellComponent;

7
src/global.d.ts vendored Normal file
View File

@@ -0,0 +1,7 @@
export declare global {
interface Window {
__REDUX_DEVTOOLS_EXTENSION__: () => StoreEnhancer<Store<any, AnyAction>, {}>;
}
}
export default global;

View File

@@ -1,5 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider, ReactReduxContext } from 'react-redux';
import { createStore } from './redux/store';
import { actions } from './redux/game';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
const store = createStore();
ReactDOM.render(
<Provider store={store} context={ReactReduxContext}>
<App />
</Provider>,
document.getElementById('root'),
);
store.dispatch(actions.startGame());

View File

@@ -1,5 +1,5 @@
import { cellState, notSet } from '../types/cellState';
import { IBoard } from '../types/IBoard';
import { Board, Cell, Cells, empty, Rows } from '../types/Board';
import { Winner } from '../types/Player';
enum NoOneEnum {}
type INoOne = string | NoOneEnum;
@@ -8,23 +8,14 @@ export const noOne: INoOne = 'noOne';
enum UndeterminedEnum {}
type IUndetermined = string | UndeterminedEnum;
export const undetermined: IUndetermined = 'undetermined';
type IWinner = cellState | INoOne | IUndetermined;
export interface IBoardSummary {
horizontal: Array<Array<cellState>>;
vertical: Array<Array<cellState>>;
diagonal: Array<Array<cellState>>;
winner: IWinner;
horizontal: Rows;
vertical: Rows;
diagonal: Rows;
winner: Winner;
}
/*
* diagonal 1-2
* horizonal 1-3
* vertical 1-3
* line: X: 0, O: 1
* */
export const getBoardSummary = (board: IBoard): IBoardSummary => {
export const getBoardSummary = (board: Board): IBoardSummary => {
const summary: IBoardSummary = {
horizontal: [[], [], []],
vertical: [[], [], []],
@@ -44,27 +35,29 @@ export const getBoardSummary = (board: IBoard): IBoardSummary => {
}),
);
const getWinnerFromLine = (line: cellState[]): IWinner =>
const getWinnerFromLine = (line: Cell[]): Winner =>
line.reduce(
(cellWinner: IWinner, cell: cellState): IWinner => {
if (cell === notSet) {
(cellWinner: Winner, cell: Cell, index): Winner => {
if (cell === empty) {
return undetermined;
}
if (cellWinner === undetermined && cell !== notSet) {
if (index === 0 && cellWinner === undetermined && cell !== empty) {
return cell;
}
if (index > 0 && cellWinner === undetermined) {
return undetermined;
}
if (cellWinner === cell) {
return cell;
}
return noOne;
return undetermined;
},
undetermined as IWinner,
undetermined as Winner,
);
const getWinnerFromLines = (lines: cellState[][]): IWinner =>
const getWinnerFromLines = (lines: Rows): Winner =>
lines.reduce(
(lineWinner: IWinner, line: cellState[]): IWinner =>
lineWinner !== undetermined ? lineWinner : getWinnerFromLine(line),
(lineWinner: Winner, line: Cells): Winner => (lineWinner !== undetermined ? lineWinner : getWinnerFromLine(line)),
undetermined,
);

View File

@@ -1 +1,2 @@
/* eslint-disable-next-line */
/// <reference types="react-scripts" />

121
src/redux/game.ts Normal file
View File

@@ -0,0 +1,121 @@
import { Reducer, Action, Dispatch, MiddlewareAPI } from 'redux';
import { Player, Winner, undetermined } from '../types/Player';
import { Board, createEmptyBoard, Cell, empty } from '../types/Board';
import { getBoardSummary } from '../lib/scoring';
export const START_GAME = 'START_GAME';
export const END_GAME = 'END_GAME';
export const NEXT_PLAYER = 'NEXT_PLAYER';
export const MAKE_MOVE = 'MAKE_MOVE';
export const UPDATE_BOARD = 'UPDATE_BOARD';
export const DETERMINE_WINNER = 'DETERMINE_WINNER';
export interface MakeMoveAction extends Action {
type: typeof MAKE_MOVE;
payload: {
rowIndex: number;
cellIndex: number;
currentPlayer: Player;
};
}
export interface UpdateBoardAction extends Action {
type: typeof UPDATE_BOARD;
payload: {
rowIndex: number;
cellIndex: number;
currentPlayer: Player;
};
}
export const actions = {
startGame: (): Action => ({ type: START_GAME }),
nextPlayer: (): Action => ({ type: NEXT_PLAYER }),
endGame: (): Action => ({ type: END_GAME }),
makeMove: (rowIndex: number, cellIndex: number, currentPlayer: Player): MakeMoveAction => ({
type: MAKE_MOVE,
payload: { rowIndex, cellIndex, currentPlayer },
}),
updateBoard: (rowIndex: number, cellIndex: number, currentPlayer: Player): UpdateBoardAction => ({
type: UPDATE_BOARD,
payload: { rowIndex, cellIndex, currentPlayer },
}),
determineWinner: (): Action => ({ type: DETERMINE_WINNER }),
};
export interface GameState {
activeGame: Boolean;
currentPlayer: Player;
board: Board;
winner: Winner;
}
export type IGameState = GameState;
const defaultState: IGameState = {
currentPlayer: Player.X,
activeGame: false,
board: createEmptyBoard(),
winner: undetermined,
};
export const reducer: Reducer<IGameState, Action> = (state: IGameState = defaultState, action: Action): IGameState => {
if (action.type === START_GAME) {
return { ...state, board: createEmptyBoard(), activeGame: true };
}
if (action.type === END_GAME) {
return { ...state, activeGame: false };
}
if (action.type === NEXT_PLAYER) {
if (!state.activeGame) {
return state;
}
return { ...state, currentPlayer: state.currentPlayer === Player.X ? Player.O : Player.X };
}
if (action.type === UPDATE_BOARD) {
if (!state.activeGame) {
return state;
}
const { rowIndex, cellIndex, currentPlayer } = (action as UpdateBoardAction).payload;
const checkCell = (rI: number, cI: number, cell: Cell): Cell => {
if (rI !== rowIndex || cI !== cellIndex) {
return cell;
}
if (cell !== empty) {
return cell;
}
return currentPlayer;
};
return { ...state, board: [...state.board.map((row, rI) => row.map((cell, cI) => checkCell(rI, cI, cell)))] };
}
if (action.type === DETERMINE_WINNER) {
const boardSummary = getBoardSummary(state.board);
return { ...state, winner: boardSummary.winner };
}
return state;
};
export const middleware = ({ dispatch, getState }: MiddlewareAPI<Dispatch<Action>, GameState>) => (
next: Dispatch<Action>,
) => (action: Action): void => {
next(action);
if (action.type === MAKE_MOVE) {
const { activeGame } = getState();
if (!activeGame) {
return;
}
const { rowIndex, cellIndex, currentPlayer } = (action as MakeMoveAction).payload;
dispatch(actions.updateBoard(rowIndex, cellIndex, currentPlayer));
dispatch(actions.nextPlayer());
dispatch(actions.determineWinner());
const { winner } = getState();
if (winner !== undetermined) {
dispatch(actions.endGame());
}
}
};
export default reducer;

15
src/redux/store.ts Normal file
View File

@@ -0,0 +1,15 @@
import { createStore as createReduxStore, Store, AnyAction, compose, StoreEnhancer, applyMiddleware } from 'redux';
import { reducer, middleware } from './game';
const storeEnhancers: StoreEnhancer<Store<any, AnyAction>, {}>[] = [
applyMiddleware(middleware),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
].filter((m) => m);
export const createStore = (): Store<any, AnyAction> =>
createReduxStore(reducer, undefined, compose.apply(compose, storeEnhancers) as StoreEnhancer<
Store<any, AnyAction>,
{}
>);
export default createStore;

13
src/types/Board.ts Normal file
View File

@@ -0,0 +1,13 @@
import { Player } from './Player';
export enum EmptyEnum {}
export type Empty = string & EmptyEnum;
export const empty: Empty = 'empty' as Empty;
export type Cell = Empty | Player;
export type Cells = Cell[];
export type Row = Cell[];
export type Rows = Row[];
export type Board = Rows;
export const createEmptyBoard = (): Board => [[empty, empty, empty], [empty, empty, empty], [empty, empty, empty]];

View File

@@ -1,3 +0,0 @@
import { cellState } from './cellState';
export type IBoard = Array<Array<cellState>>;

16
src/types/Player.ts Normal file
View File

@@ -0,0 +1,16 @@
export enum Player {
X = 'X',
O = 'O',
}
enum TieEnum {}
type Tie = string | TieEnum;
export const tie: Tie = 'tie';
enum UndeterminedEnum {}
type Undetermined = string | UndeterminedEnum;
export const undetermined: Undetermined = 'undetermined';
export type Winner = Player | Tie | Undetermined;
export default Player;

View File

@@ -1,7 +0,0 @@
import playerEnum from './playerEnum';
export enum notSetTypeEnum {}
export type notSetType = string & notSetTypeEnum;
export const notSet: notSetType = 'notSet' as notSetType;
export type cellState = notSetType | playerEnum;

View File

@@ -1,6 +0,0 @@
export enum playerEnum {
X = 'X',
O = 'O',
}
export default playerEnum;