1+
2+ let frameCounter = 0 ;
3+
4+ function gameLoop ( ) {
5+ ctx . clearRect ( 0 , 0 , canvas . width , canvas . height ) ;
6+
7+ for ( const organism of organisms ) {
8+ organism . move ( ) ;
9+ organism . consumeFood ( ) ;
10+ if ( Math . random ( ) < organism . color . a ) {
11+ organism . reproduce ( ) ;
12+ }
13+ organism . draw ( ) ;
14+ }
15+
16+ for ( const foodSource of foodSources ) {
17+ foodSource . draw ( ) ;
18+ }
19+
20+ if ( Math . random ( ) < newOrganismFrequency ) {
21+ addRandomOrganism ( ) ;
22+ }
23+
24+ if ( Math . random ( ) < newFoodSourceFrequency ) {
25+ addRandomFoodSource ( ) ;
26+ }
27+
28+ const { redCount, greenCount, blueCount } = countByDominantColor ( organisms , organism => organism . color ) ;
29+ organismsDataRed . push ( redCount ) ;
30+ organismsDataGreen . push ( greenCount ) ;
31+ organismsDataBlue . push ( blueCount ) ;
32+
33+ // Remove the oldest entry when the array length exceeds 100
34+ [ organismsDataRed , organismsDataGreen , organismsDataBlue ] . forEach ( data => {
35+ if ( data . length > 100 ) {
36+ data . shift ( ) ;
37+ }
38+ } ) ;
39+
40+ const { redCount : foodRedCount , greenCount : foodGreenCount , blueCount : foodBlueCount } = countByDominantColor ( foodSources , foodSource => foodSource . colorPreference ) ;
41+ foodSourcesDataRed . push ( foodRedCount ) ;
42+ foodSourcesDataGreen . push ( foodGreenCount ) ;
43+ foodSourcesDataBlue . push ( foodBlueCount ) ;
44+
45+ // Remove the oldest entry when the array length exceeds 100
46+ [ foodSourcesDataRed , foodSourcesDataGreen , foodSourcesDataBlue ] . forEach ( data => {
47+ if ( data . length > 100 ) {
48+ data . shift ( ) ;
49+ }
50+ } ) ;
51+
52+ frameCounter ++ ;
53+ document . getElementById ( 'frameCounter' ) . innerText = frameCounter ;
54+
55+ requestAnimationFrame ( gameLoop ) ;
56+ }
57+
58+ gameLoop ( ) ;
0 commit comments