commit b577d2f09753578133bc7e1b3398251712b551d7
parent 6138f400d734a434eb149ad765ba1bced9864a09
Author: William Lindholm <william_lindholm@outlook.com>
Date: Wed, 22 Mar 2023 01:40:39 +0100
changed to threaded game function and added dynamic timing
Diffstat:
2 files changed, 42 insertions(+), 23 deletions(-)
diff --git a/OOP2023_a22willi_a21liltr_assignment4/src/game/Game.java b/OOP2023_a22willi_a21liltr_assignment4/src/game/Game.java
@@ -7,43 +7,62 @@ import javax.swing.JOptionPane;
import blocks.Poly;
-public class Game {
+public class Game extends Thread {
private Board board;
private Timer timer;
- private final int tickRate = 200;
+
+ private int tickSpeed;
+ private final int maxTickSpeed = 250;
+ private final int minTickSpeed = 50;
BlockFactory factory;
private Poly poly;
public Game(Board board) {
+
+ tickSpeed = maxTickSpeed;
+
timer = new Timer();
- timer.scheduleAtFixedRate(gameLoop, tickRate, tickRate);
this.board = board;
factory = new BlockFactory();
factory.setSpawn(board.getPrefferedSpawn());
}
-
- private TimerTask gameLoop = new TimerTask() {
- @Override
- public void run() {
+
+ public void run() {
+ while (!(board.hasLost())) {
+ calculateTickSpeed();
+
+ //controll game speed
+ try {
+ Thread.sleep(tickSpeed);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+
+ //run game
board.detectFullRow();
- if (!(board.hasLost())) {
- board.repaint();
- if (board.isFalling()) {
- board.fall(poly);
- } else {
- board.givePoints(1);
- poly = factory.generateRandomPoly();
- board.addPoly(poly);
- }
-
- board.repaint();
+ board.repaint();
+
+ if (board.isFalling()) {
+ board.fall(poly);
} else {
- System.out.println("You lost");
- JOptionPane.showMessageDialog(null, "You scored: " + board.getScore() + " points");
- System.exit(0);
+ board.givePoints(1);
+ poly = factory.generateRandomPoly();
+ board.addPoly(poly);
}
+
+ board.repaint();
}
- };
+ System.out.println("You lost");
+ JOptionPane.showMessageDialog(null, "You scored: " + board.getScore() + " points");
+ System.exit(0);
+ }
+
+ private void calculateTickSpeed() {
+ if (tickSpeed >= minTickSpeed) {
+ tickSpeed = maxTickSpeed - (board.getScore() / 2);
+ }
+ System.out.println("delay: " + tickSpeed);
+ }
}
diff --git a/OOP2023_a22willi_a21liltr_assignment4/src/game/Main.java b/OOP2023_a22willi_a21liltr_assignment4/src/game/Main.java
@@ -9,6 +9,6 @@ public class Main {
Board board = new Board();
GUI gui = new GUI(board);
Game game = new Game(board);
-
+ game.start();
}
}