import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.Timer; import java.util.Random; public class World extends JPanel implements KeyListener, ActionListener { Timer timer; Shape[] board; public World(Game parent) { parent.addKeyListener(this); timer = new Timer(400, this); board = new Shape[BoardWidth * BoardHeight]; } Shape shapeAt(int x, int y) { return board[(y * BoardWidth) + x]; } public void keyPressed(KeyEvent e) { System.out.println( "... Key pressed: " + e ); int keycode = e.getKeyCode(); switch (keycode) { case KeyEvent.VK_LEFT: shape.tryMove(shape.curX - 1, shape.curY); break; case KeyEvent.VK_RIGHT: shape.tryMove(shape.curX + 1, shape.curY); break; } } public void keyReleased(KeyEvent e) { System.out.println( "... Key typed: " + e ); } public void keyTyped(KeyEvent e) { System.out.println( "... Key typed: " + e ); } public void start() { this.timer.start(); } boolean isFallingFinished = true; public void actionPerformed(ActionEvent e) { if (isFallingFinished) { isFallingFinished = false; newPiece(); } else { oneLineDown(); } } Shape shape; private void newPiece() { shape = randomShape(); System.out.println( shape ); if (! shape.tryMove(BoardWidth / 2 + 1, BoardHeight - 1 + shape.minY())) { // curPiece.setShape(Tetrominoes.NoShape); timer.stop(); // isStarted = false; // statusbar.setText("game over"); System.exit(0); } // this.repaint(); count = 0; } Shape randomShape() { Random r = new Random(); int x = Math.abs(r.nextInt()) % 7 + 1; int type = (int) (Math.random() * 8); switch (type) { // case 0: return new NoShape(this); case 1: return new LShape(this); case 2: return new MirroredLShape(this); case 3: return new LineShape(this); case 4: return new SquareShape(this); case 5: return new SShape(this); case 6: return new ZShape(this); case 7: return new TShape(this); } return new NoShape(this); } int count = 0; private void oneLineDown() { if (! (shape.tryMove(shape.curX, shape.curY - 1))) pieceDropped(); count += 1; System.out.println( count ); if (count == 20) { isFallingFinished = true; } } private void pieceDropped() { // for (int i = 0; i < 4; ++i) { // int x = curX + curPiece.x(i); // int y = curY - curPiece.y(i); // board[(y * BoardWidth) + x] = curPiece.getShape(); // } // removeFullLines(); // if (!isFallingFinished) // newPiece(); } public void paint(Graphics g) { super.paint(g); // for (Shape shape : shapes) shape.draw(g); if (shape != null) shape.draw(g); } int squareWidth() { return (int) getSize().getWidth() / BoardWidth; } int squareHeight() { return (int) getSize().getHeight() / BoardHeight; } final int BoardWidth = 10; final int BoardHeight = 22; }