feat: day 1 progress

This commit is contained in:
Martin Prokoph
2025-06-27 19:58:59 +02:00
commit 9e45ea3f37
29 changed files with 988 additions and 0 deletions

View File

@@ -0,0 +1,23 @@
package eu.midnightdust.yaytris;
import eu.midnightdust.yaytris.util.NightJson;
import java.util.HashMap;
import java.util.Map;
public class Settings {
private static final NightJson json = new NightJson(Settings.class, "tetris_settings.json5");
public static int musicVolume = 100;
public static int soundVolume = 100;
public static float guiScale = 3.f;
//public static Map<String, Integer> highScores = new HashMap<>();
public static void load() {
json.readJson();
}
public static void write() {
json.writeJson();
}
}

View File

@@ -0,0 +1,21 @@
package eu.midnightdust.yaytris;
import eu.midnightdust.yaytris.game.Space;
import eu.midnightdust.yaytris.ui.TetrisUI;
import javax.swing.*;
public class Tetris {
public static Space space;
static TetrisUI ui;
public static void main(String[] args) {
try {
System.setProperty("java.awt.headless", "false");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception | Error e) { System.out.printf("%s: %s\n", "Error setting system look and feel", e); }
Settings.load();
space = new Space();
ui = new TetrisUI();
}
}

View File

@@ -0,0 +1,47 @@
package eu.midnightdust.yaytris.game;
import java.awt.Color;
import java.util.*;
public class Space {
private final Color[][] gameMap; // Bereits abgesetzte Tetrominos werden nur noch als einzelne Farben ('Blobs') auf der Karte abgespeichert
public Space() {
gameMap = new Color[7][12];
for (int x = 0; x < gameMap.length; x++) {
for (int y = 0; y < gameMap[x].length; y++) {
if (Math.random() < 0.5f) {
gameMap[x][y] = Color.getHSBColor((float) Math.random(), 1.f, 1.f);
}
}
}
}
public Color[][] getGameMap() {
return gameMap;
}
public int onLinesChanged(Tetromino tetromino, int... lines) {
int combo = 0;
Set<Integer> completedLines = new TreeSet<>();
for (int line : lines) {
Color[] newBlobs = tetromino.getLine(line);
for (int i = 0; i < newBlobs.length; i++) {
if (newBlobs[i] == null) continue;
gameMap[line][i] = newBlobs[i];
}
if (Arrays.stream(gameMap[line]).noneMatch(Objects::isNull)) { // Line completed
combo += 1;
completedLines.add(line);
combo *= completedLines.size();
}
}
for (int completedIndex = 0; completedIndex < completedLines.size(); completedIndex++) { // Remove completed lines
int line = completedLines.toArray(new Integer[0])[completedIndex];
for (int i = line+completedIndex; i >= 0; i--) {
gameMap[i] = gameMap[i-1];
}
}
return combo;
}
}

View File

@@ -0,0 +1,40 @@
package eu.midnightdust.yaytris.game;
import eu.midnightdust.yaytris.util.Vec2i;
import java.awt.*;
public class Tetromino {
private final TetrominoShape shape;
private int[][] collision;
private Vec2i centerPos;
public Tetromino(TetrominoShape shape) {
this.shape = shape;
this.collision = shape.boundary;
this.centerPos = Vec2i.of(0, 0);
}
public void fall(int length) {
centerPos = centerPos.offset(Vec2i.of(0, length));
}
public void rotate() {
int[][] newCollision = new int[collision[0].length][collision.length];
for (int i = 0; i < collision.length; i++) {
for (int j = 0; j < collision[i].length; j++) {
newCollision[j][i] = collision[i][j];
}
}
this.collision = newCollision;
}
public Color[] getLine(int line) {
Color[] l = new Color[7];
for (int i = 0; i < l.length; i++) {
if (collision.length < line-centerPos.getX() && collision[line-centerPos.getX()][i] != 0)
l[i] = shape.color;
}
return l;
}
}

View File

@@ -0,0 +1,48 @@
package eu.midnightdust.yaytris.game;
import java.awt.Color;
public enum TetrominoShape {
SQUARE(new int[][]{
{1, 1},
{1, 2}
}, Color.YELLOW),
LINE(new int[][]{
{1},
{2},
{1},
{1}
}, Color.BLUE),
T(new int[][]{
{0, 1, 0},
{1, 2, 1}
}, Color.RED),
L_LEFT(new int[][]{
{0, 1},
{0, 2},
{1, 1}
}, Color.MAGENTA),
L_RIGHT(new int[][]{
{1, 0},
{2, 0},
{1, 1}
}, Color.GREEN),
ZAP_LEFT(new int[][]{
{0, 1},
{1, 2},
{1, 0}
}, Color.CYAN),
ZAP_RIGHT(new int[][]{
{1, 0},
{2, 1},
{0, 1}
}, Color.PINK);
;
final int[][] boundary;
final Color color;
TetrominoShape(int[][] boundary, Color color) {
this.boundary = boundary;
this.color = color;
}
}

View File

@@ -0,0 +1,46 @@
package eu.midnightdust.yaytris.ui;
import eu.midnightdust.yaytris.Tetris;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class GameCanvas extends JPanel {
final TetrisUI ui;
final BufferedImage texture;
GameCanvas(TetrisUI ui) {
this.ui = ui;
try {
this.texture = ImageIO.read(this.getClass().getResourceAsStream("/textures/tetromino.png"));
} catch (IOException | NullPointerException ex) {
throw new RuntimeException(ex);
}
}
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
if (graphics == null) return;
//graphics.clearRect(this.getX(), this.getY(), this.getWidth(), this.getHeight());
for (int x = 0; x < Tetris.space.getGameMap().length; x++) {
for (int y = 0; y < Tetris.space.getGameMap()[x].length; y++) {
Color color = Tetris.space.getGameMap()[x][y];
if (color == null) continue;
int blockSize = (this.getWidth()-this.getInsets().right)/Tetris.space.getGameMap().length;
//graphics.setXORMode(color);
graphics.drawImage(texture, x*blockSize +getInsets().left, y*blockSize + getInsets().top, blockSize, blockSize, color, this);
graphics.setColor(withAlpha(color, 100));
graphics.fillRect(x*blockSize +getInsets().left, y*blockSize + getInsets().top, blockSize, blockSize);
}
}
//this.paint(graphics);
//super.paintComponent(graphics);
}
public static Color withAlpha(Color color, int alpha) {
return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
}
}

View File

@@ -0,0 +1,25 @@
package eu.midnightdust.yaytris.ui;
import javax.swing.*;
import javax.swing.plaf.basic.BasicButtonUI;
import javax.swing.plaf.metal.MetalButtonUI;
import javax.swing.plaf.synth.SynthButtonUI;
import static eu.midnightdust.yaytris.ui.TetrisUI.scale;
import static eu.midnightdust.yaytris.ui.TetrisUI.setFontScale;
public class MainMenu extends JPanel {
final TetrisUI ui;
MainMenu(int x, int y, int width, int height, TetrisUI ui) {
this.ui = ui;
this.setBounds(x, y, width, height);
this.setLayout(null);
JButton settingsButton = new JButton("Settings");
settingsButton.addActionListener(ui::openSettings);
settingsButton.setBounds(scale(60), scale(20), scale(100), scale(20));
setFontScale(settingsButton);
this.add(settingsButton);
}
}

View File

@@ -0,0 +1,38 @@
package eu.midnightdust.yaytris.ui;
import eu.midnightdust.yaytris.Settings;
import eu.midnightdust.yaytris.Tetris;
import javax.swing.*;
import javax.swing.plaf.basic.BasicSliderUI;
import java.awt.*;
import static eu.midnightdust.yaytris.ui.TetrisUI.scale;
import static eu.midnightdust.yaytris.ui.TetrisUI.setFontScale;
public class SettingsMenu extends JPanel {
final TetrisUI ui;
SettingsMenu(int x, int y, int width, int height, TetrisUI ui) {
this.ui = ui;
this.setBounds(x, y, width, height);
this.setLayout(null);
JSlider scaleSlider = new JSlider(100, 500, (int) (Settings.guiScale * 100));
scaleSlider.setBounds(scale(10), scale(20), scale(200), scale(20));
scaleSlider.setBackground(Color.DARK_GRAY);
scaleSlider.addChangeListener(change -> {
Settings.guiScale = scaleSlider.getValue() / 100f;
Settings.write();
});
setFontScale(scaleSlider);
this.add(scaleSlider);
JButton backButton = new JButton("Back");
backButton.addActionListener(ui::openMainMenu);
backButton.setBounds(scale(60), scale(140), scale(100), scale(20));
setFontScale(backButton);
this.add(backButton);
}
}

View File

@@ -0,0 +1,116 @@
package eu.midnightdust.yaytris.ui;
import eu.midnightdust.yaytris.game.Space;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import static eu.midnightdust.yaytris.Settings.guiScale;
public class TetrisUI extends JFrame {
JLabel titleLabel;
GameCanvas gamePanel;
JPanel menuPanel;
public TetrisUI() {
Space space = new Space();
this.setLayout(null);
this.setTitle("Tetris");
this.setSize((int) (400 * guiScale), (int) (300 * guiScale));
this.setResizable(false);
this.getContentPane().setBackground(Color.DARK_GRAY);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setWindowPosition(this, 0);
titleLabel = new JLabel("Tetris");
titleLabel.setForeground(Color.WHITE);
Image titleImage;
try {
titleImage = ImageIO.read(this.getClass().getResourceAsStream("/textures/logo.png"));
} catch (IOException | NullPointerException ex) {
throw new RuntimeException(ex);
}
titleLabel = new JLabel();
titleLabel.setIcon(new ImageIcon(new ImageIcon(titleImage).getImage().getScaledInstance(scale(110), scale(30), Image.SCALE_DEFAULT)));
this.add(titleLabel);
gamePanel = new GameCanvas(this);
gamePanel.setBackground(Color.BLACK);
gamePanel.setBorder(new LineBorder(Color.GRAY, scale(2)));
this.add(gamePanel);
rescale();
openMainMenu(null);
this.setVisible(true);
}
private void rescale() {
this.setSize((int) (400 * guiScale), (int) (300 * guiScale));
titleLabel.setBounds(scale(225), scale(7), scale(110), scale(30));
gamePanel.setBounds(scale(10), scale(10), scale(150), scale(260));
for (Component comp : this.getComponents()){
if (comp instanceof JComponent) setFontScale((JComponent) comp);
}
}
public static int scale(int bound) {
return (int) (bound * guiScale);
}
public static void setFontScale(JComponent label) {
//if (label.getFont() != null) label.setFont(label.getFont().deriveFont((float) label.getFont().getSize() * guiScale));
}
public void openMainMenu(ActionEvent actionEvent) {
if (this.menuPanel != null) this.remove(menuPanel);
rescale();
menuPanel = new MainMenu(scale(170), scale(40), scale(220), scale(230), this);
menuPanel.setBackground(Color.DARK_GRAY);
menuPanel.setBorder(new LineBorder(Color.GRAY, scale(2)));
this.add(menuPanel);
this.repaint();
}
public void openSettings(ActionEvent actionEvent) {
if (this.menuPanel != null) this.remove(menuPanel);
menuPanel = new SettingsMenu(scale(170), scale(40), scale(220), scale(230), this);
menuPanel.setBackground(Color.DARK_GRAY);
menuPanel.setBorder(new LineBorder(Color.GRAY, scale(2)));
this.add(menuPanel);
this.repaint();
}
// Source: https://stackoverflow.com/a/19746437
private void setWindowPosition(JFrame window, int screen)
{
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] allDevices = env.getScreenDevices();
int topLeftX, topLeftY, screenX, screenY, windowPosX, windowPosY;
if (screen < allDevices.length && screen > -1)
{
topLeftX = allDevices[screen].getDefaultConfiguration().getBounds().x;
topLeftY = allDevices[screen].getDefaultConfiguration().getBounds().y;
screenX = allDevices[screen].getDefaultConfiguration().getBounds().width;
screenY = allDevices[screen].getDefaultConfiguration().getBounds().height;
}
else
{
topLeftX = allDevices[0].getDefaultConfiguration().getBounds().x;
topLeftY = allDevices[0].getDefaultConfiguration().getBounds().y;
screenX = allDevices[0].getDefaultConfiguration().getBounds().width;
screenY = allDevices[0].getDefaultConfiguration().getBounds().height;
}
windowPosX = ((screenX - window.getWidth()) / 2) + topLeftX;
windowPosY = ((screenY - window.getHeight()) / 2) + topLeftY;
window.setLocation(windowPosX, windowPosY);
}
}

View File

@@ -0,0 +1,113 @@
package eu.midnightdust.yaytris.util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
/*
NightJson v0.1 by Martin Prokoph
Extremely lightweight (and incomplete) JSON library
Concept inspired by GSON
*/
public class NightJson {
private static final String KEY_PATTERN = "\"(-?[0-9a-zA-Z]*)\":";
Class<?> jsonClass;
String fileLocation;
public NightJson(Class<?> jsonClass) {
this.jsonClass = jsonClass;
}
public NightJson(Class<?> jsonClass, String fileLocation) {
this(jsonClass);
this.fileLocation = fileLocation;
}
public void setFileLocation(String fileLocation) {
this.fileLocation = fileLocation;
}
public void writeJson() {
if (fileLocation == null) return;
try {
FileWriter jsonFile = new FileWriter(fileLocation);
jsonFile.write("{\n");
Iterator<Field> it = Arrays.stream(jsonClass.getFields()).iterator();
while (it.hasNext()) {
Field field = it.next();
jsonFile.write("\t");
if (field.getType() == Comment.class) {
jsonFile.write("// %s\n".formatted(((Comment) field.get(null)).commentString));
continue;
}
jsonFile.write((field.getType() == String.class || field.getType().isEnum() ? "\"%s\": \"%s\"" : "\"%s\": %s").formatted(field.getName(), field.get(null)));
jsonFile.write(it.hasNext() ? ",\n" : "\n");
}
jsonFile.write("}");
jsonFile.close();
} catch (IOException | IllegalAccessException e) {
System.out.println("Oh no! An Error occurred whilst writing the JSON file :(");
e.fillInStackTrace();
}
}
public void readJson() {
if (fileLocation == null) return;
try {
File file = new File(fileLocation);
if (!file.exists()) {
writeJson();
return;
}
Scanner jsonFile = new Scanner(file);
Map<String, String> jsonKeyValuePairs = new HashMap<>();
AtomicReference<String> lastKey = new AtomicReference<>();
jsonFile.forEachRemaining(s -> {
if (!s.matches("[{}]") && !s.matches("//+")) {
if (s.matches(KEY_PATTERN)) {
lastKey.set(s.replaceAll("([\":])", ""));
jsonKeyValuePairs.put(lastKey.get(), "");
}
else jsonKeyValuePairs.put(lastKey.get(), (jsonKeyValuePairs.get(
lastKey.get()).isEmpty() ? "" : jsonKeyValuePairs.get(lastKey.get()) + " "
) + s.replaceAll("([\",])", ""));
}
});
for (String key : jsonKeyValuePairs.keySet()) {
String currentString = jsonKeyValuePairs.get(key);
//System.out.printf("Key: %s Value: %s%n", key, currentString);
Field field;
try { field = jsonClass.getField(key);
} catch (NoSuchFieldException e) {continue;}
Object value = switch (field.getType().getName()) {
case "byte" -> Byte.parseByte(currentString);
case "int" -> Integer.parseInt(currentString);
case "long" -> Long.parseLong(currentString);
case "float" -> Float.parseFloat(currentString);
case "double" -> Double.parseDouble(currentString);
default -> currentString;
};
if (field.getType().isEnum()) value = Arrays.stream(field.getType().getEnumConstants())
.filter(enumConstant -> Objects.equals(enumConstant.toString(), currentString)).findFirst().orElseThrow();
field.set(field, value);
}
jsonFile.close();
} catch (IOException | IllegalAccessException | NoSuchElementException e) {
System.out.println("Oh no! An Error occurred whilst reading the JSON file :(");
e.fillInStackTrace();
}
}
public static class Comment {
final String commentString;
public Comment(String commentString) {
this.commentString = commentString;
}
}
}

View File

@@ -0,0 +1,31 @@
package eu.midnightdust.yaytris.util;
public class Vec2i {
private final int x;
private final int y;
Vec2i(int x, int y) {
this.x = x;
this.y = y;
}
public static Vec2i of(int x) {
//noinspection SuspiciousNameCombination
return new Vec2i(x, x);
}
public static Vec2i of(int x, int y) {
return new Vec2i(x, y);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Vec2i offset(Vec2i other) {
return new Vec2i(x + other.getX(), y + other.getY());
}
}