Merge branch 'master' into new_master

master
Tudor Stanciu 2022-11-21 02:02:05 +02:00
commit 0f8d4bf3d7
20 changed files with 16114 additions and 0 deletions

2
.env Normal file
View File

@ -0,0 +1,2 @@
PUBLIC_URL=/play-nine/
PORT=3006

23
.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

68
README.md Normal file
View File

@ -0,0 +1,68 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br>
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br>
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br>
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.<br>
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.<br>
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 cant go back!**
If you arent 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 youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt 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).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `npm run build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

23
dockerfile Normal file
View File

@ -0,0 +1,23 @@
# build environment
FROM node:12 as builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . ./
RUN npm run build
# production environment
FROM node:12
RUN printf '\n\n- Copy application files\n'
ARG APP_SUBFOLDER=play-nine
COPY --from=builder /app/build ./application/${APP_SUBFOLDER}
COPY --from=builder /app/build/index.html ./application/
RUN npm install -g serve@11.3.0
EXPOSE 80
CMD ["sh","-c","serve -s application -p 80"]

15375
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

39
package.json Normal file
View File

@ -0,0 +1,39 @@
{
"name": "play-nine",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"bootstrap": "^4.3.1",
"font-awesome": "^4.7.0",
"lodash": "^4.17.15",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-fontawesome": "^1.7.1",
"react-router-dom": "^5.0.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

41
public/index.html Normal file
View File

@ -0,0 +1,41 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Play Nine</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

15
public/manifest.json Normal file
View File

@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

20
src/components/App.js Normal file
View File

@ -0,0 +1,20 @@
import React from "react";
import Game from "./game";
import PageNotFound from "./PageNotFound";
import { Route, Switch } from "react-router-dom";
class App extends React.Component {
state = {};
render() {
return (
<div>
<Switch>
<Route exact path="/" component={Game} />
<Route component={PageNotFound} />
</Switch>
</div>
);
}
}
export default App;

View File

@ -0,0 +1,5 @@
import React from "react";
const PageNotFound = () => <h1>Oops! Page not found</h1>;
export default PageNotFound;

15
src/components/answer.jsx Normal file
View File

@ -0,0 +1,15 @@
import React from "react";
const Answer = props => {
return (
<div className="col-5">
{props.selectedNumbers.map((number, i) => (
<span key={i} onClick={() => props.unselectNumber(number)}>
{number}
</span>
))}
</div>
);
};
export default Answer;

49
src/components/button.jsx Normal file
View File

@ -0,0 +1,49 @@
import React from "react";
const Button = props => {
let button;
switch (props.answerIsCorrect) {
case true:
button = (
<button className="btn btn-success" onClick={props.acceptAnswer}>
<i className="fa fa-check" />
</button>
);
break;
case false:
button = (
<button className="btn btn-danger">
<i className="fa fa-times" />
</button>
);
break;
default:
button = (
<button
className="btn btn-primary"
onClick={props.checkAnswer}
disabled={props.selectedNumbers.length === 0}
>
=
</button>
);
break;
}
return (
<div className="col-2 text-center">
{button}
<br />
<br />
<button
className="btn btn-warning btn-sm"
onClick={props.redraw}
disabled={props.redraws === 0}
>
<i className="fa fa-refresh" /> {props.redraws}
</button>
</div>
);
};
export default Button;

View File

@ -0,0 +1,14 @@
import React from "react";
const DoneFrame = props => {
return (
<div className="text-center">
<h2>{props.doneStatus}</h2>
<button className="btn btn-outline-secondary" onClick={props.resetGame}>
Play Again
</button>
</div>
);
};
export default DoneFrame;

184
src/components/game.jsx Normal file
View File

@ -0,0 +1,184 @@
import React, { Component } from "react";
import _ from "lodash";
import Stars from "./stars";
import Button from "./button";
import Numbers from "./numbers";
import Answer from "./answer";
import DoneFrame from "./doneFrame";
var possibleCombinationSum = function(arr, n) {
if (arr.indexOf(n) >= 0) {
return true;
}
if (arr[0] > n) {
return false;
}
if (arr[arr.length - 1] > n) {
arr.pop();
return possibleCombinationSum(arr, n);
}
var listSize = arr.length,
combinationsCount = 1 << listSize;
for (var i = 1; i < combinationsCount; i++) {
var combinationSum = 0;
for (var j = 0; j < listSize; j++) {
if (i & (1 << j)) {
combinationSum += arr[j];
}
}
if (n === combinationSum) {
return true;
}
}
return false;
};
class Game extends Component {
static randomNumber = lastNumberOfStars => {
var randomNo = 1 + Math.floor(Math.random() * 9);
if (lastNumberOfStars == null) {
return randomNo;
}
while (randomNo === lastNumberOfStars) {
randomNo = 1 + Math.floor(Math.random() * 9);
}
return randomNo;
};
static initialState = () => ({
selectedNumbers: [],
randomNumberOfStars: Game.randomNumber(null),
usedNumbers: [],
answerIsCorrect: null,
redraws: 5,
doneStatus: null
});
state = Game.initialState();
resetGame = () => this.setState(Game.initialState());
selectNumber = clickedNumber => {
if (
this.state.selectedNumbers.indexOf(clickedNumber) >= 0 ||
this.state.usedNumbers.indexOf(clickedNumber) >= 0
) {
return;
}
this.setState(prevState => ({
answerIsCorrect: null,
selectedNumbers: prevState.selectedNumbers.concat(clickedNumber)
}));
};
unselectNumber = clickedNumber => {
this.setState(prevState => ({
answerIsCorrect: null,
selectedNumbers: prevState.selectedNumbers.filter(
number => number !== clickedNumber
)
}));
};
checkAnswer = () => {
this.setState(prevState => ({
answerIsCorrect:
prevState.randomNumberOfStars ===
prevState.selectedNumbers.reduce((acc, n) => acc + n, 0)
}));
};
acceptAnswer = () => {
this.setState(
prevState => ({
usedNumbers: prevState.usedNumbers.concat(prevState.selectedNumbers),
selectedNumbers: [],
randomNumberOfStars: Game.randomNumber(prevState.randomNumberOfStars),
answerIsCorrect: null
}),
this.updateDoneStatus
);
};
redraw = () => {
if (this.state.redraws === 0) return;
this.setState(
prevState => ({
selectedNumbers: [],
randomNumberOfStars: Game.randomNumber(prevState.randomNumberOfStars),
answerIsCorrect: null,
redraws: prevState.redraws - 1
}),
this.updateDoneStatus
);
};
possibleSolutions = ({ randomNumberOfStars, usedNumbers }) => {
const possibleNumbers = _.range(1, 10).filter(
number => usedNumbers.indexOf(number) === -1
);
return possibleCombinationSum(possibleNumbers, randomNumberOfStars);
};
updateDoneStatus = () => {
this.setState(prevState => {
if (prevState.usedNumbers.length === 9) {
return { doneStatus: "Done. Nice!" };
}
if (prevState.redraws === 0 && !this.possibleSolutions(prevState)) {
return { doneStatus: "Game Over!" };
}
});
};
render() {
const {
selectedNumbers,
randomNumberOfStars,
answerIsCorrect,
usedNumbers,
redraws,
doneStatus
} = this.state;
return (
<div className="container">
<h3>Play Nine</h3>
<hr />
<div className="row">
<Stars numberOfStars={randomNumberOfStars} />
<Button
selectedNumbers={selectedNumbers}
checkAnswer={this.checkAnswer}
answerIsCorrect={answerIsCorrect}
acceptAnswer={this.acceptAnswer}
redraw={this.redraw}
redraws={redraws}
/>
<Answer
selectedNumbers={selectedNumbers}
unselectNumber={this.unselectNumber}
/>
</div>
<br />
{doneStatus ? (
<DoneFrame doneStatus={doneStatus} resetGame={this.resetGame} />
) : (
<Numbers
selectedNumbers={selectedNumbers}
selectNumber={this.selectNumber}
usedNumbers={usedNumbers}
/>
)}
</div>
);
}
}
export default Game;

View File

@ -0,0 +1,33 @@
import React from "react";
import _ from "lodash";
const Numbers = props => {
const numberClassName = number => {
if (props.usedNumbers.indexOf(number) >= 0) {
return "used";
}
if (props.selectedNumbers.indexOf(number) >= 0) {
return "selected";
}
};
return (
<div className="card text-center">
<div>
{Numbers.list.map((number, i) => (
<span
key={i}
className={numberClassName(number)}
onClick={() => props.selectNumber(number)}
>
{number}
</span>
))}
</div>
</div>
);
};
Numbers.list = _.range(1, 10);
export default Numbers;

14
src/components/stars.jsx Normal file
View File

@ -0,0 +1,14 @@
import React from "react";
import _ from "lodash";
const Stars = props => {
return (
<div className="col-5">
{_.range(props.numberOfStars).map(j => (
<i key={j} className="fa fa-star" />
))}
</div>
);
};
export default Stars;

41
src/index.css Normal file
View File

@ -0,0 +1,41 @@
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;
}
.fa-star {
margin: 0.5em;
font-size: 24px;
}
span {
display: inline-block;
margin: 0.5em;
text-align: center;
background-color: #ccc;
width: 24px;
border-radius: 50%;
cursor: pointer;
}
.selected {
background-color: #eee;
color: #ddd;
cursor: not-allowed;
}
.used {
background-color: #aaddaa;
color: #99bb99;
cursor: not-allowed;
}

18
src/index.js Normal file
View File

@ -0,0 +1,18 @@
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./components/App";
import * as serviceWorker from "./serviceWorker";
import "font-awesome/css/font-awesome.min.css";
import "bootstrap/dist/css/bootstrap.css";
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<BrowserRouter basename={process.env.PUBLIC_URL}><App /></BrowserRouter>,
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();

135
src/serviceWorker.js Normal file
View File

@ -0,0 +1,135 @@
// 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();
});
}
}