@@ -16,6 +16,44 @@ class GameOfLife extends Component {
1616 populatedCells : ( props . startingPopulation || [ ] ) . map ( ( cell ) => {
1717 return cell [ 0 ] + ( cell [ 1 ] * props . width ) ;
1818 } ) ,
19+ border : this . props . border ,
20+ } ;
21+ }
22+
23+ cellIsPopulated ( populatedCells , x , y ) {
24+ let cellIndex = x + ( y * this . state . width ) ;
25+ return populatedCells . includes ( cellIndex ) ;
26+ }
27+
28+ getAdjacentCellIndices ( x , y ) {
29+ let left = x - 1 ;
30+ let right = x + 1 ;
31+ if ( this . state . border === 'marquee' ) {
32+ if ( left < 0 ) {
33+ left = this . state . width - 1 ;
34+ }
35+ if ( right >= this . state . width ) {
36+ right = 0 ;
37+ }
38+ } else {
39+ right = Math . min ( this . state . width - 1 , x + 1 ) ;
40+ }
41+
42+ let top = y - 1 ;
43+ let bottom = y + 1 ;
44+ if ( this . state . border === 'marquee' ) {
45+ if ( bottom >= this . state . height ) {
46+ bottom = 0 ;
47+ }
48+ if ( top < 0 ) {
49+ top = this . state . height - 1 ;
50+ }
51+ } else {
52+ bottom = Math . min ( this . state . height - 1 , y + 1 ) ;
53+ }
54+
55+ return {
56+ top, right, bottom, left,
1957 } ;
2058 }
2159
@@ -25,8 +63,14 @@ class GameOfLife extends Component {
2563 for ( let y = 0 ; y < this . state . height ; y ++ ) {
2664 const currentCellIndex = x + ( y * this . state . width ) ;
2765 let numberOfPopulatedNeighbours = 0 ;
28- for ( let nx = x - 1 ; nx <= Math . min ( this . state . width - 1 , x + 1 ) ; nx ++ ) {
29- for ( let ny = y - 1 ; ny <= Math . min ( this . state . height - 1 , y + 1 ) ; ny ++ ) {
66+ // let cellRight = x + 1 >= this.state.width ? 0 : x + 1;
67+ // let cellBelow = y + 1 >= this.state.height ? 0 : y + 1;
68+ const { top, right, bottom, left } = this . getAdjacentCellIndices ( x , y ) ;
69+ let xOptions = x === right ? [ left , x ] : [ left , x , right ] ;
70+ let yOptions = y === bottom ? [ top , y ] : [ top , y , bottom ] ;
71+
72+ for ( let nx of xOptions ) {
73+ for ( let ny of yOptions ) {
3074 let cellIndex = nx + ( ny * this . state . width ) ;
3175 let populated = populatedCells . includes ( cellIndex ) ;
3276 if ( ( nx !== x || ny !== y ) && populated ) {
@@ -132,11 +176,14 @@ GameOfLife.propTypes = {
132176 height : PropTypes . number ,
133177 generation : PropTypes . number ,
134178 start : PropTypes . bool ,
179+ gridBehaviour : PropTypes . bool ,
180+ border : PropTypes . oneOf ( [ 'hard' , 'marquee' ] ) ,
135181}
136182
137183GameOfLife . defaultProps = {
138184 generation : 0 ,
139185 start : false ,
186+ border : 'hard' ,
140187}
141188
142189export default GameOfLife ;
0 commit comments