1+ function createGrid ( rows , cols ) {
2+ const grid = document . getElementById ( 'grid' ) ;
3+ grid . innerHTML = '' ; // Clear any existing grid
4+
5+ for ( let r = 0 ; r < rows ; r ++ ) {
6+ for ( let c = 0 ; c < cols ; c ++ ) {
7+ const light = document . createElement ( 'div' ) ;
8+ light . classList . add ( 'light' ) ;
9+ light . dataset . row = r ;
10+ light . dataset . col = c ;
11+ light . addEventListener ( 'click' , ( ) => toggleLights ( r , c ) ) ;
12+ grid . appendChild ( light ) ;
13+ grid . style . gridTemplateColumns = `repeat(${ level } , 60px)` ;
14+ }
15+ }
16+ }
17+
18+ function toggleLights ( row , col ) {
19+ toggleLight ( row , col ) ;
20+ toggleLight ( row - 1 , col ) ; // Up
21+ toggleLight ( row + 1 , col ) ; // Down
22+ toggleLight ( row , col - 1 ) ; // Left
23+ toggleLight ( row , col + 1 ) ; // Right
24+ checkWin ( ) ;
25+ }
26+
27+ function toggleLight ( row , col ) {
28+ const light = document . querySelector ( `.light[data-row='${ row } '][data-col='${ col } ']` ) ;
29+ if ( light ) {
30+ light . classList . toggle ( 'off' ) ;
31+ }
32+
33+ }
34+
35+ function resetGame ( ) {
36+ const lights = document . querySelectorAll ( '.light' ) ;
37+ lights . forEach ( light => light . classList . remove ( 'off' ) ) ;
38+ }
39+
40+ let level = 3 ;
41+ const levelLimit = 9 ;
42+
43+ function startGame ( ) {
44+ createGrid ( level , level ) ;
45+ const lights = document . querySelectorAll ( '.light' ) ;
46+ }
47+
48+ function checkWin ( ) {
49+ const lights = document . querySelectorAll ( '.light' ) ;
50+ const isWin = Array . from ( lights ) . every ( light => light . classList . contains ( 'off' ) ) ;
51+ if ( isWin ) {
52+ if ( level === levelLimit ) {
53+ alert ( 'Congratulations! You have won all the levels!' ) ;
54+ } else {
55+ alert ( 'You win!' ) ;
56+ level ++ ; // Increase the level
57+ resetGame ( ) ;
58+ startGame ( ) ; // Start the next level
59+ }
60+ }
61+ }
0 commit comments