-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
108 lines (98 loc) · 2.66 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import * as React from "react";
import { StatusBar } from "expo-status-bar";
import { SafeAreaView, StyleSheet, Text, View } from "react-native";
import Card from "./Card";
const cards = [
// "🥹",
// "🗣️",
// "🦷",
// "🍑",
// "🌪️",
// "🌎",
"🐷",
"🪝",
"⚛️",
"🔑",
"🥕",
"🥑",
// "👻",
// "🥶",
// "🥵",
];
export default function App() {
const [board, setBoard] = React.useState(() => shuffle([...cards, ...cards]));
const [selectedCards, setSelectedCards] = React.useState([]);
const [matchedCards, setMatchedCards] = React.useState([]);
const [score, setScore] = React.useState(0);
React.useEffect(() => {
if (selectedCards.length < 2) return;
if (board[selectedCards[0]] === board[selectedCards[1]]) {
setMatchedCards([...matchedCards, ...selectedCards]);
setSelectedCards([]);
} else {
const timeoutId = setTimeout(() => setSelectedCards([]), 1000);
return () => clearTimeout(timeoutId);
}
}, [selectedCards]);
const handleTapCard = (index) => {
if (selectedCards.length >= 2 || selectedCards.includes(index)) return;
setSelectedCards([...selectedCards, index]);
setScore(score + 1);
};
const didPlayerWin = () => matchedCards.length === board.length;
return (
<SafeAreaView style={styles.container}>
<Text style={styles.title}>
{didPlayerWin() ? "Congratulations 🎉" : "Memory"}
</Text>
<Text style={styles.title}>Score: {score}</Text>
<View style={styles.board}>
{board.map((card, index) => {
const isTurnedOver =
selectedCards.includes(index) || matchedCards.includes(index);
return (
<Card
key={index}
isTurnedOver={isTurnedOver}
onPress={() => handleTapCard(index)}
>
{card}
</Card>
);
})}
</View>
<StatusBar style="light" />
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#0f172a",
alignItems: "center",
justifyContent: "start",
},
board: {
flexDirection: "row",
justifyContent: "center",
flexWrap: "wrap",
},
title: {
fontSize: 32,
fontWeight: "900",
color: "snow",
marginVertical: 15,
},
});
/**
* Returns the array shuffled into a random order.
* Do not edit this function.
*/
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const randomIndex = Math.floor(Math.random() * (i + 1));
// Swap the elements at i and randomIndex
[array[i], array[randomIndex]] = [array[randomIndex], array[i]];
}
return array;
}