0% found this document useful (0 votes)
12 views

Documento Sin Título

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Documento Sin Título

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Aquí tienes un ejemplo básico de código para un juego de la serpiente en Java:

```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;

public class SnakeGame extends JPanel implements KeyListener {

private static final int WIDTH = 500;


private static final int HEIGHT = 500;
private static final int UNIT_SIZE = 25;
private static final int GAME_UNITS = (WIDTH * HEIGHT) / UNIT_SIZE;
private final int DELAY = 100;
private final int[] x = new int[GAME_UNITS];
private final int[] y = new int[GAME_UNITS];
private int bodyParts = 6;
private int applesEaten;
private int appleX;
private int appleY;
private char direction = 'R';
private boolean running = false;
private Timer timer;

public SnakeGame() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.black);
setFocusable(true);
addKeyListener(this);
startGame();
}

public void startGame() {


newApple();
running = true;
timer = new Timer(DELAY, e -> {
if (running) {
move();
checkApple();
checkCollisions();
}
repaint();
});
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}

public void draw(Graphics g) {


if (running) {
// Draw apple
g.setColor(Color.red);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);

// 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);
}
}

public void newApple() {


appleX = new Random().nextInt((int) (WIDTH / UNIT_SIZE)) * UNIT_SIZE;
appleY = new Random().nextInt((int) (HEIGHT / UNIT_SIZE)) * UNIT_SIZE;
}

public void move() {


for (int i = bodyParts; i > 0; i--) {
x[i] = x[i - 1];
y[i] = y[i - 1];
}

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;
}
}

public void checkApple() {


if ((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++;
applesEaten++;
newApple();
}
}

public void checkCollisions() {


// Check if head collides with body
for (int i = bodyParts; i > 0; i--) {
if ((x[0] == x[i]) && (y[0] == y[i])) {
running = false;
}
}

// Check if head touches left border


if (x[0] < 0) {
running = false;
}
// Check if head touches right border
if (x[0] >= WIDTH) {
running = false;
}
// Check if head touches top border
if (y[0] < 0) {
running = false;
}
// Check if head touches bottom border
if (y[0] >= HEIGHT) {
running = false;
}

if (!running) {
timer.stop();
}
}

public void gameOver(Graphics g) {


// Score
g.setColor(Color.red);
g.setFont(new Font("Ink Free", Font.BOLD, 75));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Game Over", (WIDTH - metrics.stringWidth("Game Over")) / 2, HEIGHT /
2);
// Score
g.setColor(Color.red);
g.setFont(new Font("Ink Free", Font.BOLD, 40));
g.drawString("Score: " + applesEaten, (WIDTH - metrics.stringWidth("Score: " +
applesEaten)) / 2, g.getFont().getSize());
}

@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) {
}

public static void main(String[] args) {


JFrame frame = new JFrame("Snake Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(new SnakeGame());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
```

Este código crea un juego simple de la serpiente en Java que puedes ejecutar y jugar en
una ventana.

You might also like