diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..f6b35a0 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,15 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "chrome", + "request": "launch", + "name": "Launch Chrome against localhost", + "url": "http://localhost:3000", + "webRoot": "${workspaceFolder}" + } + ] +} \ No newline at end of file diff --git a/README.md b/README.md index 897dc83..64433e2 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +Solutions to additional problems given in React's "tic tac toe" tutorial. + This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts @@ -12,33 +14,6 @@ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.
You will also see any lint errors in the console. -### `npm test` - -Launches the test runner in the interactive watch mode.
-See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. - -### `npm run build` - -Builds the app for production to the `build` folder.
-It correctly bundles React in production mode and optimizes the build for the best performance. - -The build is minified and the filenames include the hashes.
-Your app is ready to be deployed! - -See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. - -### `npm run eject` - -**Note: this is a one-way operation. Once you `eject`, you can’t go back!** - -If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. - -Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. - -You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. - -## Learn More - -You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). +### `Useful links` -To learn React, check out the [React documentation](https://reactjs.org/). +Tutorial page: [React documentation](https://reactjs.org/tutorial/tutorial.html). diff --git a/src/App.css b/src/App.css deleted file mode 100644 index 92f956e..0000000 --- a/src/App.css +++ /dev/null @@ -1,32 +0,0 @@ -.App { - text-align: center; -} - -.App-logo { - animation: App-logo-spin infinite 20s linear; - height: 40vmin; -} - -.App-header { - background-color: #282c34; - min-height: 100vh; - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - font-size: calc(10px + 2vmin); - color: white; -} - -.App-link { - color: #61dafb; -} - -@keyframes App-logo-spin { - from { - transform: rotate(0deg); - } - to { - transform: rotate(360deg); - } -} diff --git a/src/App.js b/src/App.js deleted file mode 100644 index 7e261ca..0000000 --- a/src/App.js +++ /dev/null @@ -1,28 +0,0 @@ -import React, { Component } from 'react'; -import logo from './logo.svg'; -import './App.css'; - -class App extends Component { - render() { - return ( -
-
- logo -

- Edit src/App.js and save to reload. -

- - Learn React - -
-
- ); - } -} - -export default App; diff --git a/src/App.test.js b/src/App.test.js deleted file mode 100644 index a754b20..0000000 --- a/src/App.test.js +++ /dev/null @@ -1,9 +0,0 @@ -import React from 'react'; -import ReactDOM from 'react-dom'; -import App from './App'; - -it('renders without crashing', () => { - const div = document.createElement('div'); - ReactDOM.render(, div); - ReactDOM.unmountComponentAtNode(div); -}); diff --git a/src/index.css b/src/index.css index cee5f34..90b4cd2 100644 --- a/src/index.css +++ b/src/index.css @@ -1,14 +1,80 @@ body { - margin: 0; - padding: 0; - font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", - "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", - sans-serif; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -code { - font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", - monospace; -} + font: 14px "Century Gothic", Futura, sans-serif; + margin: 20px; + } + + .active { + font-weight: 600; + } + + .inactive { + font-weight: normal; + } + + ol, ul { + padding-left: 30px; + } + + .board-row:after { + clear: both; + content: ""; + display: table; + } + + .status { + margin-bottom: 10px; + } + + .square { + background: #fff; + border: 1px solid #999; + float: left; + font-size: 24px; + font-weight: bold; + line-height: 34px; + height: 34px; + margin-right: -1px; + margin-top: -1px; + padding: 0; + text-align: center; + width: 34px; + } + + .square:focus { + outline: none; + } + + .kbd-navigation .square:focus { + background: #ddd; + } + + .winningSquares { + color: #000; + background: rgb(142, 252, 99); + } + + .draw { + text-align: center; + width: 102px; + height: 102px; + background-color: #ddd; + padding: 20px; + } + + .win { + text-align: center; + } + + .reset { + padding: 5px; + } + + .game { + display: flex; + flex-direction: row; + } + + .game-info { + margin-left: 20px; + } + \ No newline at end of file diff --git a/src/index.js b/src/index.js index 0c5e75d..a124201 100644 --- a/src/index.js +++ b/src/index.js @@ -1,12 +1,304 @@ -import React from 'react'; -import ReactDOM from 'react-dom'; -import './index.css'; -import App from './App'; -import * as serviceWorker from './serviceWorker'; - -ReactDOM.render(, document.getElementById('root')); - -// If you want your app to work offline and load faster, you can change -// unregister() to register() below. Note this comes with some pitfalls. -// Learn more about service workers: http://bit.ly/CRA-PWA -serviceWorker.unregister(); +import React from "react"; +import ReactDOM from "react-dom"; +import "./index.css"; + +const Square = props => { + return ( + + ); +}; + +class Board extends React.Component { + highlightSquares = i => { + if (this.props.winningSquares.length > 0) { + if (this.props.winningSquares.indexOf(i) > -1) { + return "square winningSquares"; + } else { + return "square"; + } + } else { + return "square"; + } + }; + + renderSquare(i) { + let highlight = this.highlightSquares(i); + return ( + this.props.onClick(i)} + /> + ); + } + + generateRow = (index, max) => { + let rows = []; + + for (index; index < max; index++) { + rows.push(this.renderSquare(index)); + } + return rows; + }; + + generateBoard = (columns, rows) => { + let board = []; + + /** + * Generate (col * row, here, 3 * 3 = 9) squares + */ + for (let i = 0; i < columns * rows; i++) { + /** + * Generate columns. + * + * Only allow multiples of "number of columns". + * For example, if number of columns is 3, then, + * 3, 6, 9. + */ + if (i % columns === 0) { + board.push( +
+ {this.generateRow(i, i + columns)} +
+ ); + } + } + return board; + }; + + render() { + return ( +
+
{this.generateBoard(3, 3)}
+
+ ); + } +} + +class Game extends React.Component { + initialize = () => { + return { + history: [ + { + squares: Array(9).fill(null), + location: { col: 0, row: 0 }, + active: false, + moveNumber: 0 + } + ], + xIsNext: true, + stepNumber: 0, + toggle: false + }; + }; + + state = this.initialize(); + + reset = () => { + this.setState(this.initialize()); + }; + + jumpTo = step => { + let history = this.state.history.slice(); + + history.forEach(item => { + item.active = false; + }); + + history[step].active = true; + this.setState({ + history: history, + stepNumber: step, + xIsNext: step % 2 === 0 + }); + }; + + handleClick = i => { + /** + * If we jumped to some previous step, and then make + * a new move from that point, we throw away all "future" + * history that will now become irrelevant. + * + * slice(startingPoint, endPoint) + * + * startingPoint - Array index from which we want to start "slicing" + * endPoint - Array index less than this will be included in the "slicing" + */ + const history = this.state.history.slice(0, this.state.stepNumber + 1); + const current = history[history.length - 1]; + const squares = current.squares.slice(); + const columns = 3; + + /** + * Calculate location of square when clicked + */ + + const col = Math.floor(i % columns) + 1; + const row = Math.floor(i / columns) + 1; + + if (calculateWinner(squares) || squares[i]) { + return; + } + + squares[i] = this.state.xIsNext ? "X" : "O"; + + /** + * concat() method does not mutate the Array + * unlike Array.push(). + */ + this.setState(prevState => ({ + history: history.concat([ + { + squares: squares, + location: { + col: col, + row: row + }, + active: false, + moveNumber: history.length + } + ]), + xIsNext: !prevState.xIsNext, + stepNumber: history.length + })); + }; + + toggleMoves = () => { + const toggle = !this.state.toggle; + // const history = this.state.history; + // history.sort(function(a, b) { + // if (toggle) { + // return b.moveNumber - a.moveNumber; + // } else { + // return a.moveNumber - b.moveNumber; + // } + // }); + this.setState({ + toggle: toggle + }); + }; + + render() { + const history = this.state.history; + const current = history[this.state.stepNumber]; + const result = calculateWinner(current.squares); + const gameStatus = result && result.status ? result.status : null; + + const moves = history.map((move, index) => { + const desc = index ? "Go to move #" + index : "Go to game start"; + + let active = ""; + if (move.active) { + active = "active"; + } else { + active = "normal"; + } + return ( +
  • + +
  • + ); + }); + + moves.sort((a, b) => { + if (this.state.toggle) { + return b.key - a.key; + } else { + return a.key - b.key; + } + }); + + let status; + + if (gameStatus === "win") { + status = `Winner: ${result.win.player}`; + } else { + status = "Next player: " + (this.state.xIsNext ? "X" : "O"); + } + return ( +
    + {gameStatus === "draw" ? ( +
    +

    Draw!

    + +
    + ) : ( +
    + this.handleClick(i, col, row)} + /> + {gameStatus === "win" ? ( +
    +

    {`${result.win.player} wins!`}

    + +
    + ) : ( +
    + +
    + )} +
    + )} + +
    +
    {status}
    + {history.length > 1 ? ( + + ) : ( + "" + )} +
      {moves}
    +
    +
    + ); + } +} + +// ======================================== + +ReactDOM.render(, document.getElementById("root")); + +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] + ]; + let result = { status: "", win: {} }; + 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]) { + result = { + status: "win", + win: { player: squares[a], squares: [a, b, c] } + }; + return result; + } else { + let tempSq = squares.filter(item => item === null); + if (tempSq.length === 0) { + result = { status: "draw", win: {} }; + return result; + } + } + } + return null; +} diff --git a/src/logo.svg b/src/logo.svg deleted file mode 100644 index 6b60c10..0000000 --- a/src/logo.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/src/serviceWorker.js b/src/serviceWorker.js deleted file mode 100644 index 2283ff9..0000000 --- a/src/serviceWorker.js +++ /dev/null @@ -1,135 +0,0 @@ -// This optional code is used to register a service worker. -// register() is not called by default. - -// This lets the app load faster on subsequent visits in production, and gives -// it offline capabilities. However, it also means that developers (and users) -// will only see deployed updates on subsequent visits to a page, after all the -// existing tabs open on the page have been closed, since previously cached -// resources are updated in the background. - -// To learn more about the benefits of this model and instructions on how to -// opt-in, read http://bit.ly/CRA-PWA - -const isLocalhost = Boolean( - window.location.hostname === 'localhost' || - // [::1] is the IPv6 localhost address. - window.location.hostname === '[::1]' || - // 127.0.0.1/8 is considered localhost for IPv4. - window.location.hostname.match( - /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ - ) -); - -export function register(config) { - if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { - // The URL constructor is available in all browsers that support SW. - const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); - if (publicUrl.origin !== window.location.origin) { - // Our service worker won't work if PUBLIC_URL is on a different origin - // from what our page is served on. This might happen if a CDN is used to - // serve assets; see https://github.com/facebook/create-react-app/issues/2374 - return; - } - - window.addEventListener('load', () => { - const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; - - if (isLocalhost) { - // This is running on localhost. Let's check if a service worker still exists or not. - checkValidServiceWorker(swUrl, config); - - // Add some additional logging to localhost, pointing developers to the - // service worker/PWA documentation. - navigator.serviceWorker.ready.then(() => { - console.log( - 'This web app is being served cache-first by a service ' + - 'worker. To learn more, visit http://bit.ly/CRA-PWA' - ); - }); - } else { - // Is not localhost. Just register service worker - registerValidSW(swUrl, config); - } - }); - } -} - -function registerValidSW(swUrl, config) { - navigator.serviceWorker - .register(swUrl) - .then(registration => { - registration.onupdatefound = () => { - const installingWorker = registration.installing; - if (installingWorker == null) { - return; - } - installingWorker.onstatechange = () => { - if (installingWorker.state === 'installed') { - if (navigator.serviceWorker.controller) { - // At this point, the updated precached content has been fetched, - // but the previous service worker will still serve the older - // content until all client tabs are closed. - console.log( - 'New content is available and will be used when all ' + - 'tabs for this page are closed. See http://bit.ly/CRA-PWA.' - ); - - // Execute callback - if (config && config.onUpdate) { - config.onUpdate(registration); - } - } else { - // At this point, everything has been precached. - // It's the perfect time to display a - // "Content is cached for offline use." message. - console.log('Content is cached for offline use.'); - - // Execute callback - if (config && config.onSuccess) { - config.onSuccess(registration); - } - } - } - }; - }; - }) - .catch(error => { - console.error('Error during service worker registration:', error); - }); -} - -function checkValidServiceWorker(swUrl, config) { - // Check if the service worker can be found. If it can't reload the page. - fetch(swUrl) - .then(response => { - // Ensure service worker exists, and that we really are getting a JS file. - const contentType = response.headers.get('content-type'); - if ( - response.status === 404 || - (contentType != null && contentType.indexOf('javascript') === -1) - ) { - // No service worker found. Probably a different app. Reload the page. - navigator.serviceWorker.ready.then(registration => { - registration.unregister().then(() => { - window.location.reload(); - }); - }); - } else { - // Service worker found. Proceed as normal. - registerValidSW(swUrl, config); - } - }) - .catch(() => { - console.log( - 'No internet connection found. App is running in offline mode.' - ); - }); -} - -export function unregister() { - if ('serviceWorker' in navigator) { - navigator.serviceWorker.ready.then(registration => { - registration.unregister(); - }); - } -}