This document contains code for a Snake game applet written in Java. The applet tracks the position and movement of the snake and apples on a board. It handles snake movement, collision detection, and scoring when apples are eaten.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
38 views4 pages
Snake Game
This document contains code for a Snake game applet written in Java. The applet tracks the position and movement of the snake and apples on a board. It handles snake movement, collision detection, and scoring when apples are eaten.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4
import java.applet.
*; import java.awt.*; import java.awt.event.*;
public class SnakeGame extends Applet implements KeyListener, Runnable {
private static final long serialVersionUID = 1L; private final int BOARD_WIDTH = 400; private final int BOARD_HEIGHT = 400; private final int UNIT_SIZE = 20; private final int DELAY = 75; private final Color APPLE_COLOR = Color.RED; private final Color SNAKE_COLOR = Color.GREEN; private final Color BODY_COLOR = new Color(45, 180, 0);
private int[] x = new int[100];
private int[] y = new int[100]; private int bodyParts = 6; private int applesEaten; private int appleX; private int appleY; private char direction = 'R'; private boolean running = false; private Thread thread;
// 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] >= BOARD_WIDTH) { running = false; } // Check if head touches top border if (y[0] < 0) { running = false; } // Check if head touches bottom border if (y[0] >= BOARD_HEIGHT) { running = false; } }
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; } }
public void keyReleased(KeyEvent e) {}
public static void main(String[] args) {
// Create an instance of SnakeGame SnakeGame snakeGame = new SnakeGame(); // Create a frame to hold the applet Frame frame = new Frame("Snake Game");