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+ organism . draw ( ) ;
11+ }
12+
13+ for ( const foodSource of foodSources ) {
14+ foodSource . draw ( ) ;
15+ }
16+
17+ if ( Math . random ( ) < newOrganismFrequency ) {
18+ addRandomOrganism ( ) ;
19+ }
20+
21+ if ( Math . random ( ) < newFoodSourceFrequency ) {
22+ addRandomFoodSource ( ) ;
23+ }
24+
25+ const { redCount, greenCount, blueCount } = countByDominantColor ( organisms , organism => organism . color ) ;
26+ organismsDataRed . push ( redCount ) ;
27+ organismsDataGreen . push ( greenCount ) ;
28+ organismsDataBlue . push ( blueCount ) ;
29+
30+ // Remove the oldest entry when the array length exceeds 100
31+ [ organismsDataRed , organismsDataGreen , organismsDataBlue ] . forEach ( data => {
32+ if ( data . length > 1000 ) {
33+ data . shift ( ) ;
34+ }
35+ } ) ;
36+
37+ const { redCount : foodRedCount , greenCount : foodGreenCount , blueCount : foodBlueCount } = countByDominantColor ( foodSources , foodSource => foodSource . colorPreference ) ;
38+ foodSourcesDataRed . push ( foodRedCount ) ;
39+ foodSourcesDataGreen . push ( foodGreenCount ) ;
40+ foodSourcesDataBlue . push ( foodBlueCount ) ;
41+
42+ // Remove the oldest entry when the array length exceeds 100
43+ [ foodSourcesDataRed , foodSourcesDataGreen , foodSourcesDataBlue ] . forEach ( data => {
44+ if ( data . length > 1000 ) {
45+ data . shift ( ) ;
46+ }
47+ } ) ;
48+
49+ frameCounter ++ ;
50+ document . getElementById ( 'frameCounter' ) . innerText = frameCounter ;
51+
52+ requestAnimationFrame ( gameLoop ) ;
53+ }
54+
55+ gameLoop ( ) ;
0 commit comments