// // Tetris game // import java.awt.*; import java.awt.event.*; class Tetris extends Frame { public static void main(String [] args) { Tetris world = new Tetris(); world.show(); } // data fields public static final int FrameWidth = 300; public static final int FrameHeight = 400; private PieceMover player; public Tetris () { setSize (FrameWidth, FrameHeight); setTitle("Tetris"); addKeyListener (new keyDown()); //requestFocus(); player = new PieceMover(this); player.start(); } // interface point between two threads private int currentCommand = Piece.Down; public synchronized int getCommand(int nextCommand) { int oldCommand = currentCommand; currentCommand = nextCommand; return oldCommand; } private class keyDown extends KeyAdapter { public void keyPressed (KeyEvent e) { char key = e.getKeyChar(); switch (key) { case 'g': player.newGame(); break; case 'j': getCommand(Piece.Left); break; case 'k': getCommand(Piece.Rotate); break; case 'l': getCommand(Piece.Right); break; case 'q': System.exit(0); } } } public void update (Graphics g) { Image buffer = createImage (FrameWidth, FrameHeight); Graphics sg = buffer.getGraphics(); sg.clearRect(0, 0, FrameWidth, FrameHeight); player.paint(sg); g.drawImage (buffer, 0, 0, this); } } class PieceMover extends Thread { // private data fields private Tetris controller; private Color table[][]; private Piece currentPiece; private int score = 0; // constructor public PieceMover (Tetris t) { controller = t; table = new Color[15][30]; newGame(); } // thread starting point public void run () { while (dropPiece()) { } } // other methods public void newGame () { for (int i = 0; i < 30; i++) for (int j = 0; j < 15; j++) table[j][i] = Color.white; } public void paint (Graphics g) { for (int i = 0; i < 30; i++) for (int j = 0; j < 15; j++) { g.setColor(table[j][i]); g.fillRect(20+10*j, 350-10*i, 10, 10); } g.setColor(Color.blue); g.drawString("Score " + score, 200, 200); } private boolean dropPiece () { int piecetype = 1 + (int) (7 * Math.random()); currentPiece = new Piece(piecetype); if (! currentPiece.move(Piece.Down, table)) return false; int command = controller.getCommand(Piece.Down); while (currentPiece.move(command, table)) { controller.repaint(); yield(); try { sleep(100); } catch(InterruptedException e) { } command = controller.getCommand(Piece.Down); } // piece cannot move, check score checkScore(); return true; } private void checkScore() { for (int i = 0; i < 30; i++) { boolean scored = true; for (int j = 0; j < 15; j++) if (table[j][i] == Color.white) scored = false; if (scored) { score += 10; moveDown(i); i = i - 1; // check row again } } } private void moveDown (int start) { for (int i = start; i < 30; i++) for (int j = 0; j < 15; j++) if (i < 29) table[j][i] = table[j][i+1]; else table[j][i] = Color.white; } }