Untitled
unknown
plain_text
3 years ago
2.4 kB
8
Indexable
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class SnakeGame extends JPanel implements ActionListener, KeyListener {
private static final int WIDTH = 500;
private static final int HEIGHT = 500;
private static final int DOT_SIZE = 10;
private static final int ALL_DOTS = 900;
private static final int RAND_POS = 29;
private static final int DELAY = 140;
private Timer timer;
private boolean inGame = true;
private boolean leftDirection = false;
private boolean rightDirection = true;
private boolean upDirection = false;
private boolean downDirection = false;
private int dots;
private int apple_x;
private int apple_y;
private int[] x = new int[ALL_DOTS];
private int[] y = new int[ALL_DOTS];
public SnakeGame() {
addKeyListener(this);
setBackground(Color.black);
setFocusable(true);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
initGame();
}
public void initGame() {
dots = 3;
for (int i = 0; i < dots; i++) {
x[i] = 50 - i * 10;
y[i] = 50;
}
locateApple();
timer = new Timer(DELAY, this);
timer.start();
}
public void locateApple() {
Random random = new Random();
apple_x = random.nextInt(RAND_POS) * DOT_SIZE;
apple_y = random.nextInt(RAND_POS) * DOT_SIZE;
}
public void checkApple() {
if ((x[0] == apple_x) && (y[0] == apple_y)) {
dots++;
locateApple();
}
}
public void checkCollision() {
for (int i = dots; i > 0; i--) {
if ((i > 4) && (x[0] == x[i]) && (y[0] == y[i])) {
inGame = false;
}
}
if (y[0] >= HEIGHT) {
inGame = false;
}
if (y[0] < 0) {
inGame = false;
}
if (x[0] >= WIDTH) {
inGame = false;
}
if (x[0] < 0) {
inGame = false;
}
}
public void move() {Editor is loading...