├── public
├── favicon.ico
├── manifest.json
└── index.html
├── src
├── index.js
├── components
│ ├── Square.js
│ ├── Board.js
│ └── Game.js
└── index.css
├── .gitignore
├── .vscode
└── launch.json
├── package.json
├── README.md
├── LICENSE
└── CSS
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/harman052/react-tutorial-solutions/HEAD/public/favicon.ico
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import ReactDOM from "react-dom";
3 | import Game from "./components/Game";
4 |
5 | ReactDOM.render( , document.getElementById("root"));
6 |
--------------------------------------------------------------------------------
/src/components/Square.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 |
3 | const Square = props => {
4 | return (
5 |
9 | {props.value}
10 |
11 | );
12 | };
13 |
14 | export default Square;
15 |
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | }
10 | ],
11 | "start_url": ".",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 | .vscode
21 |
22 | npm-debug.log*
23 | yarn-debug.log*
24 | yarn-error.log*
25 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to learn about possible attributes.
3 | // Hover to view descriptions of existing attributes.
4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "type": "chrome",
9 | "request": "launch",
10 | "name": "Launch Chrome against localhost",
11 | "url": "http://localhost:3000",
12 | "webRoot": "${workspaceFolder}"
13 | }
14 | ]
15 | }
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "tic-tac-toe",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "gh-pages": "^3.0.0",
7 | "react": "^16.13.1",
8 | "react-dom": "^16.13.1",
9 | "react-scripts": "^3.4.1"
10 | },
11 | "scripts": {
12 | "predeploy": "npm run build",
13 | "deploy": "gh-pages -d build",
14 | "start": "react-scripts start",
15 | "build": "react-scripts build",
16 | "test": "react-scripts test",
17 | "eject": "react-scripts eject"
18 | },
19 | "eslintConfig": {
20 | "extends": "react-app"
21 | },
22 | "browserslist": [
23 | ">0.2%",
24 | "not dead",
25 | "not ie <= 11",
26 | "not op_mini all"
27 | ],
28 | "homepage": "https://harman052.github.io/react-tutorial-solutions"
29 | }
30 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Solutions to additional challenges given in React's "tic tac toe" tutorial. [Demo](https://harman052.github.io/react-tutorial-solutions/)
2 | In addition to tutorial challenges, reset and play again buttons are added. Technically, both are same. Reset button appears all the time but play again shows up only when game is over (i.e. either draw or win/lose).
3 |
4 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
5 |
6 | ### How to start the app?
7 |
8 | Go to the app root directory and run: `npm start`
9 |
10 | It will start the development server. App will open at [http://localhost:3000](http://localhost:3000) in the browser. The page will reload if you make edits. You will also see any lint errors in the console.
11 |
12 | ### Useful links
13 |
14 | [Tutorial: Intro to React](https://reactjs.org/tutorial/tutorial.html).
15 |
16 | #### Suggestions/contributions for all sorts of improvements are highly encouraged. :-)
17 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Harmanpreet Singh
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/CSS:
--------------------------------------------------------------------------------
1 | body {
2 | font: 14px "Century Gothic", Futura, sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | .active {
7 | font-weight: 600;
8 | }
9 |
10 | .inactive {
11 | font-weight: normal;
12 | }
13 |
14 | ol, ul {
15 | padding-left: 30px;
16 | }
17 |
18 | .board-row:after {
19 | clear: both;
20 | content: "";
21 | display: table;
22 | }
23 |
24 | .status {
25 | margin-bottom: 10px;
26 | }
27 |
28 | .square {
29 | background: #fff;
30 | border: 1px solid #999;
31 | float: left;
32 | font-size: 24px;
33 | font-weight: bold;
34 | line-height: 34px;
35 | height: 34px;
36 | margin-right: -1px;
37 | margin-top: -1px;
38 | padding: 0;
39 | text-align: center;
40 | width: 34px;
41 | }
42 |
43 | .square:hover {
44 | outline: none;
45 | background: #fff1d3;
46 | }
47 |
48 | .square:focus {
49 | outline: none;
50 | background: #fff;
51 | }
52 |
53 | .kbd-navigation .square:focus {
54 | background: #ddd;
55 | }
56 |
57 | .winLine {
58 | color: #07851c;
59 | /*background-color: rgb(252, 224, 99);*/
60 | }
61 |
62 | .draw {
63 | text-align: center;
64 | width: 102px;
65 | height: 102px;
66 | background-color: #ddd;
67 | padding: 20px;
68 | }
69 |
70 | .win {
71 | text-align: center;
72 | }
73 |
74 | .reset {
75 | padding: 5px;
76 | }
77 |
78 | .game {
79 | display: flex;
80 | flex-direction: row;
81 | }
82 |
83 | .game-info {
84 | margin-left: 20px;
85 | }
86 |
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | font: 14px "Century Gothic", Futura, sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | .active {
7 | font-weight: 600;
8 | }
9 |
10 | .inactive {
11 | font-weight: normal;
12 | }
13 |
14 | ol, ul {
15 | padding-left: 30px;
16 | }
17 |
18 | .board-row:after {
19 | clear: both;
20 | content: "";
21 | display: table;
22 | }
23 |
24 | .status {
25 | margin-bottom: 10px;
26 | }
27 |
28 | .square {
29 | background: #fff;
30 | border: 1px solid #999;
31 | float: left;
32 | font-size: 24px;
33 | font-weight: bold;
34 | line-height: 34px;
35 | height: 34px;
36 | margin-right: -1px;
37 | margin-top: -1px;
38 | padding: 0;
39 | text-align: center;
40 | width: 34px;
41 | }
42 |
43 | .square:focus {
44 | outline: none;
45 | }
46 |
47 | .kbd-navigation .square:focus {
48 | background: #ddd;
49 | }
50 |
51 | .winningSquares {
52 | color: #000;
53 | background: rgb(142, 252, 99);
54 | }
55 |
56 | .draw {
57 | text-align: center;
58 | width: 102px;
59 | height: 102px;
60 | background-color: #ddd;
61 | padding: 20px;
62 | }
63 |
64 | .win {
65 | text-align: center;
66 | }
67 |
68 | .reset {
69 | padding: 5px;
70 | }
71 |
72 | .game {
73 | display: flex;
74 | flex-direction: row;
75 | }
76 |
77 | .game-info {
78 | margin-left: 20px;
79 | }
80 |
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
22 | React App
23 |
24 |
25 |
26 | You need to enable JavaScript to run this app.
27 |
28 |
29 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/src/components/Board.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import Square from "./Square";
3 | import "../index.css";
4 |
5 | class Board extends React.Component {
6 | highlightSquares = i => {
7 | if (this.props.winningSquares.length > 0) {
8 | if (this.props.winningSquares.indexOf(i) > -1) {
9 | return "square winningSquares";
10 | } else {
11 | return "square";
12 | }
13 | } else {
14 | return "square";
15 | }
16 | };
17 |
18 | renderSquare(i) {
19 | let highlight = this.highlightSquares(i);
20 | return (
21 | this.props.onClick(i)}
26 | />
27 | );
28 | }
29 |
30 | generateRow = (index, max) => {
31 | let rows = [];
32 |
33 | for (index; index < max; index++) {
34 | rows.push(this.renderSquare(index));
35 | }
36 | return rows;
37 | };
38 |
39 | generateBoard = (columns, rows) => {
40 | let board = [];
41 |
42 | /**
43 | * Generate (col * row, here, 3 * 3 = 9) squares
44 | */
45 | for (let i = 0; i < columns * rows; i++) {
46 | /**
47 | * Generate columns.
48 | *
49 | * Only allow multiples of "number of columns".
50 | * For example, if number of columns is 3, then,
51 | * 3, 6, 9.
52 | */
53 | if (i % columns === 0) {
54 | board.push(
55 |
56 | {this.generateRow(i, i + columns)}
57 |
58 | );
59 | }
60 | }
61 | return board;
62 | };
63 |
64 | render() {
65 | return (
66 |
67 |
{this.generateBoard(3, 3)}
68 |
69 | );
70 | }
71 | }
72 |
73 | export default Board;
74 |
--------------------------------------------------------------------------------
/src/components/Game.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import Board from "./Board";
3 | import "../index.css";
4 |
5 | class Game extends React.Component {
6 | /**
7 | * Initial state of the game
8 | */
9 | initialize = () => {
10 | return {
11 | history: [
12 | {
13 | squares: Array(9).fill(null),
14 | location: {
15 | col: 0,
16 | row: 0
17 | },
18 | active: false,
19 | moveNumber: 0
20 | }
21 | ],
22 | xIsNext: true,
23 | stepNumber: 0,
24 | toggle: false
25 | };
26 | };
27 |
28 | state = this.initialize();
29 |
30 | reset = () => {
31 | this.setState(this.initialize());
32 | };
33 |
34 | jumpTo = step => {
35 | let history = this.state.history;
36 |
37 | history.forEach(item => {
38 | item.active = false;
39 | });
40 |
41 | history[step].active = true;
42 | this.setState({
43 | history: history,
44 | stepNumber: step,
45 | xIsNext: step % 2 === 0
46 | });
47 | };
48 |
49 | handleClick = i => {
50 | /**
51 | * If we jumped to some previous step, and then make
52 | * a new move from that point, we throw away all "future"
53 | * history that will now become irrelevant.
54 | *
55 | * slice(startingPoint, endPoint)
56 | *
57 | * startingPoint - Array index from where the "slicing" starts.
58 | * endPoint - All array indices less than endPoint will be included in "slicing"
59 | */
60 | const history = this.state.history.slice(0, this.state.stepNumber + 1);
61 | const current = history[history.length - 1];
62 | const squares = current.squares.slice();
63 | const columns = 3;
64 |
65 | /**
66 | * Calculate location of square when clicked
67 | */
68 | const col = Math.floor(i % columns) + 1;
69 | const row = Math.floor(i / columns) + 1;
70 |
71 | if (this.calculateWinner(squares) || squares[i]) {
72 | return;
73 | }
74 |
75 | squares[i] = this.state.xIsNext ? "X" : "O";
76 |
77 | /**
78 | * concat() method does not mutate the Array
79 | * unlike Array.push().
80 | */
81 | this.setState(prevState => ({
82 | history: history.concat([
83 | {
84 | squares: squares,
85 | location: {
86 | col: col,
87 | row: row
88 | },
89 | active: false,
90 | moveNumber: history.length
91 | }
92 | ]),
93 | xIsNext: !prevState.xIsNext,
94 | stepNumber: history.length
95 | }));
96 | };
97 |
98 | toggleMoves = () => {
99 | const toggle = !this.state.toggle;
100 | this.setState({
101 | toggle: toggle
102 | });
103 | };
104 |
105 | calculateWinner = (squares) => {
106 | const lines = [
107 | [0, 1, 2],
108 | [3, 4, 5],
109 | [6, 7, 8],
110 | [0, 3, 6],
111 | [1, 4, 7],
112 | [2, 5, 8],
113 | [0, 4, 8],
114 | [2, 4, 6]
115 | ];
116 | let result = {
117 | status: "",
118 | win: {}
119 | };
120 | for (let i = 0; i < lines.length; i++) {
121 | const [a, b, c] = lines[i];
122 | if (
123 | squares[a] &&
124 | squares[a] === squares[b] &&
125 | squares[a] === squares[c]
126 | ) {
127 | result = {
128 | status: "win",
129 | win: { player: squares[a], squares: [a, b, c] }
130 | };
131 | return result;
132 | }
133 | }
134 | let tempSq = squares.filter(item => item === null);
135 | if (tempSq.length === 0) {
136 | result = { status: "draw", win: {} };
137 | return result;
138 | }
139 | return null;
140 | };
141 |
142 | render() {
143 | const history = this.state.history;
144 | const current = history[this.state.stepNumber];
145 | const result = this.calculateWinner(current.squares);
146 | const gameStatus = result && result.status ? result.status : null;
147 |
148 | const moves = history.map((move, index) => {
149 | const desc = index ? "Go to move #" + index : "Go to game start";
150 |
151 | let active = "";
152 | if (move.active) {
153 | active = "active";
154 | } else {
155 | active = "normal";
156 | }
157 | return (
158 |
159 | this.jumpTo(index)}
163 | >
164 | {`${desc} (${move.location.col}, ${move.location.row})`}
165 |
166 |
167 | );
168 | });
169 |
170 | /**
171 | * If this.state.toggle is "true", sort in
172 | * "decending order" and vice versa.
173 | */
174 | moves.sort((a, b) => {
175 | if (this.state.toggle) {
176 | return b.key - a.key;
177 | } else {
178 | return a.key - b.key;
179 | }
180 | });
181 |
182 | let status;
183 |
184 | if (gameStatus === "win") {
185 | status = `Winner: ${result.win.player}`;
186 | } else {
187 | status = "Next player: " + (this.state.xIsNext ? "X" : "O");
188 | }
189 | return (
190 |
191 | {/** If there is a draw, hide the game board and show
192 | "Play again" button */
193 | gameStatus === "draw" ? (
194 |
195 |
Draw!
196 | this.reset()}>Play again
197 |
198 | ) : (
199 | /** Otherwise, show the game board */
200 |
201 |
this.handleClick(i, col, row)}
205 | />
206 | {/** Depending upon the state of the game, either show
207 | "Play again" button or "Reset game" button */
208 | gameStatus === "win" ? (
209 |
210 |
{`"${result.win.player}" is winner!`}
211 | this.reset()}>Play again
212 |
213 | ) : (
214 |
215 | this.reset()}>Reset game
216 |
217 | )}
218 |
219 | )}
220 |
221 |
222 |
{status}
223 | {/** Show the toggle button only if there are two or more moves to sort */
224 | history.length > 1 ? (
225 |
this.toggleMoves()}>Toggle moves
226 | ) : (
227 | ""
228 | )}
229 |
{moves}
230 |
231 |
232 | );
233 | }
234 | }
235 |
236 | export default Game;
237 |
--------------------------------------------------------------------------------