Untitled

mail@pastecode.io avatar
unknown
javascript
a year ago
1.6 kB
3
Indexable
Never
const openCardsMemoized = useMemo(() => {
	return cards => {
		return cards.filter(card => card.isOpen);
	};
}, []);

useEffect(() => {
	if (gameType === 'VS Person') {
		socket.on('active-matching-game', gameObgReceive => {
			let index = gameObgReceive.index;
			setCards(cards => {
				const tempCards = [...cards];
				tempCards[index].isOpen = true;
				return [...tempCards];
			});
			if (openCardsMemoized(cards).length === 1) setTurn(true);
		});
		socket.on('user-left', () => {
			setConnectionStatus(DISCONNECTED);
		});
	}
}, [socket]);

useEffect(() => {
	console.log('im here');
	if (cards.length && numOfMatchedCards === cards.length) {
		let res = cards.length / 2;
		setWinner(numCardsFliped >= res ? 'win' : 'lose');
	}
	console.log('openCards', openCards.length);
	if (openCards.length === 2) {
		checkIfMatched();
	}
}, [turn]);

function checkIfMatched() {
	let firstCardId = gameType === 'VS Person' ? openCards[0]._doc._id : openCards[0]._id;
	let secondCardId = gameType === 'VS Person' ? openCards[1]._doc._id : openCards[1]._id;

	if (firstCardId !== secondCardId) {
		setTimeout(() => {
			setCards(cards => cards.map(card => ({ ...card, isOpen: false })));
		}, 700);
	} else {
		if (turn) setNumCardsFliped(numCardsFliped + 2);
		setTimeout(() => {
			setCards(cards => {
				return cards.map(card => {
					let cardID = gameType === 'VS Person' ? card._doc._id : card._id;
					return cardID === firstCardId || cardID === secondCardId
						? { ...card, isOpen: false, isMatched: true }
						: card;
				});
			});
		}, 1000);
	}
}