Documento Sin Título
Documento Sin Título
Documento Sin Título
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
public SnakeGame() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.black);
setFocusable(true);
addKeyListener(this);
startGame();
}
// Draw snake
for (int i = 0; i < bodyParts; i++) {
if (i == 0) {
g.setColor(Color.green);
} else {
g.setColor(new Color(45, 180, 0));
}
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
// Draw score
g.setColor(Color.red);
g.setFont(new Font("Ink Free", Font.BOLD, 40));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Score: " + applesEaten, (WIDTH - metrics.stringWidth("Score: " +
applesEaten)) / 2, g.getFont().getSize());
} else {
gameOver(g);
}
}
switch (direction) {
case 'U' -> y[0] -= UNIT_SIZE;
case 'D' -> y[0] += UNIT_SIZE;
case 'L' -> x[0] -= UNIT_SIZE;
case 'R' -> x[0] += UNIT_SIZE;
}
}
if (!running) {
timer.stop();
}
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if (direction != 'R') {
direction = 'L';
}
break;
case KeyEvent.VK_RIGHT:
if (direction != 'L') {
direction = 'R';
}
break;
case KeyEvent.VK_UP:
if (direction != 'D') {
direction = 'U';
}
break;
case KeyEvent.VK_DOWN:
if (direction != 'U') {
direction = 'D';
}
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
Este código crea un juego simple de la serpiente en Java que puedes ejecutar y jugar en
una ventana.