1
+ import { useEffect , useState } from 'react' ;
2
+ import './App.css' ;
3
+
4
+ const TILE_COLORS = [ 'red' , 'green' , 'blue' , 'yellow' , 'Red' , 'Green' , 'Blue' , 'Yellow' ] ;
5
+
6
+ export default function MemoryGame ( ) {
7
+ const [ myColors , setMyColors ] = useState < any > ( [ ] ) ;
8
+ const [ tiles , setTiles ] = useState < any > ( [ ] ) ;
9
+ const [ counter , setCounter ] = useState < number > ( 1 ) ;
10
+ const [ selected , setSelected ] = useState < any > ( [ ] ) ;
11
+
12
+ useEffect ( ( ) => {
13
+ setMyColors ( TILE_COLORS ) ;
14
+ shuffle ( TILE_COLORS ) ;
15
+ } , [ ] ) ;
16
+ // Write your code here.
17
+ function handleColor ( item : any ) {
18
+ setTiles ( [ ...tiles , item ] ) ;
19
+ setCounter ( ( counter ) => counter + 1 ) ;
20
+ if ( counter === 1 ) {
21
+ if ( tiles [ 0 ] ?. toLowerCase ( ) === item ?. toLowerCase ( ) ) {
22
+ setSelected ( [ ...selected , tiles [ 0 ] , item ] ) ;
23
+ }
24
+ setTimeout ( ( ) => {
25
+ setTiles ( [ ] ) ;
26
+ setCounter ( 0 ) ;
27
+ } , 500 ) ;
28
+ }
29
+ }
30
+ return (
31
+ < >
32
+ < h1 > Memory</ h1 >
33
+ < div className = "board" >
34
+ { myColors &&
35
+ myColors . map ( ( item : string , index : number ) => (
36
+ < div
37
+ key = { index }
38
+ style = { {
39
+ background : tiles . includes ( item ) ? item : selected . includes ( item ) ? item : 'white' ,
40
+ } }
41
+ className = { `tile ${ tiles . includes ( item ) ? item : selected . includes ( item ) ? item : '' } ` }
42
+ onClick = { ( ) => handleColor ( item ) }
43
+ > </ div >
44
+ ) ) }
45
+ </ div >
46
+ { selected . length === TILE_COLORS . length && (
47
+ < >
48
+ < h1 > You are the Winner</ h1 >
49
+ < button
50
+ onClick = { ( ) => {
51
+ setSelected ( [ ] ) ;
52
+ shuffle ( myColors ) ;
53
+ setMyColors ( TILE_COLORS ) ;
54
+ } }
55
+ >
56
+ Restart
57
+ </ button >
58
+ </ >
59
+ ) }
60
+ </ >
61
+ ) ;
62
+ }
63
+
64
+ /**
65
+ * Returns the array shuffled into a random order.
66
+ * Do not edit this function.
67
+ */
68
+ function shuffle ( array : string [ ] ) {
69
+ for ( let i = array . length - 1 ; i > 0 ; i -- ) {
70
+ const randomIndex = Math . floor ( Math . random ( ) * ( i + 1 ) ) ;
71
+
72
+ [ array [ i ] , array [ randomIndex ] ] = [ array [ randomIndex ] , array [ i ] ] ;
73
+ }
74
+ return array ;
75
+ }
0 commit comments