- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGamePanel.java
More file actions
Latest commit
244 lines (226 loc) · 7.52 KB
/
Copy pathGamePanel.java
File metadata and controls
244 lines (226 loc) · 7.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
importjavax.swing.*;
importjava.awt.*;
importjava.awt.event.*;
importjava.util.Random;
importjavax.swing.JPanel;
/**
* The GamePanel class is a JPanel that implements the core functionality of the Snake game.
* It handles the game logic, drawing, and user input.
*
* <p>This class includes methods to start the game, draw the game components,
* generate new apples, move the snake, check for collisions, and display the game over screen.</p>
*
* <p>The game board is represented as a grid, with the snake moving to eat apples and grow in size.
* The game ends if the snake collides with itself or the walls.</p>
*
* @author Pranav Kale
*/
publicclassGamePanelextendsJPanelimplementsActionListener {
staticfinalintSCREEN_WIDTH = 600;
staticfinalintSCREEN_HEIGHT = 600;
staticfinalintUNIT_SIZE = 25;
staticfinalintGAME_UNITS = (SCREEN_WIDTH * SCREEN_HEIGHT)/UNIT_SIZE;
staticfinalintDELAY = 75;
finalintx[] = newint[GAME_UNITS];
finalinty[] = newint[GAME_UNITS];
intbodyParts = 6;
intapplesEaten;
intappleX;
intappleY;
chardirection = 'R';
booleanrunning = false;
Timertimer;
Randomrandom;
/**
* Constructs the GamePanel, sets its properties, and starts the game.
*/
GamePanel() {
random = newRandom();
this.setPreferredSize(newDimension(SCREEN_WIDTH,SCREEN_HEIGHT));
this.setBackground(newColor(88, 184, 84));
this.setFocusable(true);
this.addKeyListener(newMyKeyAdapter());
startGame();
}
/**
* Starts the game by generating a new apple, setting the game running state to true,
* and starting the game timer.
*/
publicvoidstartGame() {
newApple();
running = true;
timer = newTimer(DELAY, (ActionListener) this);
timer.start();
}
/**
* Overrides the paintComponent method to draw the game elements on the panel.
*
* @param g the Graphics object to protect
*/
publicvoidpaintComponent(Graphicsg) {
super.paintComponent(g);
draw(g);
}
/**
* Draws the game grid, snake, apple, and score on the panel.
*
* @param g the Graphics object to draw with
*/
publicvoiddraw(Graphicsg) {
if(running) {
for (inti = 0; i < SCREEN_HEIGHT / UNIT_SIZE; i++) {
g.setColor(newColor(50, 102, 48));
g.drawLine(i * UNIT_SIZE, 0, i * UNIT_SIZE, SCREEN_HEIGHT);
g.drawLine(0, i * UNIT_SIZE, SCREEN_WIDTH, i * UNIT_SIZE);
}
g.setColor(Color.red);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
for (inti = 0; i < bodyParts; i++) {
if (i == 0) {
g.setColor(newColor(26, 94, 31));
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
} else {
g.setColor(newColor(34, 122, 41));
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
}
//Score points
g.setColor(Color.red);
g.setFont(newFont("Ink Free",Font.BOLD,40));
FontMetricsmetrics = getFontMetrics(g.getFont());
g.drawString("Score: " + applesEaten,(SCREEN_WIDTH - metrics.stringWidth("Score: " + applesEaten))/2,g.getFont().getSize());
} else {
gameOver(g);
}
//END
}
/**
* Generates a new apple at a random location on the game grid.
*/
publicvoidnewApple() {
appleX = random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE;
appleY = random.nextInt((int)(SCREEN_HEIGHT/UNIT_SIZE))*UNIT_SIZE;
}
/**
* Moves the snake in the current direction and updates its position.
*/
publicvoidmove() {
for(inti = bodyParts;i>0;i--) {
x[i] = x[i-1];
y[i] = y[i-1];
}
switch (direction) {
case'U' -> y[0] = y[0] - UNIT_SIZE;
case'D' -> y[0] = y[0] + UNIT_SIZE;
case'L' -> x[0] = x[0] - UNIT_SIZE;
case'R' -> x[0] = x[0] + UNIT_SIZE;
}
}
/**
* Checks if the snake's head has collided with an apple.
* If so, increases the snake's body size and the score, and generates a new apple.
*/
publicvoidcheckApple() {
if((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++;
applesEaten++;
newApple();
}
}
/**
* Checks if the snake has collided with itself or the borders of the game area.
* If a collision is detected, the game is stopped.
*/
publicvoidcheckCollisions() {
// Checks if head collides with body
for(inti=bodyParts;i>0;i--) {
if((x[0] == x[i]) && (y[0] == y[i])) {
running = false;
}
}
// Checks if head collides with left border
if(x[0] < 0) {
running = false;
}
// Checks if head collides with right border
if(x[0] > SCREEN_WIDTH) {
running = false;
}
// Checks if head collides with upper border
if(y[0] < 0) {
running = false;
}
// Checks if head collides with lower border
if(y[0] > SCREEN_HEIGHT) {
running = false;
}
if(!running) {
timer.stop();
}
}
/**
* Displays the "Game Over" screen with the final score.
*
* @param g the Graphics object to draw with
*/
publicvoidgameOver(Graphicsg) {
//Game Over Text
g.setColor(Color.red);
g.setFont(newFont("Ink Free",Font.BOLD,75));
FontMetricsmetrics1 = getFontMetrics(g.getFont());
g.drawString("Game Over!",(SCREEN_WIDTH - metrics1.stringWidth("Game Over"))/2,SCREEN_HEIGHT/2);
// Game Over Score
g.setColor(Color.red);
g.setFont(newFont("Ink Free",Font.BOLD,40));
FontMetricsmetrics2 = getFontMetrics(g.getFont());
g.drawString("Score: " + applesEaten,(SCREEN_WIDTH - metrics2.stringWidth("Score: " + applesEaten))/2,g.getFont().getSize());
}
/**
* Handles the game action events, updating the game state and repainting the game panel.
*
* @param e the action event
*/
publicvoidactionPerformed(ActionEvente) {
if(running) {
move();
checkApple();
checkCollisions();
}
repaint();
}
/**
* The MyKeyAdapter class handles keyboard input to control the direction of the snake.
*/
publicclassMyKeyAdapterextendsKeyAdapter {
/**
* Responds to key presses to change the direction of the snake.
*
* @param e the key event
*/
@Override
publicvoidkeyPressed(KeyEvente) {
switch (e.getKeyCode()) {
caseKeyEvent.VK_LEFT -> {
if (direction != 'R') {
direction = 'L';
}
}
caseKeyEvent.VK_RIGHT -> {
if (direction != 'L') {
direction = 'R';
}
}
caseKeyEvent.VK_UP -> {
if (direction != 'D') {
direction = 'U';
}
}
caseKeyEvent.VK_DOWN -> {
if (direction != 'U') {
direction = 'D';
}
}
}
}
}
}