Java Tetris密钥监听器不工作(控制台上没有错误)

时间:2018-03-28 20:44:16

标签: java

我正在为我的AP计算机科学课程开展一个项目,并且似乎无法弄清楚如何让我的主要听众工作我尝试过使用if语句和切换案例但是都没有这些使关键听众工作。代码包括三个类Tetris Runner,Canvas,PeiceMaker一切功能都很好,除了关键的监听器。关键的监听器位于canvas类的底部,任何帮助都将不胜感激。

画布类

    package Tetris;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;


import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import Tetris.PieceMaker.Tetronimos;

@SuppressWarnings("serial")
public class Canvas extends JPanel implements ActionListener
{
    public static final int CANVASWIDTH = 10;
    public static final int CANVASHEIGHT = 22;

    private Color[] colors = 
    {
            new Color(0, 0, 0),
            new Color(204, 102, 102),
            new Color(102, 204, 102),
            new Color(102, 102, 204),
            new Color(204, 204, 102),
            new Color(204, 102, 204), 
            new Color(102, 204, 204), 
            new Color(218, 170, 0)
    };

    private boolean blockSet = false;
    private boolean startGame = false; 
    private boolean pauseGame = false;
    private int linesErased = 0;
    private int currentX = 0;
    private int currentY = 0;

    private JLabel scoreLabel;

    private Timer time;

    private PieceMaker currentShape;
    private Tetronimos[] canvas;

    public Canvas(TetrisRunner run)
    {
        setFocusable(true);
        currentShape = new PieceMaker();
        time = new Timer(500, this);
        scoreLabel = run.getScoreLabel();
        canvas = new Tetronimos[CANVASWIDTH * CANVASHEIGHT];
        clearCanvas();
        addKeyListener(new TetrisAdap());
    }

    public int blockWidth()
    {
        return (int)getSize().getWidth()/CANVASWIDTH;
    }

    public int blockHeight()
    {
        return (int)getSize().getHeight()/CANVASHEIGHT;
    }

    public Tetronimos shapeLocation(int x, int y)
    {
        return canvas[y * CANVASWIDTH + x];
    }

    public void clearCanvas()
    {
        for(int i = 0; i < CANVASHEIGHT * CANVASWIDTH; i++)
        {
            canvas[i] = Tetronimos.noShape;
        }
    }

    public void droppedPiece()
    {
        for(int i = 0; i < 4; i++)
        {
            int newX = currentX + currentShape.getXPosition(i);
            int newY = currentY - currentShape.getYPosition(i);

            canvas[newY * CANVASWIDTH + newX] = currentShape.getShape();
        }

        clearRow();

        if(!blockSet)
        {
            makeNewPiece();
        }
    }

    public void makeNewPiece()
    {
        currentShape.chooseRandomShape();

        currentX = CANVASWIDTH / 2 + 1;
        currentY = CANVASHEIGHT - 1 + currentShape.minY();

        if(!movePiece(currentShape, currentX, currentY - 1))
        {
            currentShape.setShape(Tetronimos.noShape);
            time.stop();

            startGame = false;
            scoreLabel.setText("GAME OVER");
        }
    }

    public void moveDownLine()
    {
        if(!movePiece(currentShape, currentX, currentY - 1))
        {
            droppedPiece();
        }
    }

    public void actionPerformed(ActionEvent e) 
    {
        if(blockSet)
        {
            blockSet = false;
            makeNewPiece();
        } else {
            moveDownLine();
        }
    }

    public void drawShape(int x, int y, Tetronimos shape, Graphics g)
    {
        Color color = colors[shape.ordinal()];
        g.setColor(color);
        g.fillRect(x + 1, y + 1, blockWidth() - 2, blockHeight() - 2);
        g.setColor(color.brighter());
        g.drawLine(x, y + blockHeight() - 1, x, y);
        g.drawLine(x, y, x + blockWidth() - 1, y);
        g.setColor(color.darker());
        g.drawLine(x + 1, y + blockHeight() - 1, x + blockWidth() - 1, y + blockHeight() - 1);
        g.drawLine(x + blockWidth() - 1, y + blockHeight() - 1, x + blockWidth() - 1, y + 1);
    }

    public void paint(Graphics g)
    {
        super.paint(g);

        Dimension size = getSize();

        int topOfCanvas = (int)size.getHeight() - CANVASHEIGHT * blockHeight();

        for(int i = 0; i < CANVASHEIGHT; i++)
        {
            for(int p = 0; p < CANVASWIDTH; p++)
            {
                Tetronimos shape = shapeLocation(p, CANVASHEIGHT - i - 1);

                if(shape != Tetronimos.noShape)
                {
                    drawShape(p * blockWidth(), topOfCanvas + i * blockHeight(), shape, g);
                }
            }
        }

        if(currentShape.getShape() != Tetronimos.noShape)
        {
            for(int i = 0; i < 4; i++) 
            {
                int x  = currentX + currentShape.getXPosition(i);
                int y = currentY - currentShape.getYPosition(i);

                drawShape(x * blockWidth(), topOfCanvas + (CANVASHEIGHT - y - 1) * blockHeight(), currentShape.getShape(), g);
            }
        }
    }

    public void start()
    {
        if(pauseGame)
        {
            return;
        }

        startGame = true;
        blockSet = false;
        linesErased = 0;

        clearCanvas();
        makeNewPiece();
        time.start();
    }

    public void pause()
    {
        if(!startGame)
        {
            return;
        }

        pauseGame = !pauseGame;

        if(pauseGame)
        {
            time.stop();
            scoreLabel.setText("PAUSED");
        } else {
            time.start();
            scoreLabel.setText(String.valueOf(linesErased));
        }

        repaint();
    }

    public boolean movePiece(PieceMaker newPiece, int xVel, int yVel)
    {
        for(int i = 0; i < 4; i++)
        {
            int x = xVel + newPiece.getXPosition(i);
            int y = yVel - newPiece.getYPosition(i);

            if(x < 0 || x >= CANVASWIDTH || y < 0 || y >= CANVASHEIGHT)
            {
                return false;
            }

            if(shapeLocation(x, y) != Tetronimos.noShape)
            {
                return false;
            }
        }

        currentShape = newPiece;
        currentX = xVel;
        currentY = yVel;

        repaint();

        return true;
    }



    public void clearRow()
    {
        int fullRows = 0;

        for(int i = CANVASHEIGHT - 1; i >= 0; i--)
        {
            boolean rowIsFull = true;

            for(int p = 0; p < CANVASWIDTH; p++)
            {
                if(shapeLocation(p, i) == Tetronimos.noShape)
                {
                    rowIsFull = false;
                    break;
                }
            }

            if(rowIsFull)
            {
                fullRows++;

                for(int j = i; j < CANVASHEIGHT - 1; j++)
                {
                    for(int k = 0; k < CANVASWIDTH; k++)
                    {
                        canvas[j * CANVASWIDTH + k] = shapeLocation(j, k + 1);
                    }
                }
            }

            if(fullRows > 0)
            {
                linesErased += fullRows;
                scoreLabel.setText(String.valueOf(linesErased));
                blockSet = true;
                currentShape.setShape(Tetronimos.noShape);

                repaint();
            }
        }
    }

    public void dropRows()
    {
        int nextY = currentY;

        while(nextY > 0)
        {
            if(!movePiece(currentShape, currentX, nextY - 1))
            {
                break;
            }
            nextY--;    
        }
        droppedPiece();
    }





    //Tetris Adapter

public class TetrisAdap extends KeyAdapter {

        public void KeyPressed(KeyEvent ke)
        {
            if(!startGame || currentShape.getShape() == Tetronimos.noShape) 
            {
                System.out.println("Here");
                return;
            }

        int keyCode = ke.getKeyCode();

        if(keyCode == 'p' || keyCode == 'P')
            pause();

        if(pauseGame)
            return;
        if(keyCode == KeyEvent.VK_LEFT) 
        {
            System.out.println("left");
            movePiece(currentShape, currentX - 1, currentY);
        }

        if(keyCode == KeyEvent.VK_RIGHT)
        {
            System.out.println("right");
            movePiece(currentShape, currentX + 1, currentY);
        }

        if(keyCode == KeyEvent.VK_DOWN) 
        {
            System.out.println("down");
            movePiece(currentShape.rotateRight(), currentX, currentY);
        }

        if(keyCode == KeyEvent.VK_UP)
        {
            System.out.println("up");
            movePiece(currentShape.rotateLeft(), currentX, currentY);   
        }

        if(keyCode == KeyEvent.VK_SPACE) 
        {
            dropRows();
        }

        if(keyCode == 'd')
            moveDownLine();

        if(keyCode == 'D')
            moveDownLine();

        /*
         * switch(keyCode) 
        {
            case KeyEvent.VK_LEFT:
                System.out.println("left");
                movePiece(currentShape, currentX - 1, currentY);
                break;
            case KeyEvent.VK_RIGHT:
                System.out.println("right");
                movePiece(currentShape, currentX + 1, currentY);
                break;
            case KeyEvent.VK_DOWN:
                System.out.println("down");
                movePiece(currentShape.rotateRight(), currentX, currentY);
                break;
            case KeyEvent.VK_UP:
                System.out.println("up");
                movePiece(currentShape.rotateLeft(), currentX, currentY);
                break;
            case KeyEvent.VK_SPACE:
                dropRows();
                break;                  
            case 'd' :
                moveDownLine();
                break;
            case 'D' :
                moveDownLine();
        }
         * 
         */

    }   

}
}

俄罗斯方块跑者

    package Tetris;

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;

@SuppressWarnings("serial")
public class TetrisRunner extends JFrame
{
    private JLabel scoreLabel;

    public TetrisRunner()
    {
        scoreLabel = new JLabel("0");
        add(scoreLabel, BorderLayout.SOUTH);

        Canvas canvas = new Canvas(this);
        add(canvas);

        canvas.makeNewPiece();
        canvas.start();

        setSize(400, 800);
        setTitle("Tetris");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args)
    {
        TetrisRunner runner = new TetrisRunner();
        runner.setLocationRelativeTo(null);
        runner.setVisible(true);    
    }

    public JLabel getScoreLabel()
    {
        return scoreLabel;
    }
}

Peice Maker

package Tetris;

import java.util.Random;

public class PieceMaker 
{
    private Tetronimos shapeChoice;
    private int[][] coordinates;

    public PieceMaker()
    {
        coordinates = new int[4][2];
        setShape(Tetronimos.noShape);
    }

    enum Tetronimos 
    {
        noShape(new int[][] { {0,0}, {0,0}, {0,0}, {0,0} }),
        lineShape(new int[][] { {0,-1}, {0,0}, {0,1}, {0,2} }),
        sShape(new int[][] { {0,-1}, {0,0}, {1,0}, {1,1} }),
        zShape(new int[][] { {0,-1}, {0,0}, {-1,0}, {-1,1} }),
        tShape(new int[][] { {-1,0}, {0,0}, {1,0}, {0,1} }),
        lShape(new int[][] { {-1,-1}, {0,-1}, {0,0}, {0,1} }),
        jShape(new int[][] { {-1,-1}, {0,-1}, {0,0}, {0,1} }),
        blockShape(new int[][] { {0,0}, {1,0}, {0,1}, {1,1} });

        public int[][] shapeCoordinates;

        private Tetronimos(int[][] coordinates)
        {
            this.shapeCoordinates = coordinates;
        }
    }

    public void chooseRandomShape()
    {
        Random rand = new Random();
        int randChoice = Math.abs(rand.nextInt() % 7 + 1);

        Tetronimos[] choice = Tetronimos.values();
        setShape(choice[randChoice]);
    }

    public void setShape(Tetronimos shape)
    {
        for(int i = 0; i < 4; i++)
        {
            for(int p = 0; p < 2; p++)
            {
                coordinates[i][p] = shape.shapeCoordinates[i][p];
            }
        }

        shapeChoice = shape;
    }

    public void setXPosition(int oldX, int newX)
    {
        coordinates[oldX][0] = newX;
    }

    public void setYPosition(int oldY, int newY)
    {
        coordinates[oldY][1] = newY;
    }

    public int getXPosition(int newX)
    {
        return coordinates[newX][0];
    }

    public int getYPosition(int newY)
    {
        return coordinates[newY][1];
    }

    public Tetronimos getShape()
    {
        return shapeChoice;
    }

    public int minX()
    {
        int minX = coordinates[0][0];

        for(int i = 0; i < 4; i++)
        {
            minX = Math.min(minX, coordinates[i][0]);
        }

        return minX;
    }

    public int minY()
    {
        int minY = coordinates[0][1];

        for(int i = 0; i < 4; i++)
        {
            minY = Math.min(minY, coordinates[i][1]);
        }

        return minY;
    }


    //Rotate piece Left
    public PieceMaker rotateLeft() 
    {
        System.out.println("left");
        if(shapeChoice == Tetronimos.blockShape)
        {
            return this;
        }

        PieceMaker res = new PieceMaker();
        res.shapeChoice = shapeChoice;

        for(int i = 0; i < 4; i++) 
        {
            res.setXPosition(i, getYPosition(i));
            res.setYPosition(i, -getXPosition(i));
        }
        return res;     
    }

    //Rotate piece right
    public PieceMaker rotateRight() 
    {
        System.out.println("right");
        if(shapeChoice == Tetronimos.blockShape)
        {
            return this;
        }
        PieceMaker res = new PieceMaker();
        res.shapeChoice = shapeChoice;


        for(int i = 0; i < 4; i++) 
        {
            res.setXPosition(i, -getYPosition(i));
            res.setYPosition(i, getXPosition(i));   
        }
        return res; 
    }
}       

1 个答案:

答案 0 :(得分:0)

你拼错了你的keyPressed() - 方法。使用

public class TetrisAdap extends KeyAdapter {

        public void keyPressed(KeyEvent ke) { ...

而不是

public class TetrisAdap extends KeyAdapter {

    public void KeyPressed(KeyEvent ke)
    {