File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change @@ -36,7 +36,44 @@ <h1>Whack-a-mole! <span class="score">0</span></h1>
36
36
const holes = document . querySelectorAll ( '.hole' ) ;
37
37
const scoreBoard = document . querySelector ( '.score' ) ;
38
38
const moles = document . querySelectorAll ( '.mole' ) ;
39
+ let lastIndex ;
40
+ let timeUp = true ;
41
+
42
+ function randomTime ( min , max ) {
43
+ return Math . round ( Math . random ( ) * ( max - min ) + min ) ;
44
+ }
39
45
46
+ function randomHole ( holes ) {
47
+ const index = Math . floor ( Math . random ( ) * holes . length ) ;
48
+ if ( index === lastIndex ) {
49
+ return randomHole ( holes ) ;
50
+ }
51
+ lastIndex = index ;
52
+ return holes [ index ] ;
53
+ }
54
+
55
+ function showMole ( ) {
56
+ const hole = randomHole ( holes ) ;
57
+ hole . classList . add ( 'up' ) ;
58
+ setTimeout ( ( ) => {
59
+ hole . classList . remove ( 'up' ) ;
60
+ if ( ! timeUp ) showMole ( ) ;
61
+ } , randomTime ( 200 , 1000 ) ) ;
62
+ }
63
+
64
+ function startGame ( ) {
65
+ timeUp = false ;
66
+ scoreBoard . textContent = 0 ;
67
+ showMole ( ) ;
68
+ setTimeout ( ( ) => timeUp = true ) ;
69
+ }
70
+
71
+ function cachedMole ( ) {
72
+ scoreBoard . textContent = parseInt ( scoreBoard . textContent ) + 1 ;
73
+ this . parentElement . classList . remove ( 'up' ) ;
74
+ }
75
+
76
+ moles . forEach ( mole => mole . addEventListener ( 'click' , cachedMole ) ) ;
40
77
</ script >
41
78
</ body >
42
79
</ html >
You can’t perform that action at this time.
0 commit comments