Updated missing Javadoc in whole repository

* reformatted whole repository
* fixed bug enabling 180° turnaround
This commit is contained in:
delvh 2020-03-11 22:27:30 +01:00
parent 5e879e5a3d
commit 46223d60ca
11 changed files with 658 additions and 402 deletions

File diff suppressed because one or more lines are too long

View File

@ -4,18 +4,42 @@ import java.awt.Color;
import java.awt.Graphics; import java.awt.Graphics;
import java.awt.Point; import java.awt.Point;
/**
* Project: <strong>Snake</strong><br>
* File: <strong>Food.java</strong><br>
* Created: <strong>11 Mar 2020</strong><br>
*
* @author Leon Hofmeister
* @since Snake 1.0
*/
public class Food { public class Food {
private Point position; private Point position;
public Food(int x, int y) { /**
position = new Point(x,y); * Constructs a new food object.
} *
* @param x the x coordinate of the new food
* @param y the y coordinate of the new food
* @since Snake 1.0
*/
public Food(int x, int y) { position = new Point(x, y); }
/**
* Constructs a new food object.
*
* @param position the position of the food
* @since Snake 1.1
*/
public Food(Point position) { this.position = position; }
/**
* @param g the {@link Graphics} object used to draw the food
* @since Snake 1.0
*/
public void render(Graphics g) { public void render(Graphics g) {
g.setColor(Color.yellow); g.setColor(Color.yellow);
g.fillRect(position.x, position.y, 16, 16); g.fillRect(position.x, position.y, 16, 16);
} }
} }

View File

@ -6,61 +6,137 @@ import java.awt.Graphics;
import java.awt.Point; import java.awt.Point;
import java.awt.Rectangle; import java.awt.Rectangle;
import dev.lh.ui.GameWindow;
/**
* Project: <strong>Snake</strong><br>
* File: <strong>FoodFactory.java</strong><br>
* Created: <strong>11 Mar 2020</strong><br>
*
* @author Leon Hofmeister
* @since Snake 1.0
*/
public class FoodFactory { public class FoodFactory {
/**
* This enum contains all possible variations of foods. The higher the ordinal
* of an element, the less it is worth.<br>
* <br>
* Project: <strong>Snake</strong><br>
* File: <strong>FoodFactory.java</strong><br>
* Created: <strong>11 Mar 2020</strong><br>
*
* @author Leon Hofmeister
* @since Snake 1.0
*/
public static enum Food { public static enum Food {
white, yellow, orange, red, blue /**
* Use if white food is wanted.
*/
white,
/**
* Use if yellow food is wanted.
*/
yellow,
/**
* Use if orange food is wanted.
*/
orange,
/**
* Use if red food is wanted.
*/
red,
/**
* Use if blue food is wanted.
*/
blue
} }
private static FoodFactory foodFactory = new FoodFactory(); private static FoodFactory foodFactory = new FoodFactory();
private long timeOfNextFood; private long timeOfNextFood;
Point pFood = null; Point pFood = null;
private Food nextFood = Food.white; private Food nextFood = Food.white;
public int rectangleSize = 6; private int rectangleSize = 6;
private FoodFactory() {} private FoodFactory() {}
/**
* @return the (singleton) instance of FoodFactory
* @since Snake 1.0
*/
public static FoodFactory getInstance() { return foodFactory; } public static FoodFactory getInstance() { return foodFactory; }
/**
* @return a new {@link Food} object without its position
* @since Snake 1.0
*/
public Food generateFood() { public Food generateFood() {
int nextFoodIs = (int) Math.floor(Math.random() * 5); int nextFoodIs = (int) Math.floor(Math.random() * 5);
switch (nextFoodIs) { switch (nextFoodIs) {
case 0: nextFood =Food.white; break; case 0:
case 1: nextFood =Food.yellow; break; nextFood = Food.white;
case 2: nextFood =Food.orange; break; break;
case 3: nextFood =Food.red; break; case 1:
case 4: nextFood =Food.blue; break; nextFood = Food.yellow;
default: nextFood=generateFood(); break;
case 2:
nextFood = Food.orange;
break;
case 3:
nextFood = Food.red;
break;
case 4:
nextFood = Food.blue;
break;
default:
nextFood = generateFood();
} }
rectangleSize = nextFood.ordinal() + 2; rectangleSize = nextFood.ordinal() + 2;
setTimeToNextFoodMillis(); setTimeToNextFoodMillis();
return nextFood; return nextFood;
} }
public void setTimeToNextFoodMillis() { /**
timeOfNextFood=System.currentTimeMillis()+(int) Math.round(Math.random() * 15000+1000);; * Generates the amount of time that needs to pass before the next food object
} * will be constructed.
*
* @since Snake 1.0
*/
public void setTimeToNextFoodMillis() { timeOfNextFood = System.currentTimeMillis() + (int) Math.round(Math.random() * 15000 + 1000); }
public Food getNextFood() { /**
return nextFood; * @return the type of the next food
} * @since Snake 1.0
*/
public Food getNextFood() { return nextFood; }
public void setNext(Food nextFood) { /**
this.nextFood = nextFood; * @param nextFood the type the next food should have
} * @since Snake 1.0
*/
public void setNext(Food nextFood) { this.nextFood = nextFood; }
public long getTimeOfNextFood() { /**
return timeOfNextFood; * @return the time at which a new food object will be automatically created
} * @since Snake 1.0
*/
public long getTimeOfNextFood() { return timeOfNextFood; }
/**
* @param width the width of the currently used {@link GameWindow}
* @param height the height of the currently used {@link GameWindow}
* @return the position of the new {@link Food} object
* @since Snake 1.0
*/
public Point generateFoodLocation(int width, int height) { public Point generateFoodLocation(int width, int height) {
pFood = new Point((int) Math.round(Math.random() * width), (int) Math.round(Math.random() * height)); pFood = new Point((int) Math.round(Math.random() * width), (int) Math.round(Math.random() * height));
if (pFood.x < 50 || pFood.x > width - 50 || pFood.y < 50 || pFood.y > height - 50) { if (pFood.x < 50 || pFood.x > width - 50 || pFood.y < 50 || pFood.y > height - 50) {
@ -70,43 +146,87 @@ public class FoodFactory {
return pFood; return pFood;
} }
public int getRectangleSize() { /**
return rectangleSize; * @return the size of the corresponding food (length = width)
} * @since Snake 1.0
*/
public int getRectangleSize() { return rectangleSize; }
public Point getFoodLocation() { /**
return pFood; * @return the location of the currently displayed food
} * @since Snake 1.0
*/
public Point getFoodLocation() { return pFood; }
/**
* Sets the color of the given {@link Graphics} object according to the type of
* food.
*
* @param g the graphics object to paint
* @since Snake 1.0
*/
public void colorOfFood(Graphics g) { public void colorOfFood(Graphics g) {
switch (nextFood) { switch (nextFood) {
case white: g.setColor(Color.white); break; case white:
case yellow:g.setColor(Color.yellow); break; g.setColor(Color.white);
case orange:g.setColor(Color.orange); break; break;
case red: g.setColor(Color.red); break; case yellow:
case blue: g.setColor(Color.blue); break; g.setColor(Color.yellow);
break;
case orange:
g.setColor(Color.orange);
break;
case red:
g.setColor(Color.red);
break;
case blue:
g.setColor(Color.blue);
break;
}// switch }// switch
} }
/**
* @param g the {@link Graphics} object used to paint the current food object
* @since Snake 1.0
*/
public void paintFood(Graphics g) { public void paintFood(Graphics g) {
colorOfFood(g); colorOfFood(g);
g.fillRect(pFood.x, pFood.y, 5 * rectangleSize, 5 * rectangleSize); g.fillRect(pFood.x, pFood.y, 5 * rectangleSize, 5 * rectangleSize);
} }
/**
* @param snakeHead the the head of a {@link Snake} object
* @return true if the current food intersects with the snakehead
* @since Snake 1.0
*/
public boolean checkCollision(Rectangle snakeHead) { public boolean checkCollision(Rectangle snakeHead) {
int s = rectangleSize * 5; int s = rectangleSize * 5;
Rectangle food = new Rectangle(pFood, new Dimension(s, s)); Rectangle food = new Rectangle(pFood, new Dimension(s, s));
return food.intersects(snakeHead); return food.intersects(snakeHead);
} }
/**
* @return the length that will be added to the snake
* @since Snake 1.0
*/
public int getAdditionalLength() { public int getAdditionalLength() {
int snakeAdditionalLength = 0; int snakeAdditionalLength = 0;
switch (nextFood) { switch (nextFood) {
case white: snakeAdditionalLength =40;break; case white:
case yellow:snakeAdditionalLength =15;break; snakeAdditionalLength = 40;
case orange:snakeAdditionalLength =6;break; break;
case red: snakeAdditionalLength =2;break; case yellow:
case blue: snakeAdditionalLength =1;break; snakeAdditionalLength = 15;
break;
case orange:
snakeAdditionalLength = 6;
break;
case red:
snakeAdditionalLength = 2;
break;
case blue:
snakeAdditionalLength = 1;
break;
}// switch }// switch
return snakeAdditionalLength; return snakeAdditionalLength;
} }

View File

@ -3,10 +3,25 @@ package dev.lh;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/**
* The handler handles incoming events in Snake.<br>
* <br>
* Project: <strong>Snake</strong><br>
* File: <strong>Handler.java</strong><br>
* Created: <strong>11 Mar 2020</strong><br>
*
* @author Leon Hofmeister
* @since Snake 1.0
*/
public class Handler { public class Handler {
List<Updateable> targets; List<Updateable> targets;
/**
* Constructs a new {@link Handler}.
*
* @since Snake 1.0
*/
public Handler() { public Handler() {
targets = new ArrayList<>(); targets = new ArrayList<>();
targets.add(new Snake(3)); targets.add(new Snake(3));

View File

@ -2,21 +2,41 @@ package dev.lh;
import dev.lh.ui.GameWindow; import dev.lh.ui.GameWindow;
/**
* Project: <strong>Snake</strong><br>
* File: <strong>Main.java</strong><br>
* Created: <strong>11 Mar 2020</strong><br>
*
* @author Leon Hofmeister
* @since Snake 1.0
*/
public class Main { public class Main {
private static GameWindow game; private static GameWindow game;
/**
* @param args the program arguments
* @since Snake 1.0
*/
public static void main(String[] args) { public static void main(String[] args) {
// if wanted, the StartScreen can be added here // if wanted, the StartScreen can be added here
startGame(); startGame();
} }
/**
* Starts a new game of Snake.
*
* @since Snake 1.0
*/
public static void startGame() { public static void startGame() {
game = new GameWindow("Snake"); game = new GameWindow("Snake");
game.setVisible(true); game.setVisible(true);
} }
public static GameWindow getGame() { /**
return game; * @return the currently used game
} * @since Snake 1.0
*/
public static GameWindow getGame() { return game; }
} }

View File

@ -9,28 +9,71 @@ import java.util.List;
import dev.lh.ui.GameWindow; import dev.lh.ui.GameWindow;
/**
* Project: <strong>Snake</strong><br>
* File: <strong>Snake.java</strong><br>
* Created: <strong>11 Mar 2020</strong><br>
*
* @author Leon Hofmeister
* @since Snake 1.0
*/
public class Snake implements Updateable { public class Snake implements Updateable {
/**
* This enum contains all possible directions for the {@link Snake}.<br>
* <br>
* Project: <strong>Snake</strong><br>
* File: <strong>Snake.java</strong><br>
* Created: <strong>11 Mar 2020</strong><br>
*
* @author Leon Hofmeister
* @since Snake 1.0
*/
public static enum Direction { public static enum Direction {
Left, Right, Up, Down; /**
* Use if the snake should head left.
*/
Left,
/**
* Use if the snake should head right.
*/
Right,
/**
* Use if the snake should head up.
*/
Up,
/**
* Use if the snake should head down.
*/
Down;
} }
private Direction Richtung; private Direction Richtung;
private int length; private int length;
private List<Point> tiles = new ArrayList<>(); private List<Point> tiles = new ArrayList<>();
private static FoodFactory foodFactory = FoodFactory.getInstance(); private static FoodFactory foodFactory = FoodFactory.getInstance();
private final int snakeSize = 10; private final int snakeSize = 10;
/**
* Constructs a new Snake with the given length in tiles.
*
* @param length the length of the snake in tiles
* @since Snake 1.0
*/
public Snake(int length) { public Snake(int length) {
this.length = length; this.length = length;
Richtung = Direction.Left; Richtung = Direction.Left;
for(int i = 0; i<length;i++) { for (int i = 0; i < length; i++)
tiles.add(new Point(320 - 50 * i, 240)); tiles.add(new Point(320 - 50 * i, 240));
}
}// End Constructor }// End Constructor
@Override @Override
public void tick() { public void nextFrame() {
int velX = 0, velY = 0; int velX = 0, velY = 0;
switch (Richtung) { switch (Richtung) {
@ -51,7 +94,6 @@ public class Snake implements Updateable {
tiles.get(0).x += velX; tiles.get(0).x += velX;
tiles.get(0).y += velY; tiles.get(0).y += velY;
for (int i = 1; i < length; i++) { for (int i = 1; i < length; i++) {
cur = tiles.get(i); cur = tiles.get(i);
tiles.set(i, (Point) next.clone()); tiles.set(i, (Point) next.clone());
@ -65,30 +107,38 @@ public class Snake implements Updateable {
} }
}// End tick }// End tick
@Override @Override
public void render(Graphics g) { public void render(Graphics g) {
g.setColor(Color.green); g.setColor(Color.green);
for (int i = 0; i<length;i++) { for (int i = 0; i < length; i++)
g.fillRect(tiles.get(i).x, tiles.get(i).y, snakeSize, snakeSize); g.fillRect(tiles.get(i).x, tiles.get(i).y, snakeSize, snakeSize);
}
}// End render }// End render
public Direction getRichtung() { /**
return Richtung; * @return the current {@link Direction} of the snake
} * @since Snake 1.0
*/
public Direction getRichtung() { return Richtung; }
public void setRichtung(Direction richtung) { /**
Richtung = richtung; * @param richtung the new {@link Direction} of the snake
} * @since Snake 1.0
*/
public void setRichtung(Direction richtung) { Richtung = richtung; }
/**
* Adds the given length to the current snake object
*
* @param additional the number of tiles to add
* @since Snake 1.0
*/
public void addLength(int additional) { public void addLength(int additional) {
for(int i=0;i<additional;i++) { Point last = tiles.get(tiles.size() - 1);
tiles.add(null); for (int i = 0; i < additional; i++)
} tiles.add(last);
length += additional; length += additional;
} }
} }

View File

@ -2,18 +2,24 @@ package dev.lh;
import java.awt.Graphics; import java.awt.Graphics;
/**
* Project: <strong>Snake</strong><br>
* File: <strong>Spawner.java</strong><br>
* Created: <strong>11 Mar 2020</strong><br>
*
* @author Leon Hofmeister
* @since Snake 1.0
*/
public class Spawner implements Updateable { public class Spawner implements Updateable {
@Override @Override
public void tick() { public void nextFrame() {
} }
@Override @Override
public void render(Graphics g) { public void render(Graphics g) {
} }
} }

View File

@ -2,10 +2,32 @@ package dev.lh;
import java.awt.Graphics; import java.awt.Graphics;
/**
* This interface contains everything that needs to updated regularly.<br>
* <br>
* Project: <strong>Snake</strong><br>
* File: <strong>Updateable.java</strong><br>
* Created: <strong>11 Mar 2020</strong><br>
*
* @author Leon Hofmeister
* @since Snake 1.0
*/
public interface Updateable { public interface Updateable {
void tick(); /**
* Here should the actions be implemented that are supposed to happen when a new
* frame gets created.
*
* @since Snake 1.0
*/
void nextFrame();
/**
* Renders the object.
*
* @param g the {@link Graphics} object that is used to render this object
* @since Snake 1.0
*/
void render(Graphics g); void render(Graphics g);
} }

View File

@ -2,8 +2,6 @@ package dev.lh.ui;
import java.awt.BorderLayout; import java.awt.BorderLayout;
import java.awt.Font; import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import javax.swing.ImageIcon; import javax.swing.ImageIcon;
@ -16,43 +14,27 @@ import javax.swing.border.EmptyBorder;
import dev.lh.Main; import dev.lh.Main;
/**
* Project: <strong>Snake</strong><br>
* File: <strong>Endscreen.java</strong><br>
* Created: <strong>11 Mar 2020</strong><br>
*
* @author Leon Hofmeister
* @since Snake v1.1
*/
public class Endscreen extends JDialog { public class Endscreen extends JDialog {
private static final long serialVersionUID = -4457484397259161063L; private static final long serialVersionUID = -4457484397259161063L;
private final JPanel contentPanel = new JPanel(); private final JPanel contentPanel = new JPanel();
public static int currentIndex = 0; private static int score = 0;
public static boolean alreadySaved = false; private final int goodOrBadResult = 250;
public static int score = 0;
final int goodOrBadResult = 250;
// Beginn der Hauptmethode/Erstellung des JDialogs
public static void main(String[] args) {
try {
Endscreen dialog = new Endscreen(score);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
Thread.getAllStackTraces().forEach((thread, stackTraceElement) -> thread.interrupt());
System.exit(0);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/** /**
* Create the dialog. * Create the dialog.
*
* @param score1 the highscore to set
*/ */
public Endscreen(int score1) { public Endscreen(int score1) {
setScore(score1); setScore(score1);
try { try {
@ -65,6 +47,17 @@ public class Endscreen extends JDialog {
getContentPane().setLayout(new BorderLayout()); getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER); getContentPane().add(contentPanel, BorderLayout.CENTER);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
Thread.getAllStackTraces().forEach((thread, stackTraceElement) -> thread.interrupt());
System.exit(0);
}
});
} catch (Exception e) {
e.printStackTrace();
}
contentPanel.setLayout(null); contentPanel.setLayout(null);
// JScrollPane scrollPane = new JScrollPane(); // JScrollPane scrollPane = new JScrollPane();
// scrollPane.setBounds(10, 412, 349, 238); // scrollPane.setBounds(10, 412, 349, 238);
@ -81,24 +74,19 @@ public class Endscreen extends JDialog {
// scrollPane.setViewportView(table); // scrollPane.setViewportView(table);
// JLabel lblNewLabel = new JLabel("Highscores"); // JLabel lblNewLabel = new JLabel("Highscores");
// lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD | Font.ITALIC, 18)); // lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD | Font.ITALIC,
// 18));
// lblNewLabel.setBounds(65, 292, 98, 41); // lblNewLabel.setBounds(65, 292, 98, 41);
// contentPanel.add(lblNewLabel); // contentPanel.add(lblNewLabel);
JButton btnNewButton = new JButton("Play again"); JButton btnNewButton = new JButton("Play again");
btnNewButton.setMnemonic(KeyEvent.VK_ENTER); btnNewButton.setMnemonic(KeyEvent.VK_ENTER);
btnNewButton.addActionListener(new ActionListener() {// Beginn Listener new game btnNewButton.addActionListener(e -> { Main.startGame(); setVisible(false); dispose(); });
public void actionPerformed(ActionEvent e) { // BLOß NICHT RAUSWERFEN
Main.startGame();
setVisible(false);
dispose();
}
});
//BLOß NICHT RAUSWERFEN
btnNewButton.setIconTextGap(5); btnNewButton.setIconTextGap(5);
btnNewButton.setIcon(new ImageIcon( btnNewButton.setIcon(new ImageIcon(ClassLoader.getSystemResource("/com/sun/javafx/webkit/prism/resources/mediaPlayDisabled.png")));
Endscreen.class.getResource("/com/sun/javafx/webkit/prism/resources/mediaPlayDisabled.png"))); // Endscreen.class.getResource("/com/sun/javafx/webkit/prism/resources/mediaPlayDisabled.png")));
btnNewButton.setFont(new Font("Times New Roman", Font.PLAIN, 15)); btnNewButton.setFont(new Font("Times New Roman", Font.PLAIN, 15));
btnNewButton.setBounds(85, 512, 243, 100); btnNewButton.setBounds(85, 512, 243, 100);
contentPanel.add(btnNewButton); contentPanel.add(btnNewButton);
@ -124,7 +112,8 @@ public class Endscreen extends JDialog {
// JTextArea txtrBitteErstNamen = new JTextArea(); // JTextArea txtrBitteErstNamen = new JTextArea();
// txtrBitteErstNamen.setVisible(false); // txtrBitteErstNamen.setVisible(false);
// txtrBitteErstNamen.setBackground(UIManager.getColor("ScrollBar.foreground")); // txtrBitteErstNamen.setBackground(UIManager.getColor("ScrollBar.foreground"));
// txtrBitteErstNamen.setText("Bitte erst Namen \r\neingeben und\r\ndann Speichern!!!!"); // txtrBitteErstNamen.setText("Bitte erst Namen \r\neingeben und\r\ndann
// Speichern!!!!");
// txtrBitteErstNamen.setBounds(468, 412, 155, 92); // txtrBitteErstNamen.setBounds(468, 412, 155, 92);
// contentPanel.add(txtrBitteErstNamen); // contentPanel.add(txtrBitteErstNamen);
// txtrBitteErstNamen.setVisible(false); // txtrBitteErstNamen.setVisible(false);
@ -133,10 +122,12 @@ public class Endscreen extends JDialog {
// btnSaveHighscore.setMnemonic(KeyEvent.VK_ENTER); // btnSaveHighscore.setMnemonic(KeyEvent.VK_ENTER);
// btnSaveHighscore.setIconTextGap(5); // btnSaveHighscore.setIconTextGap(5);
// btnSaveHighscore.setIcon( // btnSaveHighscore.setIcon(
// new ImageIcon(Endscreen.class.getResource("/javax/swing/plaf/metal/icons/ocean/floppy.gif"))); // new
// ImageIcon(Endscreen.class.getResource("/javax/swing/plaf/metal/icons/ocean/floppy.gif")));
// btnSaveHighscore.setFont(new Font("Times New Roman", Font.PLAIN, 15)); // btnSaveHighscore.setFont(new Font("Times New Roman", Font.PLAIN, 15));
// //
// btnSaveHighscore.addActionListener(new ActionListener() {// Beginn Listener Save Highscore // btnSaveHighscore.addActionListener(new ActionListener() {// Beginn Listener
// Save Highscore
// public void actionPerformed(ActionEvent e) { // public void actionPerformed(ActionEvent e) {
// relocate(score1); // relocate(score1);
// writeFiles(); // writeFiles();
@ -162,11 +153,11 @@ public class Endscreen extends JDialog {
JLabel lblDasIstEin = new JLabel("Das ist ein hervorragender Wert!"); JLabel lblDasIstEin = new JLabel("Das ist ein hervorragender Wert!");
lblDasIstEin.setFont(new Font("Times New Roman", Font.PLAIN, 15)); lblDasIstEin.setFont(new Font("Times New Roman", Font.PLAIN, 15));
if (score1 >= goodOrBadResult) { if (score1 >= goodOrBadResult) {
chckbxNewCheckBox.setIcon(new ImageIcon(Endscreen.class.getResource("/dev/lh/snake/1211548-200.png"))); chckbxNewCheckBox.setIcon(new ImageIcon(ClassLoader.getSystemResource("/dev/lh/snake/1211548-200.png")));
chckbxNewCheckBox.setBounds(300, 200, 200, 200); chckbxNewCheckBox.setBounds(300, 200, 200, 200);
lblDasIstEin.setBounds(10, 100, 212, 50); lblDasIstEin.setBounds(10, 100, 212, 50);
} else { } else {
chckbxNewCheckBox.setIcon(new ImageIcon(Endscreen.class.getResource("/dev/lh/snake/Try_Again.jpg"))); chckbxNewCheckBox.setIcon(new ImageIcon(ClassLoader.getSystemResource("/dev/lh/snake/Try_Again.jpg")));
chckbxNewCheckBox.setBounds(300, 200, 250, 210); chckbxNewCheckBox.setBounds(300, 200, 250, 210);
lblDasIstEin.setText("Das kannst du aber noch verbessern!"); lblDasIstEin.setText("Das kannst du aber noch verbessern!");
lblDasIstEin.setBounds(10, 100, 240, 50); lblDasIstEin.setBounds(10, 100, 240, 50);
@ -174,48 +165,42 @@ public class Endscreen extends JDialog {
} }
contentPanel.add(chckbxNewCheckBox); contentPanel.add(chckbxNewCheckBox);
contentPanel.add(lblDasIstEin); contentPanel.add(lblDasIstEin);
} catch (Exception e) { setVisible(true);
e.printStackTrace();
} }
} /**
* @return the highscore of the current game
* @since Snake 1.0
*/
public static int getScore() { return score; }
public static int getScore() { /**
return score; * @param score the new highscore
} * @since Snake 1.0
*/
public static void setScore(int score) { public static void setScore(int score) { Endscreen.score = score; }
Endscreen.score = score;
}
/* /*
* public static void readInHighscoresPoints() { try { // FileReader reads text * public static void readInHighscoresPoints() { try { // FileReader reads text
* files in the default encoding. FileReader fileReader = new * files in the default encoding. FileReader fileReader = new
* FileReader(fileNamePoints); * FileReader(fileNamePoints);
*
* // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = * // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader =
* new BufferedReader(fileReader); * new BufferedReader(fileReader);
*
* currentIndex = Integer.parseInt(bufferedReader.readLine()); for (int i = 0; i * currentIndex = Integer.parseInt(bufferedReader.readLine()); for (int i = 0; i
* < currentIndex; i++) { highscorePoints[i]= * < currentIndex; i++) { highscorePoints[i]=
* Integer.parseInt(bufferedReader.readLine()); } // Always close files. * Integer.parseInt(bufferedReader.readLine()); } // Always close files.
* bufferedReader.close(); fileReader.close(); } catch (FileNotFoundException * bufferedReader.close(); fileReader.close(); } catch (FileNotFoundException
* ex) { System.out.println("Error 404:File '" + fileNamePoints + * ex) { System.out.println("Error 404:File '" + fileNamePoints +
* "' not found"); * "' not found");
*
* } catch (IOException ex) { System.out.println("Error reading file '" + * } catch (IOException ex) { System.out.println("Error reading file '" +
* fileNamePoints + "'"); ex.printStackTrace(); } } private void * fileNamePoints + "'"); ex.printStackTrace(); } } private void
* readInHighscoresPlayers(){ try { // FileReader reads text files in the * readInHighscoresPlayers(){ try { // FileReader reads text files in the
* default encoding. FileReader fileReader = new FileReader(fileNamePlayers); * default encoding. FileReader fileReader = new FileReader(fileNamePlayers);
*
* // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = * // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader =
* new BufferedReader(fileReader); * new BufferedReader(fileReader);
*
* for (int i = 0; i < currentIndex; i++) { highscorePlayers[i]= * for (int i = 0; i < currentIndex; i++) { highscorePlayers[i]=
* bufferedReader.readLine(); } // Always close files. bufferedReader.close(); * bufferedReader.readLine(); } // Always close files. bufferedReader.close();
* fileReader.close(); } catch (FileNotFoundException ex) { * fileReader.close(); } catch (FileNotFoundException ex) {
* System.out.println("Error 404:File '" + fileNamePlayers + "' not found"); * System.out.println("Error 404:File '" + fileNamePlayers + "' not found");
*
*
* } catch (IOException ex) { System.out.println("Error reading file '" + * } catch (IOException ex) { System.out.println("Error reading file '" +
* fileNamePlayers + "'"); ex.printStackTrace(); } } /* private void * fileNamePlayers + "'"); ex.printStackTrace(); } } /* private void
* writeFiles() { File dateiPoints = new File("." + File.separator + * writeFiles() { File dateiPoints = new File("." + File.separator +
@ -226,7 +211,6 @@ public class Endscreen extends JDialog {
* catch (Exception e1) { e1.printStackTrace(); } finally { try { * catch (Exception e1) { e1.printStackTrace(); } finally { try {
* bwpoints.close(); fwpoints.close(); alreadySaved = true; } catch (IOException * bwpoints.close(); fwpoints.close(); alreadySaved = true; } catch (IOException
* e2) { e2.printStackTrace(); } } * e2) { e2.printStackTrace(); } }
*
* File dateiPlayers = new File("." + File.separator + fileNamePlayers); * File dateiPlayers = new File("." + File.separator + fileNamePlayers);
* FileWriter fwplayers = null; BufferedWriter bwplayers = null; try { fwplayers * FileWriter fwplayers = null; BufferedWriter bwplayers = null; try { fwplayers
* = new FileWriter(dateiPlayers); bwplayers = new BufferedWriter(fwplayers); * = new FileWriter(dateiPlayers); bwplayers = new BufferedWriter(fwplayers);
@ -234,20 +218,14 @@ public class Endscreen extends JDialog {
* bwplayers.write(highscorePlayers[i]); } } catch (Exception e1) { * bwplayers.write(highscorePlayers[i]); } } catch (Exception e1) {
* e1.printStackTrace(); } finally { try { bwplayers.close(); fwplayers.close(); * e1.printStackTrace(); } finally { try { bwplayers.close(); fwplayers.close();
* alreadySaved = true; } catch (IOException e2) { e2.printStackTrace(); } } * alreadySaved = true; } catch (IOException e2) { e2.printStackTrace(); } }
*
*
* } * }
*
*
* /** Launch the application. * /** Launch the application.
*/ */
/* /*
* public void relocate(int newScore) { * public void relocate(int newScore) {
*
* String newPlayer = new String(tfName.getText()); if (newPlayer.equals("")) { * String newPlayer = new String(tfName.getText()); if (newPlayer.equals("")) {
* txtrBitteErstNamen.setVisible(true); return; } else { sortFiles(newScore, * txtrBitteErstNamen.setVisible(true); return; } else { sortFiles(newScore,
* newPlayer); } } * newPlayer); } }
*
* private void sortFiles(int newScore, String newPlayer) { if * private void sortFiles(int newScore, String newPlayer) { if
* (highscorePoints.length==highscorePlayers.length&& * (highscorePoints.length==highscorePlayers.length&&
* highscorePoints.length<=30) { for(int i=0;i<highscorePoints.length;i++) { * highscorePoints.length<=30) { for(int i=0;i<highscorePoints.length;i++) {
@ -276,7 +254,6 @@ public class Endscreen extends JDialog {
* temp[i]=toCompare; for(int k=i+1;k<temp.length;k++) { int tmp2=temp[k]; * temp[i]=toCompare; for(int k=i+1;k<temp.length;k++) { int tmp2=temp[k];
* temp[k]=tmp; tmp=tmp2; } arrange(temp); return; } else { temp[30]=toCompare; * temp[k]=tmp; tmp=tmp2; } arrange(temp); return; } else { temp[30]=toCompare;
* arrange(temp); } * arrange(temp); }
*
* } } } * } } }
*/ */
} }

View File

@ -16,17 +16,30 @@ import dev.lh.FoodFactory;
import dev.lh.Snake; import dev.lh.Snake;
import dev.lh.Snake.Direction; import dev.lh.Snake.Direction;
/**
* Project: <strong>Snake</strong><br>
* File: <strong>GameWindow.java</strong><br>
* Created: <strong>11 Mar 2020</strong><br>
*
* @author Leon Hofmeister
* @since Snake 1.0
*/
public class GameWindow extends JFrame { public class GameWindow extends JFrame {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private Snake s = new Snake(7); private Snake s = new Snake(7);
private FoodFactory foodFactory = FoodFactory.getInstance(); private FoodFactory foodFactory = FoodFactory.getInstance();
/**
* @param title the title of the frame
* @since Snake 1.0
*/
public GameWindow(String title) { public GameWindow(String title) {
super(title); super(title);
newFood(); newFood();
Dimension size = Toolkit.getDefaultToolkit().getScreenSize(); Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(new Rectangle(size)); setBounds(new Rectangle(size));
setLocation(0, 0);
setLocationRelativeTo(null); setLocationRelativeTo(null);
setMinimumSize(size); setMinimumSize(size);
setPreferredSize(size); setPreferredSize(size);
@ -35,7 +48,6 @@ public class GameWindow extends JFrame {
setResizable(false); setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE); setDefaultCloseOperation(EXIT_ON_CLOSE);
add(new JPanel() { add(new JPanel() {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ -58,40 +70,46 @@ public class GameWindow extends JFrame {
switch (e.getKeyCode()) { switch (e.getKeyCode()) {
case KeyEvent.VK_W: case KeyEvent.VK_W:
case KeyEvent.VK_UP: case KeyEvent.VK_UP:
s.setRichtung(Direction.Up); if (!s.getRichtung().equals(Direction.Down)) s.setRichtung(Direction.Up);
break; break;
case KeyEvent.VK_A: case KeyEvent.VK_A:
case KeyEvent.VK_LEFT: case KeyEvent.VK_LEFT:
s.setRichtung(Direction.Left); if (!s.getRichtung().equals(Direction.Right)) s.setRichtung(Direction.Left);
break; break;
case KeyEvent.VK_S: case KeyEvent.VK_S:
case KeyEvent.VK_DOWN: case KeyEvent.VK_DOWN:
s.setRichtung(Direction.Down); if (!s.getRichtung().equals(Direction.Up)) s.setRichtung(Direction.Down);
break; break;
case KeyEvent.VK_D: case KeyEvent.VK_D:
case KeyEvent.VK_RIGHT: case KeyEvent.VK_RIGHT:
s.setRichtung(Direction.Right); if (!s.getRichtung().equals(Direction.Left)) s.setRichtung(Direction.Right);
break; break;
}// switch }
}// keypressed }
});// keylistener
Timer timer = new Timer(50, (evt) -> {
s.tick();
if(System.currentTimeMillis()>=foodFactory.getTimeOfNextFood()) newFood();
repaint();
}); });
Timer timer = new Timer(50,
(evt) -> { s.nextFrame(); if (System.currentTimeMillis() >= foodFactory.getTimeOfNextFood()) newFood(); repaint(); });
timer.start(); timer.start();
setVisible(true); setVisible(true);
} }
/**
* Generates new food
*
* @since Snake 1.1
*/
public void newFood() { public void newFood() {
foodFactory.generateFood(); foodFactory.generateFood();
foodFactory.generateFoodLocation(super.getWidth(), super.getHeight()); foodFactory.generateFoodLocation(super.getWidth(), super.getHeight());
repaint();
} }
public void close() { /**
dispose(); * Disposes this frame
} *
* @since Snake 1.1
*/
public void close() { dispose(); }
} }

View File

@ -2,11 +2,7 @@ package dev.lh.ui;
import java.awt.EventQueue; import java.awt.EventQueue;
import java.awt.Font; import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon; import javax.swing.ImageIcon;
import javax.swing.JButton; import javax.swing.JButton;
@ -16,30 +12,38 @@ import javax.swing.border.EmptyBorder;
import dev.lh.Main; import dev.lh.Main;
/**
* Project: <strong>Snake</strong><br>
* File: <strong>StartScreen.java</strong><br>
* Created: <strong>11 Mar 2020</strong><br>
*
* @author Leon Hofmeister
* @since Snake 1.0
*/
public class StartScreen extends JFrame { public class StartScreen extends JFrame {
private static final long serialVersionUID = 6055940532003735543L; private static final long serialVersionUID = 6055940532003735543L;
private JPanel contentPane; private JPanel contentPane;
public static int currentIndex = 0;
public static List<String[]> combination = new ArrayList<>();
/** /**
* Launch the application. * closes the application.
*/ */
public static void close() { public static void close() { System.exit(0); }
System.exit(0);
}
/**
* Launches Snake.
*
* @param args the program arguments
* @since Snake 1.0
*/
public static void main(String[] args) { public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() { EventQueue.invokeLater(() -> {
public void run() {
try { try {
StartScreen frame = new StartScreen(); StartScreen frame = new StartScreen();
frame.setVisible(true); frame.setVisible(true);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}); });
} }
@ -87,19 +91,16 @@ public class StartScreen extends JFrame {
JButton buPlay = new JButton("Start Game"); JButton buPlay = new JButton("Start Game");
buPlay.setBounds(158, 197, 190, 131); buPlay.setBounds(158, 197, 190, 131);
buPlay.setIcon(new ImageIcon( buPlay.setIcon(new ImageIcon(StartScreen.class.getResource("/com/sun/javafx/webkit/prism/resources/mediaPlayDisabled.png")));
StartScreen.class.getResource("/com/sun/javafx/webkit/prism/resources/mediaPlayDisabled.png")));
buPlay.setMnemonic(KeyEvent.VK_ENTER); buPlay.setMnemonic(KeyEvent.VK_ENTER);
buPlay.setFont(new Font("Times New Roman", Font.PLAIN, 16)); buPlay.setFont(new Font("Times New Roman", Font.PLAIN, 16));
buPlay.addActionListener(new ActionListener() { buPlay.addActionListener(a -> {
public void actionPerformed(ActionEvent a) {
Main.startGame(); Main.startGame();
setVisible(false); setVisible(false);
dispose(); dispose();
System.gc(); System.gc();
}
}); });
contentPane.setLayout(null); contentPane.setLayout(null);