First commit

This commit is contained in:
Jose134 2025-01-21 23:51:02 +01:00
commit 816a76dcfa
22 changed files with 5284 additions and 0 deletions

38
.gitignore vendored Normal file
View File

@ -0,0 +1,38 @@
# Dependencies
/node_modules
/.pnp
.pnp.js
# Testing
/coverage
# Production
/build
# Misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
# Vite
.vite
dist
# IDEs and editors
/.idea
/.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

32
Dockerfile Normal file
View File

@ -0,0 +1,32 @@
# Use an official node image as the base image
FROM node:20-alpine as build
# Set the working directory
WORKDIR /app
# Copy package.json and package-lock.json
COPY package.json package-lock.json ./
# Install dependencies
RUN npm install
# Copy the rest of the application code
COPY . .
# Build the application
RUN npm run build
# Use an official nginx image to serve the app
FROM nginx:alpine
# Copy the build output to the nginx html directory
COPY --from=build /app/dist /usr/share/nginx/html
# Copy nginx configuration file
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Expose port 80
EXPOSE 80
# Start nginx
CMD ["nginx", "-g", "daemon off;"]

8
README.md Normal file
View File

@ -0,0 +1,8 @@
# React + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh

38
eslint.config.js Normal file
View File

@ -0,0 +1,38 @@
import js from '@eslint/js'
import globals from 'globals'
import react from 'eslint-plugin-react'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
export default [
{ ignores: ['dist'] },
{
files: ['**/*.{js,jsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
parserOptions: {
ecmaVersion: 'latest',
ecmaFeatures: { jsx: true },
sourceType: 'module',
},
},
settings: { react: { version: '18.3' } },
plugins: {
react,
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...js.configs.recommended.rules,
...react.configs.recommended.rules,
...react.configs['jsx-runtime'].rules,
...reactHooks.configs.recommended.rules,
'react/jsx-no-target-blank': 'off',
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
},
]

13
index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Minesweeper</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

14
nginx.conf Normal file
View File

@ -0,0 +1,14 @@
server {
listen 80;
server_name localhost;
location / {
add_header "Access-Control-Allow-Origin" "*";
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, PUT, DELETE";
add_header "Access-Control-Allow-Headers" "Origin, X-Requested-With, Content-Type, Accept, Authorization";
if ($request_method = OPTIONS) {
return 204;
}
}
}

4446
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

30
package.json Normal file
View File

@ -0,0 +1,30 @@
{
"name": "minesweeper-front",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --host",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"dotenv": "^16.4.7",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"socket.io-client": "^4.8.1"
},
"devDependencies": {
"@eslint/js": "^9.17.0",
"@types/react": "^18.3.18",
"@types/react-dom": "^18.3.5",
"@vitejs/plugin-react": "^4.3.4",
"eslint": "^9.17.0",
"eslint-plugin-react": "^7.37.2",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.16",
"globals": "^15.14.0",
"vite": "^6.0.5"
}
}

6
src/App.css Normal file
View File

@ -0,0 +1,6 @@
#root {
max-width: 90%;
margin: 0 auto;
padding: 2rem;
text-align: center;
}

56
src/App.jsx Normal file
View File

@ -0,0 +1,56 @@
import { useEffect, useState } from 'react';
import './App.css';
import { setupSocketEffect, socket } from './socket';
import RoomSelection from './components/RoomSelection';
import Game from './components/Game';
const App = () => {
const [room, setRoom] = useState({});
useEffect(() => setupSocketEffect(socket, setRoom), []);
const handleDisconnect = () => {
socket.disconnect();
}
const handleJoinRoom = (username, room) => {
socket.connect();
socket.emit('joinRoom', { username, room });
}
const handleCreateRoom = (username, rows, cols, bombs, autoflag, gameMode) => {
socket.connect();
socket.emit('createRoom', { username, rows, cols, bombs, autoflag, gameMode });
};
const handleTileClick = (tileId) => {
socket.emit('tileClick', { tileId });
}
const handleSelectionConfirm = (tileId) => {
socket.emit('tileSelect', { tileId });
}
const handleTileFlag = (tileId) => {
socket.emit('tileFlag', { tileId });
}
return (
<>
{
room && room.id
? <Game
room={room}
playerSocketId={socket.id}
handleDisconnect={handleDisconnect}
handleTileClick={handleTileClick}
handleSelectionConfirm={handleSelectionConfirm}
handleTileFlag={handleTileFlag}
/>
: <RoomSelection handleJoinRoom={handleJoinRoom} handleCreateRoom={handleCreateRoom} />
}
</>
);
}
export default App

24
src/components/Board.css Normal file
View File

@ -0,0 +1,24 @@
.board {
padding: 2em;
display: grid;
grid-template-rows: repeat(10, 1fr);
grid-template-columns: repeat(10, 1fr);
gap: 0.15em;
}
.tile {
height: 3em;
width: 3em;
}
.revealed {
background-color: #141414;
}
.tile span {
font-size: 1.5em;
}
.tile-clicked {
background-color: #646cff;
}

75
src/components/Board.jsx Normal file
View File

@ -0,0 +1,75 @@
import PropTypes from 'prop-types';
import './Board.css';
const Board = ({ board, players, handleTileClick, handleTileFlag, setSelectedTile }) => {
const valueColors = {
1: '#6a8cff',
2: '#7fff7f',
3: '#ff6a6a',
4: '#9f7fff',
5: '#ff7f7f',
6: '#7fffff',
7: '#4f4f4f',
8: '#a0a0a0'
}
const playerColors = new Map();
players.forEach(player => playerColors.set(player.socketId, player.color));
const getStyle = (tile) => {
const style = {};
const tombstoneOf = players.find(player => player.tombstone === tile.id);
const selectionOf = players.find(player => player.selection === tile.id);
if (tombstoneOf) style.backgroundColor = playerColors.get(tombstoneOf.socketId);
else if (selectionOf) style.backgroundColor = playerColors.get(selectionOf.socketId);
if (tile.value !== undefined) style.color = valueColors[tile.value];
return style;
}
const getTileDisplay = (tile) => {
const tombstone = players.find(player => player.tombstone === tile.id);
if (tombstone) return '💀';
if (tile.flagged) return '🚩';
if (tile.bomb) return '💣';
if (tile.value) return tile.value;
return '';
}
const clickTile = (tile) => {
setSelectedTile(tile);
handleTileClick(tile);
}
const rightClickTile = (tile) => {
handleTileFlag(tile);
}
return (
<div className="board" style={{ gridTemplateColumns: `repeat(${board.cols}, 1fr)`, gridTemplateRows: `repeat(${board.rows}, 1fr)` }}>
{
board.tiles.map((tile) => (
<button
key={tile.id}
className={tile.value !== undefined ? "tile revealed" : "tile"}
style={getStyle(tile)}
onClick={() => clickTile(tile.id)}
onContextMenu={(evt) => {
evt.preventDefault();
rightClickTile(tile.id);
}}>
<span>{getTileDisplay(tile)}</span>
</button>
))
}
</div>
);
};
Board.propTypes = {
board: PropTypes.object.isRequired,
players: PropTypes.array.isRequired,
handleTileClick: PropTypes.func.isRequired,
handleTileFlag: PropTypes.func.isRequired,
setSelectedTile: PropTypes.func.isRequired
};
export default Board;

11
src/components/Game.css Normal file
View File

@ -0,0 +1,11 @@
.game {
display: flex;
flex-direction: row;
gap: 50px;
}
.confirm-button:disabled {
background-color: #646cff;
color: #ffffff;
cursor: not-allowed;
}

54
src/components/Game.jsx Normal file
View File

@ -0,0 +1,54 @@
import { PropTypes } from 'prop-types';
import Board from './Board';
import RoomInfo from './RoomInfo';
import './Game.css';
import { useState } from 'react';
const Game = ({ room, playerSocketId, handleDisconnect, handleTileClick, handleSelectionConfirm, handleTileFlag }) => {
const [selectedTile, setSelectedTile] = useState(null);
const isSelectionConfirmed = () => {
const player = room.players.find(player => player.socketId === playerSocketId);
return player && player.confirmedSelection;
}
return (
room && room.id ?
<div className="game">
<div>
<RoomInfo room={room} handleDisconnect={handleDisconnect} />
</div>
<div>
<div style={{ paddingLeft: '2em', paddingRight: '2em' }}>
{
room.gameMode === 'turns'
? <button
className="confirm-button"
disabled={isSelectionConfirmed()}
onClick={() => handleSelectionConfirm(selectedTile)}>
Confirm</button>
: <></>
}
</div>
<Board
board={room.board}
players={room.players}
handleTileClick={handleTileClick}
handleTileFlag={handleTileFlag}
setSelectedTile={setSelectedTile} />
</div>
</div>
: <h1>Loading</h1>
);
}
Game.propTypes = {
room: PropTypes.object.isRequired,
playerSocketId: PropTypes.string.isRequired,
handleDisconnect: PropTypes.func.isRequired,
handleTileClick: PropTypes.func.isRequired,
handleSelectionConfirm: PropTypes.func.isRequired,
handleTileFlag: PropTypes.func.isRequired
};
export default Game;

View File

@ -0,0 +1,31 @@
.container {
width: 200px;
text-align: left;
}
h2 {
margin-bottom: -0.5em;
}
button {
width: 100%;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: flex;
align-items: center;
margin: 0.5em 0;
}
.player-color-indicator {
width: 1em;
height: 1em;
border-radius: 50%;
display: inline-block;
margin-right: 0.5em;
}

View File

@ -0,0 +1,39 @@
import { PropTypes } from 'prop-types';
import './RoomInfo.css';
const RoomInfo = ({ room, handleDisconnect }) => {
return (
<div className="container">
{
room.gameState === "lost"
? <h1>Game Over</h1>
:
room.gameState === "won"
? <h1>Victory</h1>
: <></>
}
<h2>Room: {room.id}</h2>
<p>{room.board.cols}&#10799;{room.board.rows} &ndash; {room.board.bombs} bombs</p>
<button onClick={() => handleDisconnect()}>Disconnect</button>
<h3>Players:</h3>
<ul style={{ listStyleType: 'none' }}>
{
room.players.map((user, idx) =>
<li key={idx}>
<span className="player-color-indicator" style={{ backgroundColor: user.color }}></span>
{user.tombstone ? <span>💀</span> : <></>}
<span>{user.name}</span>
{user.confirmedSelection ? <span></span> : <></>}
</li>)
}
</ul>
</div>
);
}
RoomInfo.propTypes = {
room: PropTypes.object.isRequired,
handleDisconnect: PropTypes.func.isRequired
};
export default RoomInfo;

View File

@ -0,0 +1,76 @@
.room-selection {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
margin-top: 20px;
}
.room-selection h1 {
font-size: 3.2em;
line-height: 1.1;
}
.room-selection > div {
margin: 0 50px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
}
.separator {
padding: 0;
border: 2px solid #646cff;
width: 0px;
height: 250px;
border-radius: 3px;
}
.room-selection button {
width: 100%;
height: 3em;
}
.input-group {
width: 100%;
display: flex;
flex-direction: row;
gap: 5px;
}
.input-group label {
flex: 1;
text-align: right;
margin-right: 10px;
}
.input-group input {
flex: 2;
}
.input-group-buttons {
width: 100%;
display: flex;
flex-direction: column;
gap: 5px;
}
.input-group-buttons div {
display: flex;
flex-direction: row;
gap: 5px;
}
.input-group-buttons button {
width: 100%;
height: 2.5em;
cursor: pointer;
}
.input-group-buttons button:disabled {
background-color: #646cff;
color: #f9f9f9;
cursor: unset;
}

View File

@ -0,0 +1,140 @@
import PropTypes from 'prop-types';
import { useState } from 'react';
import './RoomSelection.css';
const RoomJoin = ({ handleJoinRoom }) => {
const [username, setUsername] = useState('');
const [room, setRoom] = useState('');
const joinRoom = () => {
handleJoinRoom(username, room);
}
return (
<div id="join-room">
<div className="input-group">
<label>Username</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="input-group">
<label>Room ID</label>
<input
type="text"
value={room}
onChange={(e) => setRoom(e.target.value)}
/>
</div>
<button onClick={joinRoom}>Join Room</button>
</div>
);
}
const RoomCreate = ({ handleCreateRoom }) => {
const [username, setUsername] = useState('');
const [rows, setRows] = useState(16);
const [cols, setCols] = useState(16);
const [bombs, setBombs] = useState(40);
const [autoflag, setAutoflag] = useState(false);
const [gameMode, setGameMode] = useState("realtime");
const createRoom = () => {
handleCreateRoom(username, rows, cols, bombs, autoflag, gameMode);
}
return (
<div id="create-room">
<div className="input-group">
<label>Username</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="input-group">
<label>Rows</label>
<input
type="number"
value={rows}
onChange={(e) => setRows(e.target.value)}
/>
</div>
<div className="input-group">
<label>Columns</label>
<input
type="number"
value={cols}
onChange={(e) => setCols(e.target.value)}
/>
</div>
<div className="input-group">
<label>Bombs</label>
<input
type="number"
value={bombs}
onChange={(e) => setBombs(e.target.value)}
/>
</div>
{/* <div className="input-group">
<label>Autoflag</label>
<input
type="checkbox"
value={autoflag}
onChange={(e) => setAutoflag(e.target.value)}
/>
</div> */}
<div className="input-group-buttons">
<div>
<label>Autoflag</label>
</div>
<div>
<button disabled={!autoflag} onClick={() => setAutoflag(false)}>No</button>
<button disabled={autoflag} onClick={() => setAutoflag(true)}>Yes</button>
</div>
</div>
<div className="input-group-buttons">
<div>
<label>Game Mode</label>
</div>
<div>
<button disabled={gameMode === "realtime"} onClick={() => setGameMode("realtime")}>Realtime</button>
<button disabled={gameMode === "turns"} onClick={() => setGameMode("turns")}>Turn based</button>
</div>
</div>
<button onClick={createRoom}>Create Room</button>
</div>
);
}
const RoomSelection = ({ handleCreateRoom, handleJoinRoom }) => {
return (
<>
<h1>Minesweeper</h1>
<div className="room-selection">
<RoomJoin handleJoinRoom={handleJoinRoom} />
<div className="separator"></div>
<RoomCreate handleCreateRoom={handleCreateRoom} />
</div>
</>
);
}
RoomCreate.propTypes = {
handleCreateRoom: PropTypes.func.isRequired,
};
RoomJoin.propTypes = {
handleJoinRoom: PropTypes.func.isRequired,
};
RoomSelection.propTypes = {
handleCreateRoom: PropTypes.func.isRequired,
handleJoinRoom: PropTypes.func.isRequired,
};
export default RoomSelection;

70
src/index.css Normal file
View File

@ -0,0 +1,70 @@
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
display: flex;
align-items: center;
justify-content: center;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
/* @media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
} */

10
src/main.jsx Normal file
View File

@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
)

65
src/socket.js Normal file
View File

@ -0,0 +1,65 @@
import process from 'process';
import { io } from 'socket.io-client';
const URL = process.env.BACKEND_URL || 'http://localhost:3001';
export const socket = io(URL, {
autoConnect: false,
transports: ['websocket'],
withCredentials: true,
});
export const setupSocketEffect = (socket, setRoom) => {
const socketHandlers = [
{
event: 'connect',
handler: () => {
}
},
{
event: 'disconnect',
handler: () => {
setRoom(null);
}
},
{
event: 'error',
handler: (error) => {
console.error(error);
}
},
{
event: 'youJoinedRoom',
handler: (data) => {
setRoom({ ...data });
}
},
{
event: 'roomUserJoined',
handler: (data) => {
setRoom({ ...data });
}
},
{
event: 'roomUserLeft',
handler: (data) => {
setRoom({ ...data });
}
},
{
event: 'updateRoom',
handler: (data) => {
setRoom({ ...data });
}
}
];
socketHandlers.forEach(({ event, handler }) => {
socket.on(event, handler);
});
return () => {
socketHandlers.forEach(({ event, handler }) => {
socket.off(event, handler);
});
};
};

8
vite.config.js Normal file
View File

@ -0,0 +1,8 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
base: "http://localhost:5173"
})