@@ -27,50 +27,39 @@ function generateCells(cellCount) {
2727 return shuffle ( [ ...clearCells , ...knownCells , ...mineCells ] ) ;
2828}
2929
30- function createCellsStore ( ) {
31- const width = 100 ;
32- const height = 100 ;
33- const initial = {
34- width,
35- height,
36- cells : generateCells ( width * height )
37- } ;
38- const { subscribe, set, update } = writable ( initial ) ;
39- return {
40- subscribe,
41- reveal : idx =>
42- update ( state => {
43- state . cells [ idx ] . stateKnown = true ;
44- return state ;
45- } )
46- } ;
47- }
48- export const cellsStore = createCellsStore ( ) ;
49-
50- export const width = derived (
51- [ cellsStore ] ,
52- ( [ $cellsStore ] ) => $cellsStore . width
53- ) ;
54- export const height = derived (
55- [ cellsStore ] ,
56- ( [ $cellsStore ] ) => $cellsStore . height
57- ) ;
30+ export const width = writable ( 100 ) ;
31+ export const height = writable ( 100 ) ;
5832export const cellCount = derived (
5933 [ width , height ] ,
6034 ( [ $width , $height ] ) => $width * $height
6135) ;
36+ export const cellStores = generateCells ( get ( cellCount ) ) . map ( createCellStore ) ;
37+ export const surroundingStores = cellStores . map ( ( _ , idx ) =>
38+ createSurroundingsStore ( idx )
39+ ) ;
6240
63- export function deriveCellStore ( idx ) {
64- return derived ( [ cellsStore ] , ( [ $cellsStore ] ) => $cellsStore . cells [ idx ] ) ;
41+ export function regenerate ( ) {
42+ generateCells ( get ( cellCount ) ) . forEach ( ( newCell , idx ) =>
43+ cellStores [ idx ] . set ( newCell )
44+ ) ;
6545}
6646
67- export function deriveSurroundingsStore ( idx , width , height ) {
68- const idxs = surroundingIndices ( idx , width , height ) ;
69- const store = derived ( [ cellsStore ] , ( [ $cellsStore ] ) =>
70- idxs . map ( idx => $cellsStore . cells [ idx ] )
71- ) ;
47+ function createCellStore ( cell ) {
48+ const { subscribe, set, update } = writable ( cell ) ;
49+ return {
50+ subscribe,
51+ set,
52+ reveal : ( ) => update ( cell => ( { ...cell , stateKnown : true } ) )
53+ } ;
54+ }
55+
56+ export function createSurroundingsStore ( idx ) {
57+ const idxs = surroundingIndices ( idx , get ( width ) , get ( height ) ) ;
58+ const relevantStores = idxs . map ( idx => cellStores [ idx ] ) ;
59+ // @ts -ignore
60+ const store = derived ( relevantStores , values => values ) ;
7261 return {
7362 ...store ,
74- reveal : ( ) => idxs . forEach ( cellsStore . reveal )
75- }
63+ reveal : ( ) => relevantStores . forEach ( store => store . reveal ( ) )
64+ } ;
7665}
0 commit comments