Snake/Java: Difference between revisions

no edit summary
No edit summary
Line 5:
/* Sourced By Samuel Dennis */
/* */
/* LastCreated EditiedOn (09/01/2019) */
/* Last Editied (11/18/2019) */
/***************************************************/
import java.awt.*;
Line 13 ⟶ 14:
import java.util.List;
import javax.swing.*;
public class TestCodeSnake extends JPanel implements Runnable {
enum Dir {
up(0, -1), right(1, 0), down(0, 1), left(-1, 0);
Dir(int x, int y) {
this.x = x; this.y = y;
}
final int x, y;
}
 
static final Random rand = new Random();
public class Snake extends JPanel implements Runnable {
static final int WALL = -1;
enum Dir {
static final int MAX_ENERGY = 1500;
up(0, -1), right(1, 0), down(0, 1), left(-1, 0);
 
volatile boolean gameOver = true;
Dir(int x, int y) {
this.x = x; this.y = y;
}
 
Thread gameThread;
final int x, y;
int score, hiScore;
}
int nRows = 44;
int nCols = 64;
Dir dir;
int energy;
 
int[][] grid;
static final Random rand = new Random();
List<Point> snake, treats;
static final int WALL = -1;
Font smallFont;
static final int MAX_ENERGY = 1500;
 
public TestCodeSnake() {
volatile boolean gameOver = true;
setPreferredSize(new Dimension(640, 440));
 
setBackground(Color.WHITE);
Thread gameThread;
setFont(new Font("TimesNewRoman", Font.BOLD, 48));
int score, hiScore;
int nRows = 44setFocusable(true);
int nCols = 64;
smallFont = getFont().deriveFont(Font.BOLD, 18);
Dir dir;
int energy initGrid();
 
addMouseListener(
int[][] grid;
new MouseAdapter() {
List<Point> snake, treats;
Font smallFont;
 
public Snake() {
setPreferredSize(new Dimension(640, 440));
setBackground(Color.white);
setFont(new Font("SansSerif", Font.BOLD, 48));
setFocusable(true);
 
smallFont = getFont().deriveFont(Font.BOLD, 18);
initGrid();
 
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (gameOver) {
startNewGame();
repaint();
}
}
});
 
addKeyListener(new KeyAdapter() {
new KeyAdapter() {
 
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
if (dir != Dir.down)
dir = Dir.up;
break;
case KeyEvent.VK_LEFT:
if (dir != Dir.right)
dir = Dir.left;
break;
case KeyEvent.VK_RIGHT:
if (dir != Dir.left)
dir = Dir.right;
break;
case KeyEvent.VK_DOWN:
if (dir != Dir.up)
dir = Dir.down;
break;
}
repaint();
}
});
}
 
void startNewGame() {
switch (e.getKeyCode()) {
gameOver = false;
stop();
initGrid();
treats = new LinkedList<>();
dir = Dir.left;
energy = MAX_ENERGY;
if (score > hiScore)
hiScore = score;
score = 0;
snake = new ArrayList<>();
for (int x = 0; x < 7; x++)
snake.add(new Point(nCols / 2 + x, nRows / 2));
do
addTreat();
while(treats.isEmpty());
(gameThread = new Thread(this)).start();
}
 
void stop() {
case KeyEvent.VK_UP:
if (dirgameThread != Dir.downnull) {
Thread dirtmp = Dir.upgameThread;
gameThread = breaknull;
tmp.interrupt();
}
}
 
void initGrid() {
case KeyEvent.VK_LEFT:
grid = new int[nRows][nCols];
if (dir != Dir.right)
for (int r = 0; r < nRows; r++) dir = Dir.left;{
for (int c = 0; c < nCols; c++) break;{
if (c == 0 || c == nCols - 1 || r == 0 || r == nRows - 1)
grid[r][c] = WALL;
}
}
}
 
@Override
case KeyEvent.VK_RIGHT:
public void run() {
if (dir != Dir.left)
dir = Dir.right;
while (Thread.currentThread() == gameThread) {
break;
 
try case KeyEvent.VK_DOWN:{
Thread.sleep(Math.max(75 - score, if (dir != Dir.up25));
} catch (InterruptedException e) {
dir = Dir.down;
breakreturn;
}
repaint();
if (energyUsed() || hitsWall() || hitsSnake()) {
gameOver();
} else {
if (eatsTreat()) {
score++;
energy = MAX_ENERGY;
growSnake();
}
} moveSnake();
}
 
void startNewGame() {
gameOver = false;
 
stop();
initGrid();
treats = new LinkedList<>();
 
dir = Dir.left;
energy = MAX_ENERGY;
 
if (score > hiScore)
hiScore = score;
score = 0;
 
snake = new ArrayList<>();
for (int x = 0; x < 7; x++)
snake.add(new Point(nCols / 2 + x, nRows / 2));
 
do
addTreat();
while(treats.isEmpty()); }
repaint();
}
}
 
boolean energyUsed() {
(gameThread = new Thread(this)).start();
} energy -= 10;
return energy <= 0;
}
 
boolean void stophitsWall() {
Point head if= snake.get(gameThread != null0) {;
int nextCol = head.x + Thread tmp = gameThreaddir.x;
int nextRow = head.y + gameThread = nulldir.y;
return grid[nextRow][nextCol] == WALL;
tmp.interrupt();
}
}
 
boolean void initGridhitsSnake() {
Point gridhead = new int[nRows][nCols]snake.get(0);
for (int rnextCol = 0;head.x r+ < nRowsdir.x; r++) {
for (int cnextRow = 0;head.y c+ < nColsdir.y; c++) {
for (Point p : snake)
if (c == 0 || c == nCols - 1 || r == 0 || r == nRows - 1)
if (p.x == nextCol && p.y grid[r][c] == WALL;nextRow)
}return true;
return }false;
}
 
boolean eatsTreat() {
@Override
Point head = snake.get(0);
public void run() {
int nextCol = head.x + dir.x;
int nextRow = head.y + dir.y;
for (Point p : treats)
if (p.x == nextCol && p.y == nextRow) {
return treats.remove(p);
}
return false;
}
 
void gameOver() {
while (Thread.currentThread() == gameThread) {
gameOver = true;
stop();
}
 
void trymoveSnake() {
for (int i = snake.size() - 1; i > 0; Thread.sleep(Math.max(75 i-- score, 25)); {
Point p1 = }snake.get(i catch- (InterruptedException e1) {;
Point p2 = returnsnake.get(i);
p2.x = }p1.x;
p2.y = p1.y;
 
}
if (energyUsed() || hitsWall() || hitsSnake()) {
Point head = gameOversnake.get(0);
head.x += } else {dir.x;
head.y += dir.y;
if (eatsTreat()) {
}
score++;
energy = MAX_ENERGY;
growSnake();
}
moveSnake();
addTreat();
}
repaint();
}
}
 
boolean energyUsed() {
energy -= 10;
return energy <= 0;
}
 
boolean hitsWall() {
Point head = snake.get(0);
int nextCol = head.x + dir.x;
int nextRow = head.y + dir.y;
return grid[nextRow][nextCol] == WALL;
}
 
boolean hitsSnake() {
Point head = snake.get(0);
int nextCol = head.x + dir.x;
int nextRow = head.y + dir.y;
for (Point p : snake)
if (p.x == nextCol && p.y == nextRow)
return true;
return false;
}
 
boolean eatsTreat() {
Point head = snake.get(0);
int nextCol = head.x + dir.x;
int nextRow = head.y + dir.y;
for (Point p : treats)
if (p.x == nextCol && p.y == nextRow) {
return treats.remove(p);
}
return false;
}
 
void gameOver() {
gameOver = true;
stop();
}
 
void moveSnake() {
for (int i = snake.size() - 1; i > 0; i--) {
Point p1 = snake.get(i - 1);
Point p2 = snake.get(i);
p2.x = p1.x;
p2.y = p1.y;
}
Point head = snake.get(0);
head.x += dir.x;
head.y += dir.y;
}
 
void growSnake() {
Point tail = snake.get(snake.size() - 1);
int x = tail.x + dir.x;
int y = tail.y + dir.y;
snake.add(new Point(x, y));
}
 
void addTreat() {
if (treats.size() < 3) {
 
if (rand.nextInt(10) == 0) { // 1 in 10
 
if (rand.nextInt(4) != 0) { // 3 in 4
int x, y;
while (true) {
 
x = rand.nextInt(nCols);
y = rand.nextInt(nRows);
if (grid[y][x] != 0)
continue;
 
Point p = new Point(x, y);
if (snake.contains(p) || treats.contains(p))
continue;
 
treats.add(p);
break;
}
} else if (treats.size() > 1)
treats.remove(0);
}
}
}
 
void drawGrid(Graphics2D g) {
g.setColor(Color.lightGray);
for (int r = 0; r < nRows; r++) {
for (int c = 0; c < nCols; c++) {
if (grid[r][c] == WALL)
g.fillRect(c * 10, r * 10, 10, 10);
}
}
}
 
void drawSnakegrowSnake(Graphics2D g) {
Point tail g= snake.setColorget(Colorsnake.bluesize() - 1);
int x for= (Pointtail.x p+ : snake)dir.x;
int y = gtail.fillRect(p.xy *+ 10, pdir.y * 10, 10, 10);
snake.add(new Point(x, y));
}
 
void addTreat() {
g.setColor(energy < 500 ? Color.red : Color.orange);
if Point head = snake(treats.getsize(0); < 3) {
g.fillRect(head.x * 10, head.y * 10, 10, 10);
if (rand.nextInt(10) == 0) { // 1 in 10
}
if (rand.nextInt(4) != 0) { // 3 in 4
int x, y;
while (true) {
x = rand.nextInt(nCols);
y = rand.nextInt(nRows);
if (grid[y][x] != 0)
continue;
Point p = new Point(x, y);
if (snake.contains(p) || treats.contains(p))
continue;
treats.add(p);
break;
}
} else if (treats.size() > 1)
treats.remove(0);
}
}
}
 
void drawTreatsdrawGrid(Graphics2D g) {
g.setColor(Color.greenblack);
for (Pointint pr := treats0; r < nRows; r++) {
for g.fillRect(p.xint *c 10,= p.y0; *c 10,< 10,nCols; 10c++); {
if (grid[r][c] == WALL)
}
g.fillRect(c * 10, r * 10, 10, 10);
}
}
}
 
void drawStartScreendrawSnake(Graphics2D g) {
g.setColor(Color.bluered);
for g.setFont(getFont()Point p : snake);
g.drawStringfillRect("Snake"p.x * 10, p.y * 10, 24010, 19010);
g.setColor(Color.orange);
g.setColor(energy < 500 ? Color.red : Color.orange);
g.setFont(smallFont);
Point head = snake.get(0);
g.drawString("(click to start)", 250, 240);
g.fillRect(head.x * 10, head.y * 10, 10, 10);
}
}
 
void drawScoredrawTreats(Graphics2D g) {
int h = getHeightg.setColor(Color.green);
for g.setFont(smallFontPoint p : treats);
g.setColorfillRect(getForeground()p.x * 10, p.y * 10, 10, 10);
}
String s = format("hiscore %d score %d", hiScore, score);
g.drawString(s, 30, h - 30);
g.drawString(format("energy %d", energy), getWidth() - 150, h - 30);
}
 
void drawStartScreen(Graphics2D g) {
@Override
g.setColor(Color.red);
public void paintComponent(Graphics gg) {
superg.paintComponentsetFont(gggetFont());
g.drawString("SNAKE", 240, 190);
Graphics2D g = (Graphics2D) gg;
g.setColor(Color.orange);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
g.setFont(smallFont);
RenderingHints.VALUE_ANTIALIAS_ON);
g.drawString("(Click To START)", 250, 240);
}
 
void drawScore(Graphics2D g) {
drawGrid(g);
int h = getHeight();
g.setFont(smallFont);
g.setColor(getForeground());
String s = format("Hi-Score: %d Score: %d", hiScore, score);
g.drawString(s, 30, h - 30);
g.drawString(format("Energy: %d", energy), getWidth() - 150, h - 30);
}
 
@Override
if (gameOver) {
public void paintComponent(Graphics gg) {
drawStartScreen(g);
super.paintComponent(gg);
} else {
Graphics2D g = drawSnake(gGraphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
drawTreats(g);
drawScore(g RenderingHints.VALUE_ANTIALIAS_ON);
}
} drawGrid(g);
if (gameOver) {
drawStartScreen(g);
} else {
drawSnake(g);
drawTreats(g);
drawScore(g);
}
}
 
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
() -> JFrame f = new JFrame();{
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE mainFrame = new JFrame();
fmainFrame.setTitlesetDefaultCloseOperation("Snake"JFrame.EXIT_ON_CLOSE);
fmainFrame.setResizablesetTitle(false"SNAKE");
fmainFrame.addsetResizable(new Snake(), BorderLayout.CENTERtrue);
fmainFrame.packadd(new TestCodeSnake(), BorderLayout.CENTER);
fmainFrame.setLocationRelativeTopack(null);
fmainFrame.setVisiblesetLocationRelativeTo(truenull);
} mainFrame.setVisible(true);
});
}
}</lang>