diff --git a/README.md b/README.md deleted file mode 100644 index ee32a43..0000000 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# chess-clock -Created with CodeSandbox diff --git a/package.json b/package.json new file mode 100644 index 0000000..37a5ad2 --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "new", + "version": "1.0.0", + "description": "", + "keywords": [], + "main": "src/index.js", + "dependencies": { + "react": "16.3.2", + "react-dom": "16.3.2", + "react-scripts": "1.1.4" + }, + "devDependencies": {}, + "scripts": { + "start": "react-scripts start", + "build": "react-scripts build", + "test": "react-scripts test --env=jsdom", + "eject": "react-scripts eject" + } +} diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..42ae2d2 --- /dev/null +++ b/public/index.html @@ -0,0 +1,43 @@ + + + + + + + + + + + + React App + + + + +
+ + + + \ No newline at end of file diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..02ba307 --- /dev/null +++ b/src/index.js @@ -0,0 +1,105 @@ +import React from "react"; +import ReactDOM from "react-dom"; + +import "./styles.css"; + +const INITIAL_TIME = 10000; +const INCREMENT = 3000; +const INTERVAL = 100; +const PLAYER_1 = "player1"; +const PLAYER_2 = "player2"; + +class App extends React.Component { + state = { + [PLAYER_1]: INITIAL_TIME, + [PLAYER_2]: INITIAL_TIME, + currentPlayer: PLAYER_1, + timer: undefined, + isNewGame: true + }; + + render() { + const { currentPlayer, timer } = this.state; + + return ( +
+

+ Player 1: {this.state[PLAYER_1] / 1000} +

+

+ Player 2: {this.state[PLAYER_2] / 1000} +

+ + +
+ ); + } + + otherPlayer = player => (player === PLAYER_1 ? PLAYER_2 : PLAYER_1); + + changePlayer = player => { + const otherPlayer = this.otherPlayer(player); + + this.setState(state => ({ + [otherPlayer]: state[otherPlayer] + INCREMENT, + currentPlayer: otherPlayer + })); + }; + + decreaseTime = player => { + this.setState( + state => ({ + [player]: Math.max(state[player] - INTERVAL, 0) + }), + () => { + if (this.state[player] === 0) { + this.changePlayer(player); + } + } + ); + }; + + createTimer = () => { + return setInterval(() => { + this.decreaseTime(this.state.currentPlayer); + }, INTERVAL); + }; + + playPauseGame = () => { + this.setState(state => { + const { timer: oldTimer, isNewGame } = state; + + const newState = isNewGame + ? { + [PLAYER_1]: state[PLAYER_1] + INCREMENT, + isNewGame: false + } + : {}; + + if (oldTimer == null) { + return { + ...newState, + timer: this.createTimer() + }; + } + + clearInterval(oldTimer); + return { + ...newState, + timer: undefined + }; + }); + }; +} + +const rootElement = document.getElementById("root"); +ReactDOM.render(, rootElement); diff --git a/src/styles.css b/src/styles.css new file mode 100644 index 0000000..00c02b7 --- /dev/null +++ b/src/styles.css @@ -0,0 +1,8 @@ +.App { + font-family: sans-serif; + text-align: center; +} + +.Current { + background: red; +}