diff --git a/.prettierrc.js b/.prettierrc.js index 65e18f5ff..a037d25c9 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -7,4 +7,5 @@ module.exports = { bracketSpacing: true, arrowParens: "avoid", htmlWhitespaceSensitivity: "ignore", + endOfLine: "auto", // для своместной разработки и с linux и с windows }; diff --git a/README.md b/README.md index 9b90842c4..44e31d627 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,8 @@ +## Оценка времени выполнения работы "Внедрение лидерборда" + +- **Ожидаемое время:** 6 часов +- **Фактическое время:** 5 часов + # MVP Карточная игра "Мемо" В этом репозитории реализован MVP карточкой игры "Мемо" по [тех.заданию](./docs/mvp-spec.md) diff --git a/src/components/Cards/Cards.jsx b/src/components/Cards/Cards.jsx index 7526a56c8..3eefa3cc2 100644 --- a/src/components/Cards/Cards.jsx +++ b/src/components/Cards/Cards.jsx @@ -1,17 +1,19 @@ +// src/components/Cards/Cards.jsx + import { shuffle } from "lodash"; -import { useEffect, useState } from "react"; +import { useEffect, useState, useContext } from "react"; +import { useNavigate } from "react-router-dom"; import { generateDeck } from "../../utils/cards"; import styles from "./Cards.module.css"; import { EndGameModal } from "../../components/EndGameModal/EndGameModal"; import { Button } from "../../components/Button/Button"; import { Card } from "../../components/Card/Card"; +import { GameModeContext } from "../../context/GameModeContext"; -// Игра закончилась +// Константы статусов игры const STATUS_LOST = "STATUS_LOST"; const STATUS_WON = "STATUS_WON"; -// Идет игра: карты закрыты, игрок может их открыть const STATUS_IN_PROGRESS = "STATUS_IN_PROGRESS"; -// Начало игры: игрок видит все карты в течении нескольких секунд const STATUS_PREVIEW = "STATUS_PREVIEW"; function getTimerValue(startDate, endDate) { @@ -26,9 +28,9 @@ function getTimerValue(startDate, endDate) { endDate = new Date(); } - const diffInSecconds = Math.floor((endDate.getTime() - startDate.getTime()) / 1000); - const minutes = Math.floor(diffInSecconds / 60); - const seconds = diffInSecconds % 60; + const diffInSeconds = Math.floor((endDate.getTime() - startDate.getTime()) / 1000); + const minutes = Math.floor(diffInSeconds / 60); + const seconds = diffInSeconds % 60; return { minutes, seconds, @@ -41,53 +43,71 @@ function getTimerValue(startDate, endDate) { * previewSeconds - сколько секунд пользователь будет видеть все карты открытыми до начала игры */ export function Cards({ pairsCount = 3, previewSeconds = 5 }) { - // В cards лежит игровое поле - массив карт и их состояние открыта\закрыта + const { livesMode } = useContext(GameModeContext); // Используем контекст + + // Состояние для игровых карт const [cards, setCards] = useState([]); // Текущий статус игры const [status, setStatus] = useState(STATUS_PREVIEW); - - // Дата начала игры + // Дата начала и окончания игры const [gameStartDate, setGameStartDate] = useState(null); - // Дата конца игры const [gameEndDate, setGameEndDate] = useState(null); - - // Стейт для таймера, высчитывается в setInteval на основе gameStartDate и gameEndDate + // Состояние таймера const [timer, setTimer] = useState({ seconds: 0, minutes: 0, }); + // Количество оставшихся жизней + const initialLives = livesMode ? 3 : 1; + const [lives, setLives] = useState(initialLives); + // Выбранные в данный момент карты + const [selectedCards, setSelectedCards] = useState([]); + // Флаг для блокировки кликов во время проверки пар + const [isProcessing, setIsProcessing] = useState(false); + + // Обновляем количество жизней при изменении режима игры + useEffect(() => { + setLives(initialLives); + }, [initialLives]); - function finishGame(status = STATUS_LOST) { + // Функция для завершения игры + function finishGame(gameStatus = STATUS_LOST) { setGameEndDate(new Date()); - setStatus(status); + setStatus(gameStatus); } + + // Функция для старта игры function startGame() { const startDate = new Date(); setGameEndDate(null); setGameStartDate(startDate); setTimer(getTimerValue(startDate, null)); setStatus(STATUS_IN_PROGRESS); + setLives(initialLives); + setSelectedCards([]); + setIsProcessing(false); } + + // Функция для перезапуска игры function resetGame() { setGameStartDate(null); setGameEndDate(null); setTimer(getTimerValue(null, null)); setStatus(STATUS_PREVIEW); + setLives(initialLives); + setSelectedCards([]); + setIsProcessing(false); } /** - * Обработка основного действия в игре - открытие карты. - * После открытия карты игра может пепереходит в следующие состояния - * - "Игрок выиграл", если на поле открыты все карты - * - "Игрок проиграл", если на поле есть две открытые карты без пары - * - "Игра продолжается", если не случилось первых двух условий + * Обработка открытия карты */ const openCard = clickedCard => { - // Если карта уже открыта, то ничего не делаем - if (clickedCard.open) { + if (isProcessing || clickedCard.open) { return; } - // Игровое поле после открытия кликнутой карты + + // Открываем кликнутую карту const nextCards = cards.map(card => { if (card.id !== clickedCard.id) { return card; @@ -101,56 +121,72 @@ export function Cards({ pairsCount = 3, previewSeconds = 5 }) { setCards(nextCards); - const isPlayerWon = nextCards.every(card => card.open); + // Добавляем карту в выбранные + const nextSelectedCards = [...selectedCards, clickedCard]; + setSelectedCards(nextSelectedCards); - // Победа - все карты на поле открыты - if (isPlayerWon) { - finishGame(STATUS_WON); - return; - } + if (nextSelectedCards.length === 2) { + setIsProcessing(true); + const [firstCard, secondCard] = nextSelectedCards; - // Открытые карты на игровом поле - const openCards = nextCards.filter(card => card.open); + const isMatch = firstCard.rank === secondCard.rank && firstCard.suit === secondCard.suit; - // Ищем открытые карты, у которых нет пары среди других открытых - const openCardsWithoutPair = openCards.filter(card => { - const sameCards = openCards.filter(openCard => card.suit === openCard.suit && card.rank === openCard.rank); + if (isMatch) { + // Карты совпали + setSelectedCards([]); - if (sameCards.length < 2) { - return true; - } + // Проверяем, выиграл ли игрок + const isPlayerWon = nextCards.every(card => card.open); + if (isPlayerWon) { + finishGame(STATUS_WON); + } + setIsProcessing(false); + } else { + // Карты не совпали + const nextLives = lives - 1; + setLives(nextLives); - return false; - }); - - const playerLost = openCardsWithoutPair.length >= 2; - - // "Игрок проиграл", т.к на поле есть две открытые карты без пары - if (playerLost) { - finishGame(STATUS_LOST); - return; + if (nextLives === 0) { + // Жизни закончились, игрок проиграл + finishGame(STATUS_LOST); + setIsProcessing(false); + } else { + // Закрываем карты обратно после задержки + setTimeout(() => { + setCards(currentCards => + currentCards.map(card => { + if (card.id === firstCard.id || card.id === secondCard.id) { + return { + ...card, + open: false, + }; + } + return card; + }), + ); + setSelectedCards([]); + setIsProcessing(false); + }, 1000); // Задержка в 1 секунду + } + } } - - // ... игра продолжается }; const isGameEnded = status === STATUS_LOST || status === STATUS_WON; - - // Игровой цикл + const navigate = useNavigate(); + // Инициализация игры useEffect(() => { - // В статусах кроме превью доп логики не требуется if (status !== STATUS_PREVIEW) { return; } - // В статусе превью мы if (pairsCount > 36) { alert("Столько пар сделать невозможно"); return; } setCards(() => { - return shuffle(generateDeck(pairsCount, 10)); + return shuffle(generateDeck(pairsCount)); }); const timerId = setTimeout(() => { @@ -162,7 +198,7 @@ export function Cards({ pairsCount = 3, previewSeconds = 5 }) { }; }, [status, pairsCount, previewSeconds]); - // Обновляем значение таймера в интервале + // Обновление таймера useEffect(() => { const intervalId = setInterval(() => { setTimer(getTimerValue(gameStartDate, gameEndDate)); @@ -172,6 +208,10 @@ export function Cards({ pairsCount = 3, previewSeconds = 5 }) { }; }, [gameStartDate, gameEndDate]); + const handleStartGame = () => { + navigate("/"); // Выполняем переход на главную страницу + }; + return (
@@ -185,17 +225,26 @@ export function Cards({ pairsCount = 3, previewSeconds = 5 }) { <>
min
-
{timer.minutes.toString().padStart("2", "0")}
+
{timer.minutes.toString().padStart(2, "0")}
.
sec
-
{timer.seconds.toString().padStart("2", "0")}
+
{timer.seconds.toString().padStart(2, "0")}
)}
- {status === STATUS_IN_PROGRESS ? : null} + {status === STATUS_IN_PROGRESS ? ( + <> + {livesMode && ( +
+

Жизни: {lives}

+
+ )} + + + ) : null}
@@ -209,7 +258,9 @@ export function Cards({ pairsCount = 3, previewSeconds = 5 }) { /> ))}
- + {isGameEnded ? (
{ + const name = playerName || "Пользователь"; + const totalTime = gameDurationMinutes * 60 + gameDurationSeconds; + + console.log("Отправляем данные:", { name, time: totalTime }); + + // Отправляем данные в формате JSON + fetch("https://wedev-api.sky.pro/api/leaderboard", { + method: "POST", + headers: { + // Убираем Content-Type, так как API требует это убрать + // Не указываем заголовок Content-Type + }, + body: JSON.stringify({ name, time: totalTime }), // Преобразуем данные в JSON + }) + .then(response => { + if (!response.ok) { + throw new Error(`Ошибка HTTP: ${response.status}`); + } + return response.json(); + }) + .then(data => { + console.log("Лидер добавлен:", data); // Лог для проверки результата + onClick(); // Закрытие модального окна + }) + .catch(error => { + console.error("Ошибка при добавлении лидера:", error); + }); + }; + return (
{imgAlt}

{title}

+ setPlayerName(e.target.value)} + />

Затраченное время:

- {gameDurationMinutes.toString().padStart("2", "0")}.{gameDurationSeconds.toString().padStart("2", "0")} + {gameDurationMinutes.toString().padStart(2, "0")}:{gameDurationSeconds.toString().padStart(2, "0")}
- - + {isWon && ( + <> + + + )} + {!isWon && } + + Перейти к лидерборду +
); } diff --git a/src/components/EndGameModal/EndGameModal.module.css b/src/components/EndGameModal/EndGameModal.module.css index 9368cb8b5..90defb71a 100644 --- a/src/components/EndGameModal/EndGameModal.module.css +++ b/src/components/EndGameModal/EndGameModal.module.css @@ -1,6 +1,6 @@ .modal { width: 480px; - height: 459px; + height: 570px; border-radius: 12px; background: #c2f5ff; display: flex; @@ -23,7 +23,7 @@ font-style: normal; font-weight: 400; line-height: 48px; - + text-align: center; margin-bottom: 28px; } @@ -49,3 +49,31 @@ margin-bottom: 40px; } +.input { + background-color: #ffffff; /* Светло-голубой фон */ + border: 1px solid #dcdcdc; /* Светлая рамка */ + border-radius: 10px; /* Закругленные углы */ + font-family: 'Arial', sans-serif; + font-size: 18px; + color: #000000; + padding: 7px; + outline: none; /* Убираем стандартную обводку */ + width: 250px; /* Полная ширина */ + text-align: center; /* Выравнивание плейсхолдера по центру */ + margin-bottom: 18px; +} + +.input::placeholder { + color: #9e9e9e; /* Цвет текста плейсхолдера */ + font-weight: normal; /* Обычный вес шрифта для плейсхолдера */ + text-align: center; /* Выравнивание плейсхолдера по центру */ +} +.leaderboardLink{ + padding-top: 18px; + padding-bottom: 8px; + font-family: StratosSkyeng; + font-size: 16px; /* размер шрифта */ + color: #605bc9; /* сиреневый цвет ссылки */ + text-decoration: underline; /* подчеркивание */ + transition: color 0.3s ease; /* плавное изменение цвета при наведении */ +} \ No newline at end of file diff --git a/src/context/GameModeContext.js b/src/context/GameModeContext.js new file mode 100644 index 000000000..d0d6976b4 --- /dev/null +++ b/src/context/GameModeContext.js @@ -0,0 +1,19 @@ +import { createContext, useState, useEffect } from "react"; + +export const GameModeContext = createContext({ + livesMode: false, + setLivesMode: () => {}, +}); + +export function GameModeProvider({ children }) { + const [livesMode, setLivesMode] = useState(() => { + const savedMode = localStorage.getItem("livesMode"); + return savedMode === "true"; + }); + + useEffect(() => { + localStorage.setItem("livesMode", livesMode); + }, [livesMode]); + + return {children}; +} diff --git a/src/index.js b/src/index.js index f689c5f0b..30c3029f6 100644 --- a/src/index.js +++ b/src/index.js @@ -3,10 +3,20 @@ import ReactDOM from "react-dom/client"; import "./index.css"; import { RouterProvider } from "react-router-dom"; import { router } from "./router"; +import { GameModeProvider } from "./context/GameModeContext"; // Импортируем обновленный провайдер const root = ReactDOM.createRoot(document.getElementById("root")); + +function App() { + return ( + + + + ); +} + root.render( - + , ); diff --git a/src/pages/GamePage/GamePage.jsx b/src/pages/GamePage/GamePage.jsx index a4be871db..61f7b102e 100644 --- a/src/pages/GamePage/GamePage.jsx +++ b/src/pages/GamePage/GamePage.jsx @@ -1,10 +1,43 @@ import { useParams } from "react-router-dom"; - import { Cards } from "../../components/Cards/Cards"; +import { useEffect } from "react"; export function GamePage() { const { pairsCount } = useParams(); + // Пример функции для отправки результата в API + const sendResultToLeaderboard = (name, time) => { + const result = { + name, + time, + level: pairsCount / 3, // предположим, что level = количество пар / 3 + }; + + fetch("https://wedev-api.sky.pro/api/leaderboard", { + method: "POST", + body: JSON.stringify(result), // JSON всё ещё отправляется, но без указания заголовка + }) + .then(response => response.json()) + .then(data => { + console.log("Результат успешно добавлен:", data); + }) + .catch(error => { + console.error("Ошибка при добавлении результата:", error); + }); + }; + + // Пример эффекта для отправки данных при завершении игры + useEffect(() => { + // Это может быть любая логика завершения игры + const gameEnded = true; // Предположим, что игра завершена + const playerName = "Игрок"; // Можно получить откуда-то имя игрока + const gameTime = 120; // Время игры в секундах + + if (gameEnded) { + sendResultToLeaderboard(playerName, gameTime); + } + }, [pairsCount]); // Этот эффект будет срабатывать при изменении количества пар + return ( <> diff --git a/src/pages/LeaderboardPage/LeaderboardPage.jsx b/src/pages/LeaderboardPage/LeaderboardPage.jsx new file mode 100644 index 000000000..5cc84a341 --- /dev/null +++ b/src/pages/LeaderboardPage/LeaderboardPage.jsx @@ -0,0 +1,76 @@ +import { useState, useEffect } from "react"; +import styles from "./LeaderboardPage.module.css"; +import { useNavigate } from "react-router-dom"; + +export function LeaderboardPage() { + const [leaders, setLeaders] = useState([]); + const navigate = useNavigate(); + + useEffect(() => { + fetch("https://wedev-api.sky.pro/api/leaderboard") + .then(response => response.json()) + .then(data => { + // Поскольку API не поддерживает level, фильтруем по времени или другому признаку + const thresholdForHardLevel = 30; // Порог для сложного уровня (время в секундах) + + // Фильтрация по порогу времени + const filteredLeaders = data.leaders.filter(leader => leader.time >= thresholdForHardLevel); + + // Сортируем лидеров по времени (чем меньше время, тем выше позиция) + const sortedLeaders = filteredLeaders.sort((a, b) => a.time - b.time); + + // Ограничиваем список до топ 10 игроков + const topLeaders = sortedLeaders.slice(0, 10); + + setLeaders(topLeaders); + }) + .catch(error => { + console.error("Ошибка при получении списка лидеров:", error); + }); + }, []); + + // Обработчик нажатия на кнопку + const handleStartGame = () => { + navigate("/"); // Выполняем переход на главную страницу + }; + + return ( +
+
+

Лидерборд

+
+ +
+
+ + + + + + + + + + {leaders.map((leader, index) => ( + + + + + + ))} + +
ПозицияПользовательВремя
{`# ${index + 1}`}{leader.name}{formatTime(leader.time)}
+
+ ); +} + +// Функция для форматирования времени в минуты и секунды +function formatTime(timeInSeconds) { + const minutes = Math.floor(timeInSeconds / 60) + .toString() + .padStart(2, "0"); + const seconds = (timeInSeconds % 60).toString().padStart(2, "0"); + return `${minutes}:${seconds}`; +} diff --git a/src/pages/LeaderboardPage/LeaderboardPage.module.css b/src/pages/LeaderboardPage/LeaderboardPage.module.css new file mode 100644 index 000000000..91bba5664 --- /dev/null +++ b/src/pages/LeaderboardPage/LeaderboardPage.module.css @@ -0,0 +1,68 @@ +.leaderboard { + background-color: #043864; + color: white; + padding: 20px; + border-radius: 8px; +} + +.title { + font-size: 24px; + font-weight: 100; + margin-bottom: 20px; + font-family: StratosSkyeng; +} + +.table { + width: 100%; + border-spacing: 0 10px; +} + +.table th, +.table td { + text-align: left; + padding: 10px 15px; + background-color: white; + color: #043864; + font-family: StratosSkyeng; +} + +.table th { + font-size: 16px; + font-weight: bold; + background-color: #d8eaff; + color: #043864; + +} + +.table tbody tr { + background-color: white; + border-radius: 16px; + box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.1); + /* Добавляем тень */ +} + +.buttonContainer { + text-align: right; + margin-top: 20px; +} + +.button { + background-color: #4caf50; + color: white; + padding: 10px 20px; + border: none; + border-radius: 5px; + cursor: pointer; + font-size: 16px; + font-family: StratosSkyeng; +} + +.button:hover { + background-color: #45a049; +} + +.header { + display: flex; + justify-content: space-between; + align-items: baseline; +} \ No newline at end of file diff --git a/src/pages/SelectLevelPage/SelectLevelPage.jsx b/src/pages/SelectLevelPage/SelectLevelPage.jsx index 758942e51..240f3e07b 100644 --- a/src/pages/SelectLevelPage/SelectLevelPage.jsx +++ b/src/pages/SelectLevelPage/SelectLevelPage.jsx @@ -1,11 +1,23 @@ import { Link } from "react-router-dom"; import styles from "./SelectLevelPage.module.css"; +import { useContext } from "react"; +import { GameModeContext } from "../../context/GameModeContext"; export function SelectLevelPage() { + const { livesMode, setLivesMode } = useContext(GameModeContext); + + const handleCheckboxChange = event => { + setLivesMode(event.target.checked); + }; + return (

Выбери сложность

+
  • @@ -23,6 +35,9 @@ export function SelectLevelPage() {
+ + Перейти к лидерборду +
); diff --git a/src/pages/SelectLevelPage/SelectLevelPage.module.css b/src/pages/SelectLevelPage/SelectLevelPage.module.css index 390ac0def..9348d81ba 100644 --- a/src/pages/SelectLevelPage/SelectLevelPage.module.css +++ b/src/pages/SelectLevelPage/SelectLevelPage.module.css @@ -1,3 +1,42 @@ +@import url('https://fonts.googleapis.com/css2?family=Cabin+Sketch:wght@400;700&display=swap'); + +.checkboxContainer { + display: flex; + align-items: center; + font-family: 'Cabin Sketch', cursive; /* Подключённый шрифт */ + font-size: 18px; + color: #333; +} + +.checkboxContainer input[type="checkbox"] { + width: 20px; + height: 20px; + margin-right: 10px; + position: relative; + cursor: pointer; + appearance: none; + background-color: #c2f5ff; + border: 2px solid #333; + border-radius: 5px; + transition: background-color 0.2s ease; + display: flex; + justify-content: center; + align-items: center; +} + +.checkboxContainer input[type="checkbox"]:checked::before { + content: '✓'; + font-size: 32px; /* Сделаем галочку чуть больше */ + color: #004980; + font-weight: bold; /* Галочка станет толще */ + position: absolute; + left: 63%; + top: 18%; + transform: translate(-50%, -50%); /* Выравнивание галочки по центру */ + font-family: 'Comic Sans MS', cursive; /* стили для галочки */ +} + + .container { width: 100%; min-height: 100%; @@ -62,3 +101,12 @@ .levelLink:visited { color: #0080c1; } +.leaderboardLink{ + padding-top: 18px; + padding-bottom: 8px; + font-family: StratosSkyeng; + font-size: 16px; /* размер шрифта */ + color: #004980; /* сиреневый цвет ссылки */ + text-decoration: underline; /* подчеркивание */ + transition: color 0.3s ease; /* плавное изменение цвета при наведении */ +} diff --git a/src/router.js b/src/router.js index da6e94b51..43cfca483 100644 --- a/src/router.js +++ b/src/router.js @@ -1,6 +1,7 @@ import { createBrowserRouter } from "react-router-dom"; import { GamePage } from "./pages/GamePage/GamePage"; import { SelectLevelPage } from "./pages/SelectLevelPage/SelectLevelPage"; +import { LeaderboardPage } from "./pages/LeaderboardPage/LeaderboardPage"; export const router = createBrowserRouter( [ @@ -12,6 +13,10 @@ export const router = createBrowserRouter( path: "/game/:pairsCount", element: , }, + { + path: "/leaderboard", // Добавлен маршрут для лидерборда + element: , + }, ], /** * basename нужен для корректной работы в gh pages