Adding a Colyseus based version

This commit is contained in:
2021-01-29 15:52:45 +01:00
parent 132fb3a3c1
commit 5e020810ae
51 changed files with 15653 additions and 82 deletions

File diff suppressed because one or more lines are too long

23
games-party/client/.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*

View File

@@ -0,0 +1,70 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.\
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.
### `yarn 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.
### `yarn 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.
### `yarn 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](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](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](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](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](https://facebook.github.io/create-react-app/docs/deployment)
### `yarn build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

View File

@@ -0,0 +1,52 @@
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"@types/jest": "^26.0.19",
"@types/node": "^14.14.19",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"@types/simple-peer": "^9.6.1",
"antd": "^4.9.4",
"colyseus.js": "^0.14.1",
"http-proxy-middleware": "^1.0.6",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-full-screen": "^0.3.2-0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.1",
"simple-peer": "^9.9.3",
"typescript": "^4.1.3",
"uuid": "^8.3.2",
"web-vitals": "^0.2.4",
"wouter": "^2.7.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@@ -0,0 +1,50 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Web site created using create-react-app" />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. 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`.
-->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Paytone+One&display=swap" rel="stylesheet">
<title>Chemmazz!</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>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

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

View File

@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@@ -0,0 +1,214 @@
html, body, #root {
height: 100%;
}
.App {
height: 100%;
font-family: 'Paytone One', sans-serif;
color: whitesmoke;
}
.bg-1 {
background-color: #ff9d00;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%25' height='100%25' viewBox='0 0 1600 800'%3E%3Cg stroke='%23000' stroke-width='66.7' stroke-opacity='0.05' %3E%3Ccircle fill='%23ff9d00' cx='0' cy='0' r='1800'/%3E%3Ccircle fill='%23fb8d17' cx='0' cy='0' r='1700'/%3E%3Ccircle fill='%23f47d24' cx='0' cy='0' r='1600'/%3E%3Ccircle fill='%23ed6e2d' cx='0' cy='0' r='1500'/%3E%3Ccircle fill='%23e35f34' cx='0' cy='0' r='1400'/%3E%3Ccircle fill='%23d85239' cx='0' cy='0' r='1300'/%3E%3Ccircle fill='%23cc453e' cx='0' cy='0' r='1200'/%3E%3Ccircle fill='%23be3941' cx='0' cy='0' r='1100'/%3E%3Ccircle fill='%23b02f43' cx='0' cy='0' r='1000'/%3E%3Ccircle fill='%23a02644' cx='0' cy='0' r='900'/%3E%3Ccircle fill='%23901e44' cx='0' cy='0' r='800'/%3E%3Ccircle fill='%23801843' cx='0' cy='0' r='700'/%3E%3Ccircle fill='%236f1341' cx='0' cy='0' r='600'/%3E%3Ccircle fill='%235e0f3d' cx='0' cy='0' r='500'/%3E%3Ccircle fill='%234e0c38' cx='0' cy='0' r='400'/%3E%3Ccircle fill='%233e0933' cx='0' cy='0' r='300'/%3E%3Ccircle fill='%232e062c' cx='0' cy='0' r='200'/%3E%3Ccircle fill='%23210024' cx='0' cy='0' r='100'/%3E%3C/g%3E%3C/svg%3E");
background-attachment: fixed;
background-size: cover;
}
.bg-2 {
background-color: #330055;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 1000'%3E%3Cg %3E%3Ccircle fill='%23330055' cx='50' cy='0' r='50'/%3E%3Cg fill='%233a015d' %3E%3Ccircle cx='0' cy='50' r='50'/%3E%3Ccircle cx='100' cy='50' r='50'/%3E%3C/g%3E%3Ccircle fill='%23410165' cx='50' cy='100' r='50'/%3E%3Cg fill='%2348026e' %3E%3Ccircle cx='0' cy='150' r='50'/%3E%3Ccircle cx='100' cy='150' r='50'/%3E%3C/g%3E%3Ccircle fill='%23500376' cx='50' cy='200' r='50'/%3E%3Cg fill='%2357047e' %3E%3Ccircle cx='0' cy='250' r='50'/%3E%3Ccircle cx='100' cy='250' r='50'/%3E%3C/g%3E%3Ccircle fill='%235f0587' cx='50' cy='300' r='50'/%3E%3Cg fill='%2367068f' %3E%3Ccircle cx='0' cy='350' r='50'/%3E%3Ccircle cx='100' cy='350' r='50'/%3E%3C/g%3E%3Ccircle fill='%236f0798' cx='50' cy='400' r='50'/%3E%3Cg fill='%237707a0' %3E%3Ccircle cx='0' cy='450' r='50'/%3E%3Ccircle cx='100' cy='450' r='50'/%3E%3C/g%3E%3Ccircle fill='%238008a9' cx='50' cy='500' r='50'/%3E%3Cg fill='%238909b1' %3E%3Ccircle cx='0' cy='550' r='50'/%3E%3Ccircle cx='100' cy='550' r='50'/%3E%3C/g%3E%3Ccircle fill='%239109ba' cx='50' cy='600' r='50'/%3E%3Cg fill='%239a09c3' %3E%3Ccircle cx='0' cy='650' r='50'/%3E%3Ccircle cx='100' cy='650' r='50'/%3E%3C/g%3E%3Ccircle fill='%23a309cb' cx='50' cy='700' r='50'/%3E%3Cg fill='%23ad09d4' %3E%3Ccircle cx='0' cy='750' r='50'/%3E%3Ccircle cx='100' cy='750' r='50'/%3E%3C/g%3E%3Ccircle fill='%23b608dc' cx='50' cy='800' r='50'/%3E%3Cg fill='%23c007e5' %3E%3Ccircle cx='0' cy='850' r='50'/%3E%3Ccircle cx='100' cy='850' r='50'/%3E%3C/g%3E%3Ccircle fill='%23c905ee' cx='50' cy='900' r='50'/%3E%3Cg fill='%23d303f6' %3E%3Ccircle cx='0' cy='950' r='50'/%3E%3Ccircle cx='100' cy='950' r='50'/%3E%3C/g%3E%3Ccircle fill='%23D0F' cx='50' cy='1000' r='50'/%3E%3C/g%3E%3C/svg%3E");
background-attachment: fixed;
background-size: contain;
}
.bg-3 {
background-color: #66ff77;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%25' height='100%25' viewBox='0 0 1000 1000'%3E%3Cdefs%3E%3CradialGradient id='a' cx='500' cy='500' r='975' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0' stop-color='%2366ff77'/%3E%3Cstop offset='1' stop-color='%23240'/%3E%3C/radialGradient%3E%3CradialGradient id='b' cx='500' cy='500' r='975' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0' stop-color='%23EF5' stop-opacity='1'/%3E%3Cstop offset='1' stop-color='%23EF5' stop-opacity='0'/%3E%3C/radialGradient%3E%3C/defs%3E%3Crect fill='url(%23a)' width='1000' height='1000'/%3E%3Cg fill='none' stroke='%23081' stroke-width='10' stroke-miterlimit='10' stroke-opacity='.2'%3E%3Cpolygon points='-500%2C500 500%2C-500 1500%2C500 500%2C1500'/%3E%3Cpolygon points='-475%2C500 500%2C-475 1475%2C500 500%2C1475'/%3E%3Cpolygon points='-450%2C500 500%2C-450 1450%2C500 500%2C1450'/%3E%3Cpolygon points='-425%2C500 500%2C-425 1425%2C500 500%2C1425'/%3E%3Cpolygon points='-400%2C500 500%2C-400 1400%2C500 500%2C1400'/%3E%3Cpolygon points='-375%2C500 500%2C-375 1375%2C500 500%2C1375'/%3E%3Cpolygon points='-350%2C500 500%2C-350 1350%2C500 500%2C1350'/%3E%3Cpolygon points='-325%2C500 500%2C-325 1325%2C500 500%2C1325'/%3E%3Cpolygon points='-300%2C500 500%2C-300 1300%2C500 500%2C1300'/%3E%3Cpolygon points='-275%2C500 500%2C-275 1275%2C500 500%2C1275'/%3E%3Cpolygon points='-250%2C500 500%2C-250 1250%2C500 500%2C1250'/%3E%3Cpolygon points='-225%2C500 500%2C-225 1225%2C500 500%2C1225'/%3E%3Cpolygon points='-200%2C500 500%2C-200 1200%2C500 500%2C1200'/%3E%3Cpolygon points='-175%2C500 500%2C-175 1175%2C500 500%2C1175'/%3E%3Cpolygon points='-150%2C500 500%2C-150 1150%2C500 500%2C1150'/%3E%3Cpolygon points='-125%2C500 500%2C-125 1125%2C500 500%2C1125'/%3E%3Cpolygon points='-100%2C500 500%2C-100 1100%2C500 500%2C1100'/%3E%3Cpolygon points='-75%2C500 500%2C-75 1075%2C500 500%2C1075'/%3E%3Cpolygon points='-50%2C500 500%2C-50 1050%2C500 500%2C1050'/%3E%3Cpolygon points='-25%2C500 500%2C-25 1025%2C500 500%2C1025'/%3E%3Cpolygon points='0%2C500 500%2C0 1000%2C500 500%2C1000'/%3E%3Cpolygon points='25%2C500 500%2C25 975%2C500 500%2C975'/%3E%3Cpolygon points='50%2C500 500%2C50 950%2C500 500%2C950'/%3E%3Cpolygon points='75%2C500 500%2C75 925%2C500 500%2C925'/%3E%3Cpolygon points='100%2C500 500%2C100 900%2C500 500%2C900'/%3E%3Cpolygon points='125%2C500 500%2C125 875%2C500 500%2C875'/%3E%3Cpolygon points='150%2C500 500%2C150 850%2C500 500%2C850'/%3E%3Cpolygon points='175%2C500 500%2C175 825%2C500 500%2C825'/%3E%3Cpolygon points='200%2C500 500%2C200 800%2C500 500%2C800'/%3E%3Cpolygon points='225%2C500 500%2C225 775%2C500 500%2C775'/%3E%3Cpolygon points='250%2C500 500%2C250 750%2C500 500%2C750'/%3E%3Cpolygon points='275%2C500 500%2C275 725%2C500 500%2C725'/%3E%3Cpolygon points='300%2C500 500%2C300 700%2C500 500%2C700'/%3E%3Cpolygon points='325%2C500 500%2C325 675%2C500 500%2C675'/%3E%3Cpolygon points='350%2C500 500%2C350 650%2C500 500%2C650'/%3E%3Cpolygon points='375%2C500 500%2C375 625%2C500 500%2C625'/%3E%3Cpolygon points='400%2C500 500%2C400 600%2C500 500%2C600'/%3E%3Cpolygon points='425%2C500 500%2C425 575%2C500 500%2C575'/%3E%3Cpolygon points='450%2C500 500%2C450 550%2C500 500%2C550'/%3E%3Cpolygon points='475%2C500 500%2C475 525%2C500 500%2C525'/%3E%3C/g%3E%3Crect fill-opacity='.2' fill='url(%23b)' width='1000' height='1000'/%3E %3C/svg%3E");
background-attachment: fixed;
background-size: cover;
}
.bg-4 {
background-color: #dd33bb;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%25' height='100%25' viewBox='0 0 1000 1000'%3E%3Cdefs%3E%3CradialGradient id='a' cx='500' cy='500' r='50%25' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0' stop-color='%23dd33bb'/%3E%3Cstop offset='1' stop-color='%23404'/%3E%3C/radialGradient%3E%3CradialGradient id='b' cx='500' cy='500' r='60%25' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0' stop-color='%23F70' stop-opacity='1'/%3E%3Cstop offset='1' stop-color='%23F70' stop-opacity='0'/%3E%3C/radialGradient%3E%3C/defs%3E%3Crect fill='url(%23a)' width='1000' height='1000'/%3E%3Cg fill='none' stroke='%23F6B' stroke-width='1' stroke-miterlimit='10' stroke-opacity='.3'%3E%3Crect x='12.5' y='12.5' width='975' height='975'/%3E%3Crect x='25' y='25' width='950' height='950'/%3E%3Crect x='37.5' y='37.5' width='925' height='925'/%3E%3Crect x='50' y='50' width='900' height='900'/%3E%3Crect x='62.5' y='62.5' width='875' height='875'/%3E%3Crect x='75' y='75' width='850' height='850'/%3E%3Crect x='87.5' y='87.5' width='825' height='825'/%3E%3Crect x='100' y='100' width='800' height='800'/%3E%3Crect x='112.5' y='112.5' width='775' height='775'/%3E%3Crect x='125' y='125' width='750' height='750'/%3E%3Crect x='137.5' y='137.5' width='725' height='725'/%3E%3Crect x='150' y='150' width='700' height='700'/%3E%3Crect x='162.5' y='162.5' width='675' height='675'/%3E%3Crect x='175' y='175' width='650' height='650'/%3E%3Crect x='187.5' y='187.5' width='625' height='625'/%3E%3Crect x='200' y='200' width='600' height='600'/%3E%3Crect x='212.5' y='212.5' width='575' height='575'/%3E%3Crect x='225' y='225' width='550' height='550'/%3E%3Crect x='237.5' y='237.5' width='525' height='525'/%3E%3Crect x='250' y='250' width='500' height='500'/%3E%3Crect x='262.5' y='262.5' width='475' height='475'/%3E%3Crect x='275' y='275' width='450' height='450'/%3E%3Crect x='287.5' y='287.5' width='425' height='425'/%3E%3Crect x='300' y='300' width='400' height='400'/%3E%3Crect x='312.5' y='312.5' width='375' height='375'/%3E%3Crect x='325' y='325' width='350' height='350'/%3E%3Crect x='337.5' y='337.5' width='325' height='325'/%3E%3Crect x='350' y='350' width='300' height='300'/%3E%3Crect x='362.5' y='362.5' width='275' height='275'/%3E%3Crect x='375' y='375' width='250' height='250'/%3E%3Crect x='387.5' y='387.5' width='225' height='225'/%3E%3Crect x='400' y='400' width='200' height='200'/%3E%3Crect x='412.5' y='412.5' width='175' height='175'/%3E%3Crect x='425' y='425' width='150' height='150'/%3E%3Crect x='437.5' y='437.5' width='125' height='125'/%3E%3Crect x='450' y='450' width='100' height='100'/%3E%3Crect x='462.5' y='462.5' width='75' height='75'/%3E%3Crect x='475' y='475' width='50' height='50'/%3E%3Crect x='487.5' y='487.5' width='25' height='25'/%3E%3C/g%3E%3Crect fill-opacity='.3' fill='url(%23b)' width='1000' height='1000'/%3E %3C/svg%3E");
background-attachment: fixed;
background-size: cover;
}
.bg-5 {
background-color: #000022;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='2000' height='2000' viewBox='0 0 800 800'%3E%3Cg fill='none' %3E%3Cg stroke='%23026' stroke-width='17'%3E%3Cline x1='-8' y1='-8' x2='808' y2='808'/%3E%3Cline x1='-8' y1='792' x2='808' y2='1608'/%3E%3Cline x1='-8' y1='-808' x2='808' y2='8'/%3E%3C/g%3E%3Cg stroke='%23002163' stroke-width='16'%3E%3Cline x1='-8' y1='767' x2='808' y2='1583'/%3E%3Cline x1='-8' y1='17' x2='808' y2='833'/%3E%3Cline x1='-8' y1='-33' x2='808' y2='783'/%3E%3Cline x1='-8' y1='-783' x2='808' y2='33'/%3E%3C/g%3E%3Cg stroke='%23002060' stroke-width='15'%3E%3Cline x1='-8' y1='742' x2='808' y2='1558'/%3E%3Cline x1='-8' y1='42' x2='808' y2='858'/%3E%3Cline x1='-8' y1='-58' x2='808' y2='758'/%3E%3Cline x1='-8' y1='-758' x2='808' y2='58'/%3E%3C/g%3E%3Cg stroke='%23001f5c' stroke-width='14'%3E%3Cline x1='-8' y1='67' x2='808' y2='883'/%3E%3Cline x1='-8' y1='717' x2='808' y2='1533'/%3E%3Cline x1='-8' y1='-733' x2='808' y2='83'/%3E%3Cline x1='-8' y1='-83' x2='808' y2='733'/%3E%3C/g%3E%3Cg stroke='%23001e59' stroke-width='13'%3E%3Cline x1='-8' y1='92' x2='808' y2='908'/%3E%3Cline x1='-8' y1='692' x2='808' y2='1508'/%3E%3Cline x1='-8' y1='-108' x2='808' y2='708'/%3E%3Cline x1='-8' y1='-708' x2='808' y2='108'/%3E%3C/g%3E%3Cg stroke='%23001d56' stroke-width='12'%3E%3Cline x1='-8' y1='667' x2='808' y2='1483'/%3E%3Cline x1='-8' y1='117' x2='808' y2='933'/%3E%3Cline x1='-8' y1='-133' x2='808' y2='683'/%3E%3Cline x1='-8' y1='-683' x2='808' y2='133'/%3E%3C/g%3E%3Cg stroke='%23001c53' stroke-width='11'%3E%3Cline x1='-8' y1='642' x2='808' y2='1458'/%3E%3Cline x1='-8' y1='142' x2='808' y2='958'/%3E%3Cline x1='-8' y1='-158' x2='808' y2='658'/%3E%3Cline x1='-8' y1='-658' x2='808' y2='158'/%3E%3C/g%3E%3Cg stroke='%23001b4f' stroke-width='10'%3E%3Cline x1='-8' y1='167' x2='808' y2='983'/%3E%3Cline x1='-8' y1='617' x2='808' y2='1433'/%3E%3Cline x1='-8' y1='-633' x2='808' y2='183'/%3E%3Cline x1='-8' y1='-183' x2='808' y2='633'/%3E%3C/g%3E%3Cg stroke='%23001a4c' stroke-width='9'%3E%3Cline x1='-8' y1='592' x2='808' y2='1408'/%3E%3Cline x1='-8' y1='192' x2='808' y2='1008'/%3E%3Cline x1='-8' y1='-608' x2='808' y2='208'/%3E%3Cline x1='-8' y1='-208' x2='808' y2='608'/%3E%3C/g%3E%3Cg stroke='%23001949' stroke-width='8'%3E%3Cline x1='-8' y1='567' x2='808' y2='1383'/%3E%3Cline x1='-8' y1='217' x2='808' y2='1033'/%3E%3Cline x1='-8' y1='-233' x2='808' y2='583'/%3E%3Cline x1='-8' y1='-583' x2='808' y2='233'/%3E%3C/g%3E%3Cg stroke='%23001846' stroke-width='7'%3E%3Cline x1='-8' y1='242' x2='808' y2='1058'/%3E%3Cline x1='-8' y1='542' x2='808' y2='1358'/%3E%3Cline x1='-8' y1='-558' x2='808' y2='258'/%3E%3Cline x1='-8' y1='-258' x2='808' y2='558'/%3E%3C/g%3E%3Cg stroke='%23001743' stroke-width='6'%3E%3Cline x1='-8' y1='267' x2='808' y2='1083'/%3E%3Cline x1='-8' y1='517' x2='808' y2='1333'/%3E%3Cline x1='-8' y1='-533' x2='808' y2='283'/%3E%3Cline x1='-8' y1='-283' x2='808' y2='533'/%3E%3C/g%3E%3Cg stroke='%2300163f' stroke-width='5'%3E%3Cline x1='-8' y1='292' x2='808' y2='1108'/%3E%3Cline x1='-8' y1='492' x2='808' y2='1308'/%3E%3Cline x1='-8' y1='-308' x2='808' y2='508'/%3E%3Cline x1='-8' y1='-508' x2='808' y2='308'/%3E%3C/g%3E%3Cg stroke='%2300153c' stroke-width='4'%3E%3Cline x1='-8' y1='467' x2='808' y2='1283'/%3E%3Cline x1='-8' y1='317' x2='808' y2='1133'/%3E%3Cline x1='-8' y1='-333' x2='808' y2='483'/%3E%3Cline x1='-8' y1='-483' x2='808' y2='333'/%3E%3C/g%3E%3Cg stroke='%23001439' stroke-width='3'%3E%3Cline x1='-8' y1='342' x2='808' y2='1158'/%3E%3Cline x1='-8' y1='442' x2='808' y2='1258'/%3E%3Cline x1='-8' y1='-458' x2='808' y2='358'/%3E%3Cline x1='-8' y1='-358' x2='808' y2='458'/%3E%3C/g%3E%3Cg stroke='%23001336' stroke-width='2'%3E%3Cline x1='-8' y1='367' x2='808' y2='1183'/%3E%3Cline x1='-8' y1='417' x2='808' y2='1233'/%3E%3Cline x1='-8' y1='-433' x2='808' y2='383'/%3E%3Cline x1='-8' y1='-383' x2='808' y2='433'/%3E%3C/g%3E%3Cg stroke='%23013' stroke-width='1'%3E%3Cline x1='-8' y1='392' x2='808' y2='1208'/%3E%3Cline x1='-8' y1='-408' x2='808' y2='408'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
}
.App .ant-layout {
background: transparent;
}
/* Game room */
.play-room .main-scene,
.play-room .players,
.play-room .game-controls {
border: 3px solid whitesmoke;
}
.play-room .main-scene {
min-height: 70vh;
}
.play-room .main-scene .admin-commands {
text-align: right;
}
.play-room .main-scene .the-ring {
/* border: 1px solid red; */
max-width: 550px;
}
/* TODO: non sono sicuro di queste media query!!! */
/* @media (min-width: 1150px) {
.play-room .main-scene .the-ring {
border: 1px solid yellow;
max-width: 750px;
}
}
@media (max-height: 800px) {
.play-room .main-scene .the-ring {
border: 1px solid lightseagreen;
transform: scale(.7);
}
} */
.play-room .players {
padding: 24px;
overflow-y: scroll;
}
.stash-preview {
text-align: center;
margin: 64px auto;
}
.play-room .game-controls {
min-height: 30vh;
}
/* Giocatori */
.player {
display: flex;
flex-direction: column;
align-items: center;
}
.player .picture {
width: 150px;
height: 180px;
background: pink url(https://picsum.photos/seed/ciccio/150) no-repeat;
background-size: cover;
border: 5px solid white;
box-shadow: 0 1px 1px rgba(0,0,0,0.12),
0 2px 2px rgba(0,0,0,0.12),
0 4px 4px rgba(0,0,0,0.12),
0 8px 8px rgba(0,0,0,0.12);
}
.player .name {
text-align: center;
}
.player.dead .picture {
/* filter: grayscale(100%); */
}
.player.dead .picture .badges i {
color: white;
}
.player .picture .badges {
display: flex;
justify-content: space-between;
padding: 8px;
}
.player .lives {
color: #D91E36;
}
/* Carte */
.card {
width: 94px;
height: 150px;
margin: 0 auto;
background: url('assets/images/carte_napoletane.png');
background-size: 1000% 400%;
/* transform: scale(.6); */
}
.card.coperta {
background: url('assets/images/carta_coperta.png');
background-size: 90% 90%;
background-repeat: no-repeat;
background-position: 10px 10px;
}
.card.coppe {
background-position-y: 0;
}
.card.denari {
background-position-y: 33%;
}
.card.bastoni {
background-position-y: 66%;
}
.card.spade {
background-position-y: 100%;
}
.card.asso {
background-position-x: 0;
}
.card.due {
background-position-x: 11%;
}
.card.tre {
background-position-x: 22%;
}
.card.quattro {
background-position-x: 33%;
}
.card.cinque {
background-position-x: 44%;
}
.card.sei {
background-position-x: 55%;
}
.card.sette {
background-position-x: 66%;
}
.card.otto {
background-position-x: 77%;
}
.card.nove {
background-position-x: 88%;
}
.card.dieci {
background-position-x: 100%;
}

View File

@@ -0,0 +1,8 @@
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

View File

@@ -0,0 +1,35 @@
import React from 'react';
import { Route, Switch } from 'wouter';
import { StateProvider } from './context/store';
import { ChatProvider } from './context/chatContext';
import LobbyPage from './pages/LobbyPage';
import PlayRoomPage from './pages/PlayRoomPage';
import { Layout } from 'antd';
import 'antd/dist/antd.css';
import 'antd/dist/antd.dark.css';
import './App.css';
const { Content } = Layout;
function App() {
return (
<StateProvider>
<ChatProvider>
<Layout className='App'>
<Content>
<Switch>
<Route path='/' component={LobbyPage} />
<Route path='/r/:roomId' component={PlayRoomPage} />
</Switch>
</Content>
{/* <Footer>Made with all the ❤️ by <a href='https://twitter.com/domtes'>@domtes</a></Footer> */}
</Layout>
</ChatProvider>
</StateProvider>
);
}
export default App;

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 MiB

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,32 @@
import * as React from 'react';
import { v4 as uuidv4 } from 'uuid';
import { Space } from 'antd';
interface HandProps {
cards: any[]
showHole: boolean
}
const Semi = ['bastoni', 'spade', 'coppe', 'denari'];
const Valori = ['asso', 'due', 'tre', 'quattro', 'cinque', 'sei', 'sette', 'otto', 'nove', 'dieci'];
const Hand: React.FC<HandProps> = ({ cards, showHole }) => {
return (
<Space direction="horizontal" align="start">
{cards.map((item) => {
let className = 'card coperta';
if (item.card !== undefined) {
const suit = Semi[item.card.card.suit];
const value = Valori[item.card.card.value];
className = showHole || item.card.public ? `card ${value} ${suit}` : 'card coperta';
}
return (
<div className={className} key={`${uuidv4()}`}></div>
)
})}
</Space>
)
}
export default Hand;

View File

@@ -0,0 +1,90 @@
import { useContext, useEffect, useRef } from 'react';
import { Card, Badge, Dropdown, Menu } from 'antd';
import { CrownOutlined, EllipsisOutlined, EuroOutlined, UserAddOutlined } from '@ant-design/icons';
import { GameContext } from '../context/store';
import { useStashManagement } from '../context/stashManagementContext';
import { useChatContext } from '../context/chatContext';
const { Meta } = Card;
const Player = ({ player, displayAdminMenu }) => {
const { state } = useContext(GameContext);
const { streamsRef } = useChatContext();
const { managePlayerStash } = useStashManagement();
const videoRef = useRef<HTMLVideoElement>(null);
useEffect(() => {
const stream = streamsRef?.current[player.sessionId];
if (stream && videoRef.current) {
console.log('[webrtc] Attaching stream to video element', player.sessionId, stream, videoRef.current);
const video = videoRef.current;
video.srcObject = stream;
}
}, [player, streamsRef]);
const handleMenuClick = ({ key }) => {
switch (key) {
case 'make-owner':
state.room.send('admin', {
command: 'give-room-ownership',
payload: { sessionId: player.sessionId }
});
break;
case 'manage-stash':
managePlayerStash(player);
break;
case 'assign-seat':
state.room.send('admin', {
command: 'assign-seat',
payload: { sessionId: player.sessionId }
});
break;
default:
throw Error('Unkown menu item');
}
};
const menu = (
<Menu mode="vertical" onClick={handleMenuClick}>
<Menu.Item key="manage-stash" icon={<EuroOutlined />}>
Gestisci fondi
</Menu.Item>
{!player.playing && (
<Menu.Item key="assign-seat" icon={<UserAddOutlined />}>
Assegna posto
</Menu.Item>
)}
{!player.owner && (
<>
<Menu.Divider />
<Menu.Item key="make-owner" icon={<CrownOutlined />} danger>
Rendi proprietario
</Menu.Item>
</>
)}
</Menu>
);
return (
<Badge.Ribbon text={player.stash}>
<Card style={{ width: 120 }}
// cover={<Image
// width={120}
// title={player.displayName}
// src={`https://i.pravatar.cc/120?u=${player.id}`}
// fallback="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3PTWBSGcbGzM6GCKqlIBRV0dHRJFarQ0eUT8LH4BnRU0NHR0UEFVdIlFRV7TzRksomPY8uykTk/zewQfKw/9znv4yvJynLv4uLiV2dBoDiBf4qP3/ARuCRABEFAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghgg0Aj8i0JO4OzsrPv69Wv+hi2qPHr0qNvf39+iI97soRIh4f3z58/u7du3SXX7Xt7Z2enevHmzfQe+oSN2apSAPj09TSrb+XKI/f379+08+A0cNRE2ANkupk+ACNPvkSPcAAEibACyXUyfABGm3yNHuAECRNgAZLuYPgEirKlHu7u7XdyytGwHAd8jjNyng4OD7vnz51dbPT8/7z58+NB9+/bt6jU/TI+AGWHEnrx48eJ/EsSmHzx40L18+fLyzxF3ZVMjEyDCiEDjMYZZS5wiPXnyZFbJaxMhQIQRGzHvWR7XCyOCXsOmiDAi1HmPMMQjDpbpEiDCiL358eNHurW/5SnWdIBbXiDCiA38/Pnzrce2YyZ4//59F3ePLNMl4PbpiL2J0L979+7yDtHDhw8vtzzvdGnEXdvUigSIsCLAWavHp/+qM0BcXMd/q25n1vF57TYBp0a3mUzilePj4+7k5KSLb6gt6ydAhPUzXnoPR0dHl79WGTNCfBnn1uvSCJdegQhLI1vvCk+fPu2ePXt2tZOYEV6/fn31dz+shwAR1sP1cqvLntbEN9MxA9xcYjsxS1jWR4AIa2Ibzx0tc44fYX/16lV6NDFLXH+YL32jwiACRBiEbf5KcXoTIsQSpzXx4N28Ja4BQoK7rgXiydbHjx/P25TaQAJEGAguWy0+2Q8PD6/Ki4R8EVl+bzBOnZY95fq9rj9zAkTI2SxdidBHqG9+skdw43borCXO/ZcJdraPWdv22uIEiLA4q7nvvCug8WTqzQveOH26fodo7g6uFe/a17W3+nFBAkRYENRdb1vkkz1CH9cPsVy/jrhr27PqMYvENYNlHAIesRiBYwRy0V+8iXP8+/fvX11Mr7L7ECueb/r48eMqm7FuI2BGWDEG8cm+7G3NEOfmdcTQw4h9/55lhm7DekRYKQPZF2ArbXTAyu4kDYB2YxUzwg0gi/41ztHnfQG26HbGel/crVrm7tNY+/1btkOEAZ2M05r4FB7r9GbAIdxaZYrHdOsgJ/wCEQY0J74TmOKnbxxT9n3FgGGWWsVdowHtjt9Nnvf7yQM2aZU/TIAIAxrw6dOnAWtZZcoEnBpNuTuObWMEiLAx1HY0ZQJEmHJ3HNvGCBBhY6jtaMoEiJB0Z29vL6ls58vxPcO8/zfrdo5qvKO+d3Fx8Wu8zf1dW4p/cPzLly/dtv9Ts/EbcvGAHhHyfBIhZ6NSiIBTo0LNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg==" />}
cover={<video playsInline autoPlay ref={videoRef} width={120} title={player.displayName} />}
actions={displayAdminMenu ? [
<Dropdown overlay={menu} trigger={['click']}>
<EllipsisOutlined key="ellipsis" />
</Dropdown>,
] : []}
>
<video ref={videoRef} width={120} title={player.displayName} autoPlay />
<Meta title={player.displayName} />
</Card>
</Badge.Ribbon>
)
};
export default Player;

View File

@@ -0,0 +1,118 @@
import { FC, useCallback, useContext, useState } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { Button, Col, Form, InputNumber, Row, Space, Slider } from 'antd';
import { GameContext } from '../context/store';
interface PromptProps {
prompt: any
}
const layout = {
labelCol: { span: 8 },
wrapperCol: { span: 16 },
};
const tailLayout = {
wrapperCol: { offset: 8, span: 16 },
};
const Prompt: FC<PromptProps> = ({ prompt }) => {
const { state } = useContext(GameContext);
const [bet, setBet] = useState<number>(10);
const [action, setAction] = useState<"more" | "stand">("stand");
const [form] = Form.useForm();
const handleValuesChange = useCallback((changedValues, allValues) => {
console.log('Values changed:', changedValues, allValues);
if (Object.keys(changedValues).includes('bet')) {
setBet(changedValues.bet);
}
}, [setBet]);
const handleBetChange = useCallback(value => {
form.setFieldsValue({ bet: value });
}, [form]);
const handleButtonClick = useCallback(value => {
setAction(value);
form.submit();
}, [form, setAction]);
const onFinish = useCallback((values: any) => {
console.log('Success:', { ...values, action });
state.room.send('resolve-prompt', { ...values, action });
form.setFieldsValue({ bet: 10 });
setBet(10);
}, [state.room, form, action, setBet]);
const onFinishFailed = (errorInfo: any) => {
console.log('Failed:', errorInfo);
};
if (prompt === undefined || !prompt.visible) {
return <></>;
}
return (
<Form
{...layout}
form={form}
name="basic"
initialValues={{
bet: bet,
}}
onValuesChange={handleValuesChange}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
{prompt.fields.map((field) => {
return (
<Form.Item key={`${uuidv4()}`}
label={field.label}
>
<Row>
<Col span={12}>
<Slider
step={1}
min={field.min}
max={field.max}
defaultValue={bet}
onChange={handleBetChange}
/>
</Col>
<Col span={4}>
<Form.Item name={field.name}>
<InputNumber
style={{ margin: '0 16px' }}
min={field.min}
max={field.max}
/>
</Form.Item>
</Col>
</Row>
</Form.Item>
)
})}
<Form.Item {...tailLayout}>
<Space>
{prompt.buttons.map((button) => {
return (
<Button
key={`${uuidv4()}`}
type={button.type}
value={button.name}
onClick={() => {
handleButtonClick(button.name);
}}>
{button.label}
</Button>
)
})}
</Space>
</Form.Item>
</Form>
)
}
export default Prompt;

View File

@@ -0,0 +1,96 @@
import { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { Button, Drawer, Form, InputNumber, Radio, Statistic } from 'antd';
import { GameContext } from '../context/store';
import { useStashManagement } from '../context/stashManagementContext';
const StashManagementDrawer = () => {
const { state } = useContext(GameContext);
const { visible, player, hide } = useStashManagement();
const [form] = Form.useForm();
const amountRef = useRef<any>(null);
const [stashPreview, setStashPreview] = useState<number | undefined>(player?.stash);
useEffect(() => {
form.setFieldsValue({ amount: 0, action: 'add-to' });
setStashPreview(player?.stash);
if (amountRef && amountRef.current) {
amountRef?.current.input.focus();
}
}, [player, form, amountRef, visible]);
const handleValuesChange = useCallback((changed, all) => {
if (!player) {
return;
}
let preview = 0;
switch (all.action) {
case 'add-to':
preview = player?.stash + all.amount;
break;
case 'remove-from':
preview = Math.max(0, player?.stash - all.amount);
break;
case 'set':
preview = all.amount;
break;
}
setStashPreview(preview);
}, [player]);
const handleConfirm = useCallback(() => {
const values = form.getFieldsValue();
console.log('Operation confirmed:', values);
state.room.send('admin', {
command: `${values.action}-user-stash`,
payload: { sessionId: player?.sessionId, amount: values.amount }
});
hide();
}, [form, player, hide, state.room]);
const handleAmountFocus = useCallback((event) => {
event.target.select();
}, []);
return (
<Drawer forceRender visible={visible} width={720}
title={`Gestione fondi per ${player?.displayName}`}
onClose={hide}
footer={
<div style={{ textAlign: 'right' }}>
<Button style={{ marginRight: 8 }} onClick={hide}>
Annulla
</Button>
<Button type="primary" onClick={handleConfirm}>
Conferma
</Button>
</div>
}>
<Form
form={form}
layout="inline"
initialValues={{ amount: 0, action: 'add-to' }}
onValuesChange={handleValuesChange}
>
<Form.Item label="Operazione" name="action">
<Radio.Group>
<Radio.Button value="add-to">Aggiungi</Radio.Button>
<Radio.Button value="remove-from">Rimuovi</Radio.Button>
<Radio.Button value="set">Imposta</Radio.Button>
</Radio.Group>
</Form.Item>
<Form.Item label="Importo" name='amount'>
<InputNumber ref={amountRef} min={0} max={10000} step={100} onFocus={handleAmountFocus} onPressEnter={handleConfirm} />
</Form.Item>
</Form>
<div className="stash-preview">
<Statistic value={`${player?.stash}${stashPreview}`} title="Anteprima" />
</div>
</Drawer>
)
};
export default StashManagementDrawer;

View File

@@ -0,0 +1,192 @@
import { createContext, useContext, useRef, useState, ReactNode, useEffect, MutableRefObject, useCallback } from 'react';
import SimplePeer from 'simple-peer';
import { GameContext } from './store';
export interface IPlayer {
sessionId: string;
}
export interface IChatContext {
audio: boolean;
video: boolean;
toggleAudio: () => void;
toggleVideo: () => void;
callPlayer: (player: IPlayer, room: any) => void;
streamsRef: MutableRefObject<Record<string, MediaStream>> | null;
}
export const ChatContext = createContext<IChatContext>({
audio: false,
video: true,
toggleAudio: () => console.warn('No implementation provided'),
toggleVideo: () => console.warn('No implementation provided'),
callPlayer: (player, room) => console.warn('No implementation provided', player, room),
streamsRef: null
});
export const useChatContext = () => useContext(ChatContext);
type Props = {
children: ReactNode;
};
export const ChatProvider = ({ children }: Props) => {
const [chatInitialized, setChatInitialized] = useState<boolean>(false);
const { state } = useContext(GameContext);
const [audioEnabled, setAudioEnabled] = useState<boolean>(false);
const [videoEnabled, setVideoEnabled] = useState<boolean>(false);
const peersRef = useRef<Record<string, SimplePeer.Instance>>({});
const streamsRef = useRef<Record<string, MediaStream>>({});
const setupVideoStream = async () => {
if (state.room === null) return null;
const stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: false
});
streamsRef.current[state.room.sessionId] = stream;
console.log('Got self stream:', state.room.sessionId, streamsRef.current);
return stream;
};
const toggleAudio = () => {
setAudioEnabled(!audioEnabled);
}
const toggleVideo = () => {
setVideoEnabled(!videoEnabled);
}
const callPlayer = (player: IPlayer, stream: any) => {
console.log('Calling player....', player, player.sessionId, stream);
const existingPeer = peersRef.current[player.sessionId];
if (!existingPeer) {
console.log('Creating peer for player:', player.sessionId);
const peer = createPeer(player.sessionId, state.room.sessionId, stream);
peersRef.current[player.sessionId] = peer;
} else {
console.log('Player is already connected', player.sessionId, existingPeer);
}
}
const callRoomParticipants = async () => {
const stream = await setupVideoStream();
console.log('Calling room participants:', state.gameState.players.values((p) => { return p.sessionId }));
state.gameState.players.forEach((player) => {
if (player.sessionId === state.room.sessionId) return;
callPlayer(player, stream);
});
};
const createPeer = (userToSignal, callerId, stream) => {
const peer = new SimplePeer({
initiator: true,
trickle: false,
stream,
});
peer.on("signal", signal => {
state.room.send('webrtc', {
command: 'call-player', payload: {
'callerId': callerId,
'targetId': userToSignal,
'signal': signal
}
});
});
peer.on('connect', () => {
console.log('[webrtc] WEBRTC PEER CONNECTED! (1)');
});
peer.on('stream', stream => {
console.log('[webrtc] Got remote stream (1)', userToSignal, stream);
streamsRef.current[userToSignal] = stream;
});
return peer;
}
const addPeer = (incomingSignal, callerId, stream) => {
const peer = new SimplePeer({
initiator: false,
trickle: false,
stream
})
peer.on("signal", signal => {
state.room.send('webrtc', {
command: 'answer-call', payload: {
'callerId': state.room.sessionId,
'targetId': callerId,
'signal': signal
}
});
});
peer.on('connect', () => {
console.log('[webrtc] WEBRTC PEER CONNECTED! (2)');
});
peer.signal(incomingSignal);
return peer;
}
useEffect(() => {
if (chatInitialized || state.room === null || state.gameState.players.size === 0) return;
console.log('[webrtc] Initializing chat');
setChatInitialized(true);
console.log('[webrtc] Registering incoming-call handler', state.room);
state.room.onMessage('answer-call', msg => {
console.log('[webrtc] Receiving answer-call:', msg);
const peer = peersRef.current[msg.callerId];
peer.signal(msg.signal);
});
state.room.onMessage('incoming-call', (msg) => {
const stream = streamsRef.current[state.room.sessionId];
console.log('[webrtc] Answering incoming call:', msg, stream);
const peer = addPeer(msg.signal, msg.callerId, stream);
peer.on('stream', stream => {
console.log('[webrtc] Got remote stream (2)', msg.callerId);
streamsRef.current[msg.callerId] = stream;
});
peersRef.current[msg.callerId] = peer;
});
callRoomParticipants();
return () => {
console.log('[webrtc] Disposing ChatProvider');
// if (state.room || state.gameState.players.size > 0) {
// console.log('[webrtc] Removing listeners for incoming-message')
// state.room.removeAllListeners('incoming-message');
// state.room.removeAllListeners('answer-call');
// streamsRef.current = {};
// setChatInitialized(false);
// }
}
}, [state.room, state.gameState.players]);
return (
<ChatContext.Provider value={{
audio: audioEnabled,
video: videoEnabled,
toggleAudio,
toggleVideo,
callPlayer,
streamsRef
}}>
{children}
</ChatContext.Provider>
)
}

View File

@@ -0,0 +1,50 @@
import { createContext, useContext, useState, ReactNode } from 'react';
export interface IPlayer {
id: string;
sessionId: string;
displayName: string;
stash: number;
}
export interface IPlayerStashContext {
visible: boolean;
player: IPlayer | undefined;
managePlayerStash: (player: IPlayer | undefined) => void;
hide: () => void;
}
export const StashManagementContext = createContext<IPlayerStashContext>({
visible: false,
player: undefined,
managePlayerStash: player => console.warn('No stash management provider', player),
hide: () => console.warn('No hide implementation provided')
});
export const useStashManagement = () => useContext(StashManagementContext);
type Props = {
children: ReactNode;
};
export const StashManagementProvider = ({ children }: Props) => {
const [visible, setVisible] = useState<boolean>(false);
const [player, setPlayer] = useState<IPlayer | undefined>(undefined);
const managePlayerStash = (player: IPlayer | undefined) => {
if (player) {
setPlayer(player);
}
setVisible(true);
};
const hide = () => {
setVisible(false);
}
return (
<StashManagementContext.Provider value={{ visible, player, managePlayerStash, hide }}>
{children}
</StashManagementContext.Provider>
)
}

View File

@@ -0,0 +1,101 @@
import React, { createContext, useEffect, useReducer } from 'react';
import * as Colyseus from 'colyseus.js';
const SOCKET_URL = `${window.location.protocol.replace("http", "ws")}//${window.location.hostname}${(window.location.port && `:${window.location.port}`)}/api`;
console.log('Socket location:', SOCKET_URL);
type SessionType = {
user_id: string;
display_name: string;
}
type GameContextType = {
client: any;
session: SessionType | null;
room: any;
bg: number;
gameState: any;
};
const initialState = {
client: new Colyseus.Client(SOCKET_URL),
session: null,
room: null,
bg: 4,
gameState: {
pot: 0,
players: new Map<string, any>()
}
};
const GameContext = createContext<{
state: GameContextType;
dispatch: React.Dispatch<any>;
}>({
state: initialState,
dispatch: () => null
});
const { Provider } = GameContext;
const StateProvider = ({ children }) => {
useEffect(() => {
const fetchSessionData = async () => {
const response = await fetch('/api/session', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
const data = await response.json();
console.log('Session data fetched:', data);
if ('user_id' in data) {
dispatch({
type: 'LOGGED_IN',
payload: data
});
}
};
fetchSessionData();
}, []);
const [state, dispatch] = useReducer((state, action) => {
switch (action.type) {
case 'LOGGED_IN':
return {
...state,
session: action.payload
};
case 'LOGGED_OUT':
return {
...state,
session: null
};
case 'JOIN_ROOM':
console.log('JOIN_ROOM', action);
return {
...state,
room: action.payload
};
case 'LEAVE_ROOM':
console.log('LEAVE_ROOM');
return {
...state,
room: null
};
case 'GAME_STATE':
return {
...state,
gameState: action.payload
};
default:
throw new Error();
};
}, initialState);
return <Provider value={{ state, dispatch }}>{children}</Provider>;
};
export { GameContext, StateProvider }

View File

@@ -0,0 +1,13 @@
body {
margin: 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;
}

View File

@@ -0,0 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals(null);

View File

@@ -0,0 +1,125 @@
import { useCallback, useContext, useState } from 'react';
import { useLocation } from 'wouter';
import { GameContext } from '../context/store';
import { message, Button, Card, Col, Divider, Input, Row, Space, Typography } from 'antd';
const { Text, Title } = Typography;
function LobbyPage() {
const { state, dispatch } = useContext(GameContext);
const [displayName, setDisplayName] = useState();
const [roomId, setRoomId] = useState<string>();
const [, setLocation] = useLocation();
const handleUsernameChange = useCallback((e) => {
setDisplayName(e.target.value);
}, []);
const handleLogin = useCallback(async () => {
console.log('Logging in with the server as', displayName);
if (displayName === undefined) {
return;
}
// Login with the server
const response = await fetch('/api/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
display_name: displayName
})
});
if (response.status === 200) {
const body = await response.json();
dispatch({
type: 'LOGGED_IN', payload: {
user_id: body.user_id,
display_name: displayName
}
});
} else {
message.error(`Something bad happened: ${response.body}`);
}
}, [dispatch, displayName]);
const handleLogout = useCallback(async () => {
console.log('Logging out from the server');
await fetch('/api/logout', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
dispatch({ type: 'LOGGED_OUT' });
}, [dispatch]);
const handleCreateRoom = useCallback(async () => {
const room = await state.client.create('game', {
user_id: state.session?.user_id,
display_name: state.session?.display_name
});
console.log('Room created successfully', room);
message.success(`Stanza creata: ${room.id}`);
dispatch({ type: 'JOIN_ROOM', payload: room });
setLocation(`/r/${room.id}`);
}, [state, dispatch, setLocation]);
const handleJoinRoom = useCallback(async () => {
if (roomId === undefined) {
return;
}
const room = await state.client.joinById(roomId, {
user_id: state.session?.user_id,
display_name: state.session?.display_name
});
dispatch({ type: 'JOIN_ROOM', payload: room });
setLocation(`/r/${room.id}`);
}, [roomId, state, dispatch, setLocation]);
return <>
<Row justify='center' align='middle' style={{ minHeight: '100vh' }}>
<Col>
<Card>
<Space direction='vertical' align='center'>
{(state.session === null) ? (
<>
<Title level={4}>Come vuoi essere chiamato?</Title>
<Input size='large' autoFocus
placeholder='Il tuo nome'
onChange={handleUsernameChange}
onPressEnter={handleLogin}></Input>
<Button type='primary' onClick={handleLogin}>Entra</Button>
</>
) : (
<>
<Text>Ciao {state.session.display_name} ({state.session.user_id})!</Text>
<Button type='primary' onClick={handleCreateRoom}>Crea una nuova stanza</Button >
<Divider plain>oppure unisciti ad una stanza esistente</Divider>
<Input placeholder='Codice stanza' onChange={(e) => setRoomId(e.target.value)} onPressEnter={handleJoinRoom}></Input>
<Button onClick={handleJoinRoom}>Entra nella stanza</Button>
<Button danger onClick={handleLogout}>Logout</Button>
</>
)}
</Space>
</Card>
</Col>
</Row>
</>
}
export default LobbyPage;

View File

@@ -0,0 +1,219 @@
import { useCallback, useContext, useEffect, useState } from 'react';
import { Badge, Layout, Row, Col, Space, Typography, Button, message, Statistic } from 'antd';
import { PauseCircleOutlined, PlaySquareOutlined } from '@ant-design/icons';
import { FullScreen, useFullScreenHandle } from "react-full-screen";
import { useLocation } from 'wouter';
import { GameContext } from '../context/store';
import { StashManagementProvider } from '../context/stashManagementContext';
import StashManagementDrawer from '../components/StashManagementDrawer';
import Player from '../components/Player';
import Hand from '../components/Hand';
import Prompt from '../components/Prompt';
const { Content } = Layout;
const { Title } = Typography;
const PlayRoomPage = ({ params }) => {
const roomId = params.roomId;
const { state, dispatch } = useContext(GameContext);
const [, setLocation] = useLocation();
const fullScreenHandle = useFullScreenHandle();
const [isRoomOwner, setIsRoomOwner] = useState(false);
const [thisPlayerHand, setThisPlayerHand] = useState([]);
const [thisPlayerPrompt, setThisPlayerPrompt] = useState([]);
const [thisPlayerScore, setThisPlayerScore] = useState();
useEffect(() => {
console.log('Room id:', roomId);
console.log('Global state:', state);
console.log('Current user:', state.session?.display_name, state.session?.user_id);
const joinRoom = async () => {
if (state.room === null) {
console.log('Room not joined yet:', state.gameState.user_id, state.gameState.display_name);
try {
const room = await state.client.joinById(roomId, {
user_id: state.session?.user_id,
display_name: state.session?.display_name
});
dispatch({ type: 'JOIN_ROOM', payload: room });
} catch (error) {
message.error('Stanza non tovata');
setLocation('/');
}
} else {
console.log('Registering room handlers');
state.room.onStateChange((newState) => {
console.log('Room state changed:', newState);
dispatch({ type: 'GAME_STATE', payload: { ...newState } });
const isOwner = newState.roomOwner === state.session?.user_id;
setIsRoomOwner(isOwner);
});
state.room.onMessage('notification', (msg) => {
console.log('Message received from server:', msg);
const msg_type = msg.type || 'info';
message[msg_type](msg.text);
});
}
};
joinRoom();
return () => {
if (state.room) {
console.log('Removing room listeners...');
state.room.removeAllListeners();
dispatch({ type: 'LEAVE_ROOM' });
}
}
}, [state.room]);
useEffect(() => {
if (state.room === null) return;
// Setting the current player reference
const p = state.gameState.players.get(state.room.sessionId);
if (p !== undefined) {
console.log('Setting current player hand:', p, p.hand);
setThisPlayerHand(p.hand);
setThisPlayerPrompt(p.prompt);
setThisPlayerScore(p.score);
}
}, [state.room, state.gameState]);
const handleStartGame = useCallback(() => {
state.room.send('admin', { command: 'start-game' });
}, [state.room]);
const handlePauseGame = useCallback(() => {
state.room.send('admin', { command: 'pause-game' });
}, [state.room]);
const handleResumeGame = useCallback(() => {
state.room.send('resume-game', {});
}, [state.room]);
return (
<FullScreen handle={fullScreenHandle}>
<StashManagementProvider>
<Layout className='play-room'>
<Content>
<Row justify="center">
<Col flex="auto" className={`main-scene bg-${state.gameState.bg}`}>
{isRoomOwner && (
<Space className="admin-commands">
{!state.gameState.running && (
<Button icon={<PlaySquareOutlined />} type="link" size="large" onClick={handleStartGame} />
)}
{(state.gameState.running && state.gameState.paused) && (
<Button icon={<PlaySquareOutlined />} type="link" size="large" onClick={handleResumeGame} />
)}
{(state.gameState.running && !state.gameState.paused) && (
<Button icon={<PauseCircleOutlined />} type="link" size="large" onClick={handlePauseGame} />
)}
</Space>
)}
{(state.gameState.running && !state.gameState.paused) && (
<Space direction="vertical" align="center" style={{ width: '100%' }} size="large">
<Statistic title="Piatto" value={state.gameState.pot} />
<Space direction="horizontal" align="baseline" split="VS" size="large" className="the-ring">
<div className="player">
<div className="picture" id="player">
<div className="badges">
<Player player={state.gameState.player1} displayAdminMenu={false} />
<div className="lives">
<i className="fas fa-heart" title="1 Vita"></i>
<i className="fas fa-heart" title="1 Vita"></i>
<i className="fas fa-heart" title="1 Vita"></i>
</div>
<div className="status"></div>
</div>
</div>
<div className="name">
{state.gameState.player1.displayName} (Banco)
{(state.gameState.player1.prompt && state.gameState.player1.prompt.visible) && (<Badge status="processing" />)}
</div>
<Hand cards={state.gameState.player1.hand} showHole={false} />
</div>
<div className="player">
<div className="picture" id="player">
<Player player={state.gameState.player2} displayAdminMenu={false} />
<div className="badges">
<div className="lives">
<i className="fas fa-heart" title="1 Vita"></i>
<i className="fas fa-heart" title="1 Vita"></i>
<i className="fas fa-heart" title="1 Vita"></i>
</div>
<div className="status"></div>
</div>
</div>
<div className="name">
{state.gameState.player2.displayName}
{(state.gameState.player2.prompt && state.gameState.player2.prompt.visible) && (<Badge status="processing" />)}
</div>
<Hand cards={state.gameState.player2.hand} showHole={false} />
<Statistic title="Scommessa" value={state.gameState.currentBet} />
</div>
</Space>
</Space>
)}
</Col>
<Col className="players" xs={4} md={6} lg={8} xl={10}>
<Title level={4}>In gioco</Title>
<Space size={12} wrap>
{Array.from<any>(state.gameState.players.values()).filter((player, index) => {
return player.playing;
}).map((player, index) => (
<Player key={index} player={player} displayAdminMenu={isRoomOwner} />
))}
</Space>
<Title level={4}>Spettatori</Title>
<Space size={12} wrap>
{Array.from<any>(state.gameState.players.values()).filter((player, index) => {
return !player.playing;
}).map((player, index) => (
<Player key={index} player={player} displayAdminMenu={isRoomOwner} />
))}
</Space>
</Col>
</Row>
<Row>
<Col className="game-controls" span={24}>
<Space direction="vertical" style={{ width: "100%" }}>
{/* <Button onClick={fullScreenHandle.enter}>Full screen</Button> */}
<Row>
<Col flex={2}>
<Hand cards={thisPlayerHand} showHole={true} />
</Col>
<Col flex={2}>
<Space direction="vertical">
{thisPlayerHand.length > 0 && <Statistic title="Il tuo punteggio:" value={thisPlayerScore} />}
<Prompt prompt={thisPlayerPrompt} />
</Space>
</Col>
</Row>
</Space>
</Col>
</Row>
<StashManagementDrawer />
</Content>
</Layout>
</StashManagementProvider>
</FullScreen >
);
}
export default PlayRoomPage;

View File

@@ -0,0 +1 @@
/// <reference types="react-scripts" />

View File

@@ -0,0 +1,13 @@
const reportWebVitals = onPerfEntry => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@@ -0,0 +1,11 @@
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = (app) => {
const socketProxy = createProxyMiddleware('/api', {
target: 'http://localhost:3001',
changeOrigin: true,
ws: true,
logLevel: 'debug'
});
app.use(socketProxy);
};

View File

@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"noImplicitAny": false,
"target": "es6",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"**/*.tsx"
]
}

12181
games-party/client/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,41 +0,0 @@
const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const { v4: uuidV4 } = require('uuid')
const { ExpressPeerServer } = require('peer');
app.enable('trust proxy');
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.get('/', (request, response) => {
// create a room
// redirect to a room
response.redirect(`/r/${uuidV4()}`)
})
app.get('/r/:room', (request, response) => {
response.render('room', { roomId: request.params.room })
})
io.on('connection', socket => {
socket.on('join-room', (roomId, userId) => {
socket.join(roomId)
socket.to(roomId).broadcast.emit('user-connected', userId)
socket.on('disconnect', () => {
socket.to(roomId).broadcast.emit('user-disconnected', userId)
})
})
})
// Connection broker
const peerServer = ExpressPeerServer(server, {
debug: true,
path: '/domingo'
})
app.use('/peerjs', peerServer)
server.listen(3000, '0.0.0.0')

View File

@@ -0,0 +1,17 @@
* TODO Implementa il muto/audio on
* TODO Implementa il video on/off
* TODO Stilizza i video
* TODO Stilizza i player offline
* TODO Controlla il bug quando sballi in presenza di matta
* TODO ridisegnare i game controls in un drawer
* TODO Investigate current player hand and prompt (move it to the context)
* TODO Implementare il full-screen (non funziona!)
* DONE Controlla meglio che i conti tornino sempre!
* DONE disegnare la :currentBet:
* DONE marcare il dealer
* DONE evidenziare il giocatore di turno
* DONE Brucia i quattro!
* DONE Integra la videochat

View File

@@ -0,0 +1,100 @@
import { BaseGameType, CardName, ICard, PlayingCard, RankSet, Suit } from 'typedeck';
enum SemeNapoletano {
Bastoni, // Suit.Clubs
Spade, // Suit.Spades
Coppe, // Suit.Diamonds
Denari // Suit.Hearts
};
export class CartaNapoletana extends PlayingCard {
public toString(): string {
return `${CardName[this.cardName]} of ${SemeNapoletano[this.suit]}`;
}
}
class NapoliGameType extends BaseGameType {
public cardsAllowed: ICard[] = [
new CartaNapoletana(CardName.Ace, Suit.Clubs),
new CartaNapoletana(CardName.Two, Suit.Clubs),
new CartaNapoletana(CardName.Three, Suit.Clubs),
new CartaNapoletana(CardName.Four, Suit.Clubs),
new CartaNapoletana(CardName.Five, Suit.Clubs),
new CartaNapoletana(CardName.Six, Suit.Clubs),
new CartaNapoletana(CardName.Seven, Suit.Clubs),
new CartaNapoletana(CardName.Eight, Suit.Clubs),
new CartaNapoletana(CardName.Nine, Suit.Clubs),
new CartaNapoletana(CardName.Ten, Suit.Clubs),
new CartaNapoletana(CardName.Ace, Suit.Diamonds),
new CartaNapoletana(CardName.Two, Suit.Diamonds),
new CartaNapoletana(CardName.Three, Suit.Diamonds),
new CartaNapoletana(CardName.Four, Suit.Diamonds),
new CartaNapoletana(CardName.Five, Suit.Diamonds),
new CartaNapoletana(CardName.Six, Suit.Diamonds),
new CartaNapoletana(CardName.Seven, Suit.Diamonds),
new CartaNapoletana(CardName.Eight, Suit.Diamonds),
new CartaNapoletana(CardName.Nine, Suit.Diamonds),
new CartaNapoletana(CardName.Ten, Suit.Diamonds),
new CartaNapoletana(CardName.Ace, Suit.Spades),
new CartaNapoletana(CardName.Two, Suit.Spades),
new CartaNapoletana(CardName.Three, Suit.Spades),
new CartaNapoletana(CardName.Four, Suit.Spades),
new CartaNapoletana(CardName.Five, Suit.Spades),
new CartaNapoletana(CardName.Six, Suit.Spades),
new CartaNapoletana(CardName.Seven, Suit.Spades),
new CartaNapoletana(CardName.Eight, Suit.Spades),
new CartaNapoletana(CardName.Nine, Suit.Spades),
new CartaNapoletana(CardName.Ten, Suit.Spades),
new CartaNapoletana(CardName.Ace, Suit.Hearts),
new CartaNapoletana(CardName.Two, Suit.Hearts),
new CartaNapoletana(CardName.Three, Suit.Hearts),
new CartaNapoletana(CardName.Four, Suit.Hearts),
new CartaNapoletana(CardName.Five, Suit.Hearts),
new CartaNapoletana(CardName.Six, Suit.Hearts),
new CartaNapoletana(CardName.Seven, Suit.Hearts),
new CartaNapoletana(CardName.Eight, Suit.Hearts),
new CartaNapoletana(CardName.Nine, Suit.Hearts),
new CartaNapoletana(CardName.Ten, Suit.Hearts)
];
}
class BancoRankSet extends RankSet {
public rankSet: CardName[] = [
CardName.Ace,
CardName.Two,
CardName.Three,
CardName.Four,
CardName.Five,
CardName.Six,
CardName.Seven,
CardName.Eight,
CardName.Nine,
CardName.Ten
];
}
export class BancoGameType extends NapoliGameType {
public rankSet = new BancoRankSet();
}
class SettemmezzoRankSet extends RankSet {
public rankSet: CardName[] = [
CardName.Eight,
CardName.Nine,
CardName.Ten,
CardName.Ace,
CardName.Two,
CardName.Three,
CardName.Four,
CardName.Five,
CardName.Six,
CardName.Seven
];
}
export class SettemmezzoGameType extends NapoliGameType {
public rankSet = new SettemmezzoRankSet();
}

View File

@@ -0,0 +1,159 @@
import { Client } from 'colyseus';
import { type, filter, ArraySchema, Schema, MapSchema } from '@colyseus/schema';
export class CardValue extends Schema {
@type('uint8')
value: number;
@type('uint8')
suit: number;
}
export class SerializedCard extends Schema {
@type('string')
owner: string;
@type('boolean')
public: boolean;
@type(CardValue)
card: CardValue;
}
export class CardPlaceholder extends Schema {
@filter(function (
this: CardPlaceholder,
client: Client,
value: SerializedCard,
root: Schema) {
return value.public || value.owner === client.sessionId;
})
@type(SerializedCard)
card: SerializedCard;
}
export class PromptField extends Schema {
@type('string')
type: string;
@type('string')
name: string;
@type('string')
label: string;
@type('int32')
min: string;
@type('int32')
max: string;
}
export class PromptButton extends Schema {
@type('string')
name: string;
@type('string')
label: string;
@type('string')
type: string;
}
export class Prompt extends Schema {
@type('boolean')
visible: boolean;
@type([PromptField])
fields = new ArraySchema<PromptField>();
@type([PromptButton])
buttons = new ArraySchema<PromptButton>();
}
export class Player extends Schema {
@type('string')
id: string;
@type('string')
sessionId: string;
@type('string')
displayName: string;
@type('boolean')
owner: boolean;
@type('int32')
stash: number = 60;
@type('int32')
bet: number = 0;
@type('boolean')
connected: boolean;
@type('boolean')
playing: boolean;
@type('boolean')
enteringNextTurn: boolean;
@type('uint8')
seat: number;
@type('boolean')
dealer: boolean;
@type([CardPlaceholder])
hand = new ArraySchema<CardPlaceholder>();
@type(Prompt)
prompt: Prompt;
@filter(function (
this: Player,
client: Client,
value: string,
root: Schema) {
return this.sessionId === client.sessionId;
})
@type('number')
score: number = 0;
}
export class GameState extends Schema {
@type('boolean')
running: boolean = false;
@type('boolean')
paused: boolean = false;
@type('int32')
pot: number = 0;
@type('int32')
minimumBet: number = 10;
@type({ map: Player })
players = new MapSchema<Player>();
@type('number')
bg: number = 1;
@type('string')
roomOwner: string;
@type(Player)
player1: Player;
@type(Player)
player2: Player;
@type('number')
currentBet: number = 0;
@type('number')
remainingCards: number;
}

View File

@@ -4,15 +4,26 @@
"description": "A WebRTC playroom", "description": "A WebRTC playroom",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"devel": "nodemon server.js" "devel": "nodemon server.ts"
}, },
"author": "Domenico Testa", "author": "Domenico Testa",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@colyseus/command": "^0.1.6",
"@types/express": "^4.17.9",
"@types/express-session": "^1.17.3",
"@types/jest": "^26.0.19",
"@types/node": "^14.14.19",
"colyseus": "^0.14.6",
"ejs": "^3.1.5", "ejs": "^3.1.5",
"express": "^4.17.1", "express": "^4.17.1",
"express-session": "^1.17.1",
"nanoevents": "^5.1.10",
"peer": "^0.6.1", "peer": "^0.6.1",
"socket.io": "^3.0.4", "socket.io": "^3.0.4",
"ts-node": "^9.1.1",
"typedeck": "^1.5.2",
"typescript": "^4.1.3",
"uuid": "^8.3.2" "uuid": "^8.3.2"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -0,0 +1,91 @@
import { Client } from 'colyseus';
import { Command } from '@colyseus/command';
import { GameState } from '../../games/state';
import { GameRoom } from '../game';
export class SetUserStashCommand extends Command<GameState, { client: Client, sessionId: string, amount: number }> {
execute({ client, sessionId, amount }) {
this.state.players[sessionId].stash = amount;
const admin = this.state.players.get(client.sessionId);
const targetClient = this.room.clients.find((client) => { return client.sessionId === sessionId });
targetClient.send('notification', { text: `${admin.displayName} ha impostato il tuo stash a ${amount}`, type: 'success' });
}
}
export class AddToUserStashCommand extends Command<GameState, { client: Client, sessionId: string, amount: number }> {
execute({ client, sessionId, amount }) {
console.log('add-to-user-stash', client, sessionId, amount);
this.state.players[sessionId].stash = this.state.players[sessionId].stash + amount;
const admin = this.state.players.get(client.sessionId);
const targetClient = this.room.clients.find((client) => { return client.sessionId === sessionId });
targetClient.send('notification', { text: `${admin.displayName} ha aggiunto ${amount} al tuo stash`, type: 'success' });
}
}
export class RemoveFromUserStashCommand extends Command<GameState, { client: Client, sessionId: string, amount: number }> {
execute({ client, sessionId, amount }) {
const admin = this.state.players.get(client.sessionId);
const targetClient = this.room.clients.find((client) => { return client.sessionId === sessionId });
targetClient.send('notification', { text: `${admin.displayName} ha rimosso ${amount} dal tuo stash`, type: 'warning' });
this.state.players[sessionId].stash = Math.max(0, this.state.players[sessionId].stash - amount);
}
}
export class GiveRoomOwnershipCommand extends Command<GameState, { client: Client, sessionId: string }> {
execute({ client, sessionId }) {
const player = this.state.players.get(sessionId);
this.state.roomOwner = player.id;
this.state.players.forEach((p, index) => {
p.owner = p.id == player.id;
});
// sends a notification to the new owner
const newOwner = this.room.clients.find((client) => { return client.sessionId === sessionId });
newOwner.send('notification', { text: 'Sei il nuovo propietario della stanza' });
}
}
export class AssignSeatCommand extends Command<GameState, { client: Client, sessionId: string }> {
execute({ client, sessionId }) {
const player = this.state.players.get(sessionId);
const minimumStash = this.state.minimumBet * 2;
if (player.stash < minimumStash) {
client.send('notification', {
type: 'warning',
text: `Al giocatore servono almeno ${minimumStash} punti per sedersi al tavolo`
});
return;
}
if (this.state.running) {
player.enteringNextTurn = true;
} else {
const seat = (<GameRoom>this.room).nextAvailableSeat();
console.log('assigning seat to user:', player.displayName, seat);
player.playing = true;
player.seat = seat;
}
}
}
export class StartGameCommand extends Command<GameState, { client: Client }> {
execute({ client }) {
if (Array.from(this.state.players.values()).filter((el) => { return el.playing; }).length < 2) {
client.send('notification', {
type: 'warning',
text: 'Servono almeno 2 giocatori per cominciare una partita'
});
return;
}
this.state.running = true;
(<GameRoom>this.room).onStartGame();
}
}
export class PauseGameCommand extends Command<GameState, { client: Client }> {
execute() {
this.state.running = false;
}
}

View File

@@ -0,0 +1,654 @@
import { Client, Room } from 'colyseus';
import { Dispatcher } from '@colyseus/command';
import { createNanoEvents } from 'nanoevents';
import { Player as CardPlayer, Hand } from 'typedeck';
import {
GameState,
Player,
CardPlaceholder,
SerializedCard,
CardValue,
PromptButton,
PromptField,
Prompt,
} from '../games/state';
import {
SetUserStashCommand,
AddToUserStashCommand,
RemoveFromUserStashCommand,
GiveRoomOwnershipCommand,
AssignSeatCommand,
StartGameCommand,
PauseGameCommand
} from './commands/admin';
import { CartaNapoletana, SettemmezzoGameType } from '../games/banco';
import { assert } from 'console';
interface OneOffEvent {
[action: string]: (client: Client, message: any) => void
}
interface PlayerAction {
action: string
bet: number
}
export class GameRoom extends Room<GameState> {
private dispatcher = new Dispatcher(this);
private messageHandlers = createNanoEvents<OneOffEvent>();
private validateSession;
private gameType = new SettemmezzoGameType();
private deck;
private currentDealer: number = -1;
sleep = (milliseconds: number = 1000): Promise<void> => {
return new Promise<void>(resolve => {
this.clock.setTimeout(resolve, milliseconds);
});
}
getSeatedPlayers(): Player[] {
const players = Array.from<Player>(this.state.players.values());
return players.filter((p) => { return (p.playing) });
}
getPlayerBySeat(n: number): Player {
const players = Array.from<Player>(this.state.players.values());
return players.find((p) => { return (p.playing && p.seat === n) });
}
pMap(callbackFn: (value: Player, index: number, array: Player[]) => Player, thisArg?: any): Player[] {
const players = Array.from<Player>(this.state.players.values());
return players.map(callbackFn);
}
setDealer(n: number) {
this.pMap((player) => {
player.dealer = player.seat === n;
return player;
});
}
nextAvailableSeat = (): number => {
const playing = this.getSeatedPlayers();
return Math.max(...playing.map((p) => { return p.seat }), 0) + 1;
}
nextDealer = (): number => {
const players = this.getSeatedPlayers();
this.currentDealer = (this.currentDealer + 1) % players.length;
const dealerSeat = players[this.currentDealer].seat;
console.log('Setting dealer seat:', dealerSeat);
this.setDealer(dealerSeat);
return dealerSeat;
}
*nextPlayerGenerator(dealer: Player) {
const players = this.getSeatedPlayers();
const dealerIndex = players.indexOf(dealer);
let n = 1;
while (true) {
let p: Player = yield players[(dealerIndex + n) % players.length];
n += 1;
}
}
shuffleCards = () => {
console.log('Hard shuffling cards!');
this.gameType = new SettemmezzoGameType();
this.deck = this.gameType.createDeck();
this.deck.shuffle();
this.state.remainingCards = 40;
}
dealCard(player: Player, faceUp: boolean = false) {
const cardPlayer = new CardPlayer(player.displayName,
new Hand());
this.deck.deal(cardPlayer.getHand(), 1);
this.state.remainingCards -= 1;
const [card] = <CartaNapoletana[]>cardPlayer.getHand().takeCardsFromBottom(1);
console.log('Card dealt:', card, 'remaining:', this.state.remainingCards);
if (card === undefined) {
// FIXME: why this ever happens?
console.warn('Card was undefined, deck:', this.deck);
return;
}
const cardValue = new CardValue({ value: card.cardName, suit: card.suit });
const serializedCard = new SerializedCard({
owner: player.sessionId,
public: faceUp,
card: cardValue
});
player.hand.push(new CardPlaceholder({ card: serializedCard }));
}
publishCards = (player: Player) => {
player.hand.forEach(pc => {
pc.card.public = true;
});
}
tossAllHands = () => {
this.pMap((player) => {
player.hand = player.hand.filter((pc) => { return false });
player.prompt = new Prompt();
return player;
});
}
getPlayerAction(player: Player): Promise<PlayerAction> {
return new Promise<PlayerAction>(resolve => {
const unbind = this.messageHandlers.on('resolve-prompt', (client, message) => {
if (player.sessionId !== client.sessionId) {
console.log('Waiting for a different sessionId:', player.sessionId, client.sessionId);
return;
}
unbind();
console.log('Got player response:', message);
resolve(message);
});
});
}
hasJolly = (hand: CardPlaceholder[]): boolean => {
return undefined !== hand.find((pc) => {
const value = pc.card.card.value;
const suit = pc.card.card.suit;
return value === 9 && suit === 3;
});
}
calculateScore = (hand: CardPlaceholder[]) => {
let score = hand.reduce((accumulator, currentValue) => {
const cardValue = currentValue.card.card.value;
const cardSuit = currentValue.card.card.suit;
if (cardValue == 9 && cardSuit == 3) {
return accumulator + 0;
}
const v = (cardValue <= 6) ? cardValue + 1 : 0.5;
return accumulator + v;
}, 0);
const withJolly = this.hasJolly(hand);
if (withJolly) {
score += Math.floor(7.5 - score);
}
return { score, withJolly };
}
playHand = async (player: Player, placeBet: boolean) => {
let playerLoose = false;
let moreCards = true;
let betPlaced = false;
let score;
const prompt = player.prompt = new Prompt();
while (moreCards && !playerLoose) {
prompt.fields.splice(0, prompt.fields.length);
prompt.buttons.splice(0, prompt.buttons.length);
if (placeBet && !betPlaced) {
prompt.fields.push(new PromptField({
name: 'bet',
label: 'Quanto scommetti',
min: this.state.minimumBet,
max: Math.min(this.state.pot, player.stash),
value: this.state.minimumBet
}));
}
prompt.buttons.push(new PromptButton({
name: 'stand',
label: 'Sto bene',
type: 'primary'
}));
prompt.buttons.push(new PromptButton({
name: 'more',
label: 'Carta',
type: 'primary'
}));
// se é un quattro servito, offri la possibilitá di "bruciare"
const lucio = player.hand.find((c) => { return c.card.card.value === 3 });
if (player.hand.length == 1 && lucio !== undefined) {
console.log('LUCIO:', lucio, lucio.card);
prompt.buttons.push(new PromptButton({
name: 'discard',
label: 'Brucia!',
type: 'primary'
}));
}
prompt.visible = true;
const choice = await this.getPlayerAction(player);
console.log('Player choice was:', choice);
if (choice.action === 'discard') {
// mostra la carta
this.publishCards(player);
this.broadcast('notification', {
type: 'info',
text: `${player.displayName} brucia il quattro`
});
// aspetta un paio di secondi
await this.sleep(2000);
// dunque svuota la mano e serve un'altra carta coperta:
player.hand.pop();
this.dealCard(player, false);
} else {
moreCards = false;
}
if (choice.hasOwnProperty('bet') && choice.action !== 'discard') {
player.stash -= choice.bet;
this.state.currentBet += choice.bet;
betPlaced = true;
}
if (choice.action === 'more') {
this.dealCard(player, true);
moreCards = true;
}
// il giocatore ha sballato? -> perde e passa il turno
score = this.calculateScore(player.hand);
console.log('Score:', score);
player.score = score.score;
if (score.score > 7.5) {
console.log('Hai sballato fraté!');
playerLoose = true;
this.publishCards(player);
this.broadcast('notification', {
type: 'error',
text: `${player.displayName} ha sballato`
});
player.prompt.visible = false;
await this.sleep(3000);
} else if (score.score == 7.5) {
console.log('Sette e mezzo!!!!');
this.publishCards(player);
moreCards = false;
player.prompt.visible = false;
}
}
prompt.visible = false;
return { score, playerLoose };
}
pauseGameIfPlayersDontMeetRequirements = async (): Promise<void> => {
const poorPlayers = this.getSeatedPlayers().filter((player) => {
return player.stash < this.state.minimumBet * 2;
});
if (poorPlayers.length > 0) {
console.log('Pausing game since not all players meet requirements');
this.state.paused = true;
poorPlayers.forEach((player) => {
this.broadcast('notification', {
type: 'warning',
text: `${player.displayName} non ha abbastanza soldi per giocare`
});
});
return new Promise<void>(resolve => {
const unbind = this.messageHandlers.on('resume-game', (client, message) => {
console.log('RESUME GAME?');
const poorPlayers = this.getSeatedPlayers().filter((player) => {
return player.stash < this.state.minimumBet * 2;
});
if (poorPlayers.length > 0) {
this.broadcast('notification', {
type: 'warning',
text: `Tutti i giocatori al tavolo devono avere almeno ${this.state.minimumBet * 2} per riprendere la partita`
});
console.log('not resuming');
return;
}
console.log('resuming');
this.state.paused = false;
unbind();
resolve();
});
});
} else {
return Promise.resolve();
}
}
async onStartGame() {
console.log('Game started');
while (this.state.running) {
await this.pauseGameIfPlayersDontMeetRequirements();
// Letting in players waiting
this.pMap((player) => {
if (player.enteringNextTurn) {
const seat = this.nextAvailableSeat();
console.log('assigning seat to user:', player.displayName, seat);
player.enteringNextTurn = false;
player.seat = seat;
player.playing = true;
};
return player;
})
// collect the initial bets
this.getSeatedPlayers().map((player) => {
player.stash -= this.state.minimumBet;
this.state.pot += this.state.minimumBet;
return player;
});
// shuffle cards
this.shuffleCards();
this.broadcast('notification', {
type: 'info',
text: 'Le carte sono state mischiate perché il mazzo passa ad un nuovo mazziere'
});
// set the dealer
const dealerSeat = this.nextDealer();
this.state.player1 = this.getPlayerBySeat(dealerSeat);
console.log('Dealer player is:', this.state.player1.displayName);
this.broadcast('notification', {
type: 'info',
text: `${this.state.player1.displayName} é il nuovo banco`
});
// await this.sleep(3000);
const table = this.nextPlayerGenerator(this.state.player1);
while (this.state.pot > 0) {
const p: Player = <Player>table.next().value;
if (p === null) {
throw Error('nextPlayerGenerator didn\'t return a valid Player instance');
}
if (p === this.state.player1) {
const prompt = this.state.player1.prompt = new Prompt();
prompt.buttons.push(new PromptButton({
name: 'cash-out',
label: 'Prendi il piatto',
type: 'primary'
}));
prompt.buttons.push(new PromptButton({
name: 'another-round',
label: 'Ancora un altro giro',
type: 'secondary'
}));
prompt.visible = true;
const choice = await this.getPlayerAction(this.state.player1);
this.state.player1.prompt = new Prompt();
console.log('Player choice was:', choice);
if (choice.action === 'cash-out') {
this.broadcast('notification', {
type: 'info',
text: `Il banco (${this.state.player1.displayName}) prende ${this.state.pot} del piatto e passa la mano`
});
this.state.player1.stash += this.state.pot;
this.state.pot = 0;
await this.sleep(3000);
break;
} else {
this.broadcast('notification', {
type: 'info',
text: `Il banco (${this.state.player1.displayName}) ha deciso per un altro giro`
});
await this.sleep(3000);
continue;
}
}
await this.pauseGameIfPlayersDontMeetRequirements();
this.state.player2 = p;
console.log('Challenger player is:', this.state.player2.displayName);
// Deal draft cards
this.dealCard(this.state.player2, false);
this.state.player2.score = this.calculateScore(this.state.player2.hand).score;
this.dealCard(this.state.player1, false);
this.state.player1.score = this.calculateScore(this.state.player1.hand).score
// Let challenger play his hand
let challengerWins = false;
const challengerResult = await this.playHand(this.state.player2, true);
console.log('Challenger:', challengerResult);;
this.publishCards(this.state.player1);
if (!challengerResult.playerLoose) {
const dealerResult = await this.playHand(this.state.player1, false);
console.log('Dealer:', dealerResult);
this.publishCards(this.state.player2);
if (!dealerResult.playerLoose) {
challengerWins = challengerResult.score.score > dealerResult.score.score;
} else {
challengerWins = true;
}
} else {
challengerWins = false;
console.log('Dealer wins!');
}
await this.sleep(5000);
const jollyWasDealt = this.hasJolly(this.state.player1.hand) || this.hasJolly(this.state.player2.hand);
console.log('La matta é stata giocata? ', jollyWasDealt);
if (challengerWins) {
this.broadcast('notification', {
type: 'success',
text: `${this.state.player2.displayName} vince (${this.state.currentBet}) dal piatto`
});
this.state.player2.stash += this.state.currentBet * 2;
this.state.pot -= this.state.currentBet;
assert(this.state.pot >= 0);
await this.sleep(3000);
} else {
this.broadcast('notification', {
type: 'success',
text: `Il banco (${this.state.player1.displayName}) vince la mano`
});
this.state.pot += this.state.currentBet;
}
this.state.currentBet = 0;
// svuota le mani
this.tossAllHands();
if (jollyWasDealt) {
console.log('Shuffling deck since jolly was dealt in last hand');
this.shuffleCards();
this.broadcast('notification', {
type: 'info',
text: 'Le carte sono state mischiate perché la matta é stata estratta nell\'ultima mano'
});
await this.sleep(3000);
}
}
}
}
onAuth(client, options, request) {
console.log('onauth', options, request.session.user_id);
const user = this.validateSession(request.session.user_id);
console.log('Found user:', user);
return user;
}
onCreate(options) {
this.deck = this.gameType.createDeck();
this.deck.shuffle();
console.log('Deck created:', this.deck);
console.log('GameRoom instance created', this.roomId, options);
this.validateSession = options.validateSession;
this.setState(new GameState());
this.state.roomOwner = options.user_id;
this.onMessage('admin', (client, message) => this.onAdminCommand(client, message));
this.onMessage('webrtc', (client, message) => this.onWebRTCCommand(client, message));
this.onMessage('*', (client, type: string, message) => {
console.log('Relaying message:', type, message);
this.messageHandlers.emit(type, client, message);
});
this.clock.start();
// DEMO: rotates the background every 60 seconds
this.clock.setInterval(() => {
this.state.bg = 1 + (this.state.bg + 1) % 5;
}, 60000);
}
onJoin(client, options, user) {
console.log(`User ${user.display_name} (${user.user_id}) joined room ${this.roomId}`, options);
if (this.state.players.size === 0) {
console.log(`User ${user.display_name} (${user.user_id}) set as room ${this.roomId} owner`);
this.state.roomOwner = user.user_id;
}
const user_already_logged_in = Array.from(this.state.players.values()).find((item) => item.id === user.user_id);
if (user_already_logged_in) {
console.log('User was already in the game!', user_already_logged_in);
return;
}
this.state.players.set(client.sessionId, new Player({
id: user.user_id,
sessionId: client.sessionId,
displayName: user.display_name,
owner: user.user_id === this.state.roomOwner,
stash: 0,
connected: true,
playing: false,
dealer: false,
hand: []
}));
}
async onLeave(client, consented) {
console.log('Player leaving:', client.sessionId);
if (this.state.players.has(client.sessionId)) {
this.state.players[client.sessionId].connected = false;
}
try {
if (consented) {
throw new Error("consented leave");
}
// allow disconnected client to reconnect into this room until 60 seconds
await this.allowReconnection(client, 60);
// client returned! let's re-activate it.
this.state.players[client.sessionId].connected = true;
} catch (e) {
// 60 seconds expired. let's remove the client.
this.state.players.delete(client.sessionId);
// explicitly broadcasting the event to let WebRTC cleanup corectly
this.broadcast('player-left', client.sessionId);
}
}
onAdminCommand(client, message) {
console.log('Admin command received:', message);
const player = this.state.players.get(client.sessionId);
if (player.id !== this.state.roomOwner) {
console.warn('Received admin command from non-owner user:', client.sessionId, message);
return;
}
const admin_commands = {
// set user stash (session_id, amount)
'set-user-stash': SetUserStashCommand,
// add to user stash (session_id, amount)
'add-to-user-stash': AddToUserStashCommand,
// remove from user stash (session_id, amount)
'remove-from-user-stash': RemoveFromUserStashCommand,
// assign seat to player (session_id)
'assign-seat': AssignSeatCommand,
// demote player (session_id)
// shuffle seats
// give room ownership (session_id)
'give-room-ownership': GiveRoomOwnershipCommand,
// start game
'start-game': StartGameCommand,
// pause game
'pause-game': PauseGameCommand,
// set room name (new name)
// set room background (background)
};
if (!admin_commands.hasOwnProperty(message.command)) {
console.error("Invalid admin command", message);
return;
}
const commandClass = admin_commands[message.command];
this.dispatcher.dispatch(new commandClass(), { ...message.payload, client });
}
onWebRTCCommand(client, message) {
console.log('WebRTC command received:', message);
const player = this.clients.find((value) => { return value.sessionId === message.payload.targetId });
if (player === null) {
console.warn('Cannot find client with sessionId', message.payload.targetId);
return;
}
if (message.command === 'call-player') {
console.log('Relaying WebRTC call:', message.payload);
if (player === undefined) {
console.warn('Incoming call to an unknown player');
return;
}
player.send('incoming-call', message.payload);
}
if (message.command === 'answer-call') {
console.log('Relaying WebRTC call:', message.payload);
player.send('answer-call', message.payload);
}
}
}

View File

@@ -0,0 +1,181 @@
import { Server } from 'colyseus';
import * as express from 'express';
import { createServer } from 'http';
import * as session from 'express-session';
import { randomBytes } from 'crypto';
import { GameRoom } from './rooms/game';
interface User {
user_id: string;
display_name: string;
}
const connected_users: { [id: string]: User } = {};
const validateSession = (user_id => {
console.log(`Is ${user_id} in ${Object.keys(connected_users)}?`);
if (Object.keys(connected_users).includes(user_id)) {
const user_info = connected_users[user_id];
console.log('Yes!', user_info);
return user_info;
}
console.log('No!');
return false;
});
// - Augments built-in Node.js IncomingMessage to include "session"
// - Lets TypeScript recognize "request.session" during onAuth()
declare module 'http' {
interface IncomingMessage {
session: session.Session
}
}
const sessionParser = session({
secret: 'any secret string',
// store: new RedisStore({ client: redisClient })
});
const port = Number(process.env.port) || 3001;
const app = express();
app.use(sessionParser);
app.use(express.json());
app.use(express.static('../client/build'))
app.post('/api/login', (req, res) => {
// login to the server (a unique display name is enough)
const username = req.body.display_name;
console.log('Login request with display name', username, connected_users);
const existing_user = Object.values(connected_users).find(user => user.display_name === username);
if (existing_user) {
console.log('oh no, no no, oh no non ononononono');
res.status(401).json({ sto: 'cazzo' });
} else {
const random_id = `player-${randomBytes(16).toString('hex')}`;
connected_users[random_id] = {
user_id: random_id,
display_name: username,
};
req.session!['user_id'] = random_id;
req.session!['display_name'] = username;
console.log('oh yeah!', connected_users);
res.json({ user_id: random_id });
}
});
app.post('/api/logout', (req, res) => {
const user_id = req.session!['user_id'];
console.log('Logging out user:', user_id);
delete connected_users[user_id];
delete req.session!['user_id'];
delete req.session!['display_name'];
res.json({ bye: 'bye' });
});
app.get('/api/session', (req, res) => {
// returns session data
res.json(req.session!);
});
const gameServer = new Server({
server: createServer(app),
verifyClient: (info, next) => {
// Make 'session' available for the websocket connection (during onAuth())
sessionParser(info.req as any, {} as any, () => next(true));
}
});
gameServer.define('game', GameRoom, { validateSession: validateSession });
gameServer.listen(port, '0.0.0.0');
// Connection broker
// const peerServerOptions = {
// debug: true,
// path: '/domingo'
// };
// const peerServer = ExpressPeerServer(server, peerServerOptions);
// app.use('/peerjs', peerServer);
// const joined_users = {};
// const rooms = {};
// io.on('connection', socket => {
// let user = null;
// let session_id = null;
// socket.on('JOIN_AS', (username) => {
// console.log('JOIN_AS', username);
// if (username === null || username in Object.values(joined_users)) {
// socket.emit('ERROR', 'Lo username non é valido oppure risulta giá in uso');
// return;
// }
// session_id = uuidV4();
// user = username;
// joined_users[session_id] = user;
// socket.emit('JOINED', session_id);
// });
// socket.on('CREATE_ROOM', (session_token) => {
// if (session_token !== session_id) {
// socket.emit('ERROR', 'Non sei autorizzato a creare una stanza');
// return;
// }
// const roomId = uuidV4();
// rooms[roomId] = {
// owner: user,
// participants: {} // maps session tokens to peer ids
// };
// console.log(`Created new room ${roomId} for user ${user}`);
// socket.emit('ROOM_CREATED', roomId);
// });
// socket.on('JOIN_ROOM', (session_token, roomId, peerId, callback) => {
// console.log('DEBUG: JOIN_ROOM', session_token, roomId, peerId);
// if (roomId in rooms === false) {
// socket.emit('ERROR', 'Stanza non trovata');
// console.log(`Cercava ${roomId} in ${rooms}`);
// return;
// }
// if (peerId === null) {
// socket.emit('ERROR', 'Peer ID mancante nella richiesta');
// return;
// }
// if (session_token in joined_users === false) {
// socket.emit('ERROR', 'La sessione non é valida');
// return;
// }
// const user = joined_users[session_token];
// console.log(`User ${user} is joining room ${roomId}`);
// // Aggiorna la stanza con il peerId
// const user_obj = {
// user_id: session_token,
// display_name: user,
// peer: peerId
// };
// rooms[roomId].participants[session_token] = user_obj;
// // Annuncia l'utente nella stanza
// socket.join(roomId);
// socket.to(roomId).broadcast.emit('USER_CONNECTED', session_token, user_obj);
// // Restituisce la lista aggiornata dei giocatori della stanza
// callback({ participants: rooms[roomId].participants });
// });
// })

View File

@@ -0,0 +1,10 @@
{
"compilerOptions": {
"declaration": true,
"experimentalDecorators": true,
"target": "es6"
},
"include": [
"**/*.ts"
]
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,33 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
const ROOM_ID = "<%= roomId %>"
</script>
<script src="/socket.io/socket.io.js" defer></script>
<script src="https://unpkg.com/peerjs@1.3.1/dist/peerjs.min.js" defer></script>
<script src="/app.js" defer></script>
<title>Document</title>
</head>
<style>
#video-grid {
display: grip;
grid-template-rows: repeat(auto-fill, 300px);
grid-auto-rows: 300px;
}
video {
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
<body>
<div id="video-grid"></div>
</body>
</html>