1
+ document . addEventListener ( 'DOMContentLoaded' , function ( ) {
2
+ const canvas = document . getElementById ( 'gameCanvas' ) ;
3
+ const ctx = canvas . getContext ( '2d' ) ;
4
+ const scoreDisplay = document . getElementById ( 'score' ) ;
5
+ const fruitSize = 20 ;
6
+ let score = 0 ;
7
+ let fruits = [ ] ;
8
+ let player = {
9
+ x : canvas . width / 2 - fruitSize / 2 ,
10
+ y : canvas . height - fruitSize * 2 ,
11
+ width : fruitSize ,
12
+ height : fruitSize ,
13
+ dx : 0
14
+ } ;
15
+
16
+ function drawPlayer ( ) {
17
+ ctx . fillStyle = 'blue' ;
18
+ ctx . fillRect ( player . x , player . y , player . width , player . height ) ;
19
+ }
20
+
21
+ function drawFruit ( fruit ) {
22
+ ctx . fillStyle = 'yellow' ;
23
+ ctx . beginPath ( ) ;
24
+ ctx . arc ( fruit . x , fruit . y , fruitSize / 2 , 0 , Math . PI * 2 ) ;
25
+ ctx . fill ( ) ;
26
+ }
27
+
28
+ function updateFruits ( ) {
29
+ if ( Math . random ( ) < 0.02 ) {
30
+ fruits . push ( {
31
+ x : Math . random ( ) * ( canvas . width - fruitSize ) ,
32
+ y : 0 ,
33
+ dy : 2
34
+ } ) ;
35
+ }
36
+
37
+ fruits . forEach ( ( fruit , index ) => {
38
+ fruit . y += fruit . dy ;
39
+
40
+ if ( fruit . y > canvas . height ) {
41
+ fruits . splice ( index , 1 ) ;
42
+ }
43
+
44
+ if (
45
+ fruit . x < player . x + player . width &&
46
+ fruit . x + fruitSize > player . x &&
47
+ fruit . y < player . y + player . height &&
48
+ fruit . y + fruitSize > player . y
49
+ ) {
50
+ score ++ ;
51
+ scoreDisplay . textContent = score ;
52
+ fruits . splice ( index , 1 ) ;
53
+ }
54
+ } ) ;
55
+ }
56
+
57
+ function drawFruits ( ) {
58
+ fruits . forEach ( fruit => drawFruit ( fruit ) ) ;
59
+ }
60
+
61
+ function clearCanvas ( ) {
62
+ ctx . clearRect ( 0 , 0 , canvas . width , canvas . height ) ;
63
+ }
64
+
65
+ function updatePlayer ( ) {
66
+ player . x += player . dx ;
67
+
68
+ if ( player . x < 0 ) {
69
+ player . x = 0 ;
70
+ } else if ( player . x + player . width > canvas . width ) {
71
+ player . x = canvas . width - player . width ;
72
+ }
73
+ }
74
+
75
+ function updateGame ( ) {
76
+ clearCanvas ( ) ;
77
+ drawPlayer ( ) ;
78
+ drawFruits ( ) ;
79
+ updateFruits ( ) ;
80
+ updatePlayer ( ) ;
81
+ requestAnimationFrame ( updateGame ) ;
82
+ }
83
+
84
+ function movePlayer ( e ) {
85
+ if ( e . key === 'ArrowLeft' ) {
86
+ player . dx = - 5 ;
87
+ } else if ( e . key === 'ArrowRight' ) {
88
+ player . dx = 5 ;
89
+ }
90
+ }
91
+
92
+ function stopPlayer ( ) {
93
+ player . dx = 0 ;
94
+ }
95
+
96
+ document . addEventListener ( 'keydown' , movePlayer ) ;
97
+ document . addEventListener ( 'keyup' , stopPlayer ) ;
98
+
99
+ updateGame ( ) ;
100
+ } ) ;
101
+
0 commit comments