Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
"plugins": ["prettier"],
"rules": {
"camelcase": ["error", { "properties": "never" }],
"prettier/prettier": "error",
"prettier/prettier": [
"error",
{
"endOfLine": "auto"
}
],
"eqeqeq": ["error", "always"],
"no-unused-vars": ["error"]
}
Expand Down
7 changes: 4 additions & 3 deletions docs/mvp-spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@
Количество карточек для каждого уровня сложности можете назначать и свои или выбрать готовый пресет.

Предлагаем следующее пресеты:
- Легкий уровень - 6 карточек (3 пары)
- Средний уровень - 12 карточек (6 пар)
- Сложный уровень - 18 карточек (9 пар)

- Легкий уровень - 6 карточек (3 пары)
- Средний уровень - 12 карточек (6 пар)
- Сложный уровень - 18 карточек (9 пар)

Как только уровень сложности выбран, игроку показывается на игровой поле.

Expand Down
1 change: 1 addition & 0 deletions lefthook.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ pre-commit:
eslint:
glob: "*.{js,jsx}"
run: npm run lint
"prettier/prettier": ["error", { "endOfLine": "auto" }]
17 changes: 16 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"classnames": "^2.3.2",
"clsx": "^2.1.1",
"gh-pages": "^6.0.0",
"lodash": "^4.17.21",
"react": "^18.2.0",
Expand Down
12 changes: 2 additions & 10 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,8 @@
</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.
<div id="modal-root"></div>

To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<div id="root"></div>
</body>
</html>
29 changes: 29 additions & 0 deletions src/API/leaders.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
export async function getLeaders() {
try {
const response = await fetch("https://wedev-api.sky.pro/api/v2/leaderboard/", {
method: "GET",
});
const isResponseOk = response.ok;
const result = await response.json();
if (isResponseOk) {
return result.leaders;
} else {
throw new Error(result.error);
}
} catch (error) {
throw new Error(error.message);
}
}

//добавление лидера в список
export const addLeader = async data => {
const response = await fetch("https://wedev-api.sky.pro/api/v2/leaderboard/", {
method: "POST",
body: JSON.stringify(data),
});

if (!response.ok) {
throw new Error("Упс, ошибка");
}
return response.json();
};
90 changes: 89 additions & 1 deletion src/components/Cards/Cards.jsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { shuffle } from "lodash";
import { useEffect, useState } from "react";
import { useContext, useEffect, useState } from "react";
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 { EasyContext } from "../../context/Context";
import alohomora from "./images/alohomora.png";
import Modal from "../modal/Modal";

// Игра закончилась
const STATUS_LOST = "STATUS_LOST";
Expand All @@ -14,6 +17,11 @@ const STATUS_IN_PROGRESS = "STATUS_IN_PROGRESS";
// Начало игры: игрок видит все карты в течении нескольких секунд
const STATUS_PREVIEW = "STATUS_PREVIEW";

const SECOND_HINT = {
title: "Алохомора",
description: " Открывается случайная пара карт.",
};

function getTimerValue(startDate, endDate) {
if (!startDate && !endDate) {
return {
Expand Down Expand Up @@ -41,6 +49,7 @@ function getTimerValue(startDate, endDate) {
* previewSeconds - сколько секунд пользователь будет видеть все карты открытыми до начала игры
*/
export function Cards({ pairsCount = 3, previewSeconds = 5 }) {
const { isEasyMode, tries, setTries, setUsedHints } = useContext(EasyContext);
// В cards лежит игровое поле - массив карт и их состояние открыта\закрыта
const [cards, setCards] = useState([]);
// Текущий статус игры
Expand All @@ -57,6 +66,11 @@ export function Cards({ pairsCount = 3, previewSeconds = 5 }) {
minutes: 0,
});

const [isHovered, setIsHovered] = useState(false);

const handleMouseOver = () => setIsHovered(true);
const handleMouseOut = () => setIsHovered(false);

function finishGame(status = STATUS_LOST) {
setGameEndDate(new Date());
setStatus(status);
Expand All @@ -73,6 +87,9 @@ export function Cards({ pairsCount = 3, previewSeconds = 5 }) {
setGameEndDate(null);
setTimer(getTimerValue(null, null));
setStatus(STATUS_PREVIEW);
if (isEasyMode) {
setTries(3);
}
}

/**
Expand Down Expand Up @@ -127,6 +144,27 @@ export function Cards({ pairsCount = 3, previewSeconds = 5 }) {

// "Игрок проиграл", т.к на поле есть две открытые карты без пары
if (playerLost) {
if (isEasyMode) {
setTries(tries - 1);
if (tries === 1) {
finishGame(STATUS_LOST);
} else {
const newCards = cards.map(c => {
if (openCardsWithoutPair.find(card => card.id === c.id)) {
return {
...c,
open: false,
};
}
return c;
});

setTimeout(() => {
setCards(newCards);
}, 500);
}
return;
}
finishGame(STATUS_LOST);
return;
}
Expand Down Expand Up @@ -172,6 +210,35 @@ export function Cards({ pairsCount = 3, previewSeconds = 5 }) {
};
}, [gameStartDate, gameEndDate]);

const [isUsedHint, setIsUsedHint] = useState(0);

const handleClickAlohomora = () => {
if (isUsedHint > 2 || gameStartDate - gameEndDate === 0) return;
setUsedHints(true);
const obj = {};
const filtredCards = cards.filter(element => !element.open);
for (let i = 0; i < filtredCards.length; i++) {
if (obj[filtredCards[i].suit + " " + filtredCards[i].rank]) {
obj[filtredCards[i].suit + " " + filtredCards[i].rank] += 1;
} else {
obj[filtredCards[i].suit + " " + filtredCards[i].rank] = 1;
}
}
const onlyPairsCards = Object.entries(obj).filter(([key, value]) => value === 2);
const randomPair = onlyPairsCards[Math.floor(Math.random() * onlyPairsCards.length)][0];
const suitOfRandomPair = randomPair.split(" ")[0];
const rankOfRandomPair = randomPair.split(" ")[1];

const newCards = cards.map(el => {
if (el.suit === suitOfRandomPair && el.rank === rankOfRandomPair) {
return { ...el, open: true };
} else {
return el;
}
});
setIsUsedHint(prev => prev + 1);
setCards(newCards);
};
return (
<div className={styles.container}>
<div className={styles.header}>
Expand All @@ -195,7 +262,23 @@ export function Cards({ pairsCount = 3, previewSeconds = 5 }) {
</>
)}
</div>
<div className={styles.cheatBox}>
<button
onMouseOver={handleMouseOver}
onMouseOut={handleMouseOut}
onClick={handleClickAlohomora}
className={styles.alohomora}
>
<img src={alohomora} alt="alohomora" />
<div className={`${styles.popUpHintContent} ${styles.popUpHintActiveSecond}`}>
<h2 className={styles.popUpHintContenTitle}>{SECOND_HINT.title}</h2>
<p className={styles.popUpHintContentDescription}>{SECOND_HINT.description}</p>
</div>
</button>
</div>

{status === STATUS_IN_PROGRESS ? <Button onClick={resetGame}>Начать заново</Button> : null}
{isEasyMode && <span>Колличество жизней: {tries}</span>}
</div>

<div className={styles.cards}>
Expand All @@ -220,6 +303,11 @@ export function Cards({ pairsCount = 3, previewSeconds = 5 }) {
/>
</div>
) : null}
{isHovered && (
<Modal>
<div className={styles.popUpHint}></div>
</Modal>
)}
</div>
);
}
92 changes: 92 additions & 0 deletions src/components/Cards/Cards.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,95 @@

margin-bottom: -12px;
}

.cheatBox {
width: 151px;
height: 68px;
display: flex;
justify-content: space-between;
align-items: center;
}

.popUpHint {
opacity: 0.6;
background-color: #004980;
width: 100%;
height: 100vh;
z-index: 5000;
position: fixed;
}

.showAllCard {
display: flex;
justify-content: center;
align-items: center;
width: 68px;
height: 68px;
border-radius: 50%;
background-color: #c2f5ff;
position: relative;
cursor: pointer;
border: none;
z-index: 7000;
}

.alohomora {
display: flex;
justify-content: center;
align-items: center;
width: 68px;
height: 68px;
border-radius: 50%;
background-color: #c2f5ff;
position: relative;
cursor: pointer;
border: none;
z-index: 7000;
}

.popUpHintContent {
position: absolute;
width: 222px;
height: 223px;
background-color: #c2f5ff;
padding: 25px 20px 20px 20px;
bottom: -230px;
z-index: 6000;
border-radius: 12px;
}

.popUpHintContenTitle {
font-size: 18px;
font-weight: 700;
line-height: 24px;
color: #004980;
}

.popUpHintContentDescription {
font-size: 18px;
font-weight: 400;
line-height: 24px;
margin-top: 10px;
}

.popUpHintActiveFirst {
display: none;
}
.showAllCard:active .popUpHint {
display: block;
}
.showAllCard:hover .popUpHintActiveFirst {
display: block;
}

.popUpHintActiveSecond {
display: none;
}

.alohomora:hover .popUpHint {
display: block;
}

.alohomora:hover .popUpHintActiveSecond {
display: block;
}
Binary file added src/components/Cards/images/alohomora.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/components/Cards/images/showallcard.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading