Game.java (1738B)
1 package game; 2 3 import java.util.Timer; 4 import java.util.TimerTask; 5 6 import javax.swing.JOptionPane; 7 8 import blocks.Poly; 9 10 public class Game extends Thread { 11 private Board board; 12 13 //gamespeed variables. 14 private int tickSpeed; 15 private final int maxTickSpeed = 250; 16 private final int minTickSpeed = 50; 17 18 BlockFactory factory; 19 20 private Poly fallingPoly; 21 22 /** 23 * Initiate game. 24 * @param The board on which the game shall be played out. 25 */ 26 public Game(Board board) { 27 tickSpeed = maxTickSpeed; 28 this.board = board; 29 factory = new BlockFactory(); 30 factory.setSpawn(board.getPrefferedSpawn()); 31 } 32 33 /** 34 * Run the game thread. 35 */ 36 public void run() { 37 while (!(board.hasLost())) { 38 calculateTickSpeed(); 39 40 //controll game speed 41 try { 42 Thread.sleep(tickSpeed); 43 } catch (InterruptedException e) { 44 e.printStackTrace(); 45 } 46 47 //run game 48 board.detectFullRow(); 49 board.repaint(); 50 51 // if there is a falling Poly move it one step down every iteration 52 // otherwise spawn a new Poly. 53 if (board.isFalling()) { 54 board.fall(fallingPoly); 55 } else { 56 board.givePoints(1); 57 fallingPoly = factory.generateRandomPoly(); 58 board.addPoly(fallingPoly); 59 } 60 61 //after all movement is done, redraw all graphics. 62 board.repaint(); 63 } 64 //if the user has lost, display the number of points collected by the user and exit the game. 65 System.out.println("You lost"); 66 JOptionPane.showMessageDialog(null, "You scored: " + board.getScore() + " points"); 67 System.exit(0); 68 } 69 70 /** 71 * Calculate the current speed at which the game should run. 72 */ 73 private void calculateTickSpeed() { 74 if (tickSpeed >= minTickSpeed) { 75 tickSpeed = maxTickSpeed - (board.getScore() / 2); 76 } 77 } 78 }