这是我写了一半的贪吃蛇代码,但是我却无法解决键盘事件的一个问题。这些代码是我照着参考书的键盘事件写的。请问我的代码出现了什么问题?
问题:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method addKeyListener(KeyListener) in the type Component is not applicable for the arguments (new PythonGame_Java.KeyListener(){})
The type new PythonGame_Java.KeyListener(){} must implement the inherited abstract method PythonGame_Java.KeyListener.keyPressed(keyEvent)
keyEvent cannot be resolved to a type
The method game(Graphics) in the type DrawPanel is not applicable for the arguments ()
at 挑战Java编贪吃蛇.PythonGame_Java.main(PythonGame_Java.java:30)
代码如下:
package 挑战Java编贪吃蛇;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.EventListener;
import javax.swing.*;
import java.io.*;
public class PythonGame_Java extends JFrame{ //蟒蛇游戏(贪吃蛇) Java语言 (我之前用Python编了类似的程序)
public PythonGame_Java(){ //<init>
super();
init();
}
public interface KeyListener extends EventListener{
public void keyPressed(keyEvent e);
}
public void init(){
this.setSize(900,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(new DrawPanel());
this.setTitle("Java贪吃蛇");
setResizable(false);
setVisible(true);
}
public static void main(String[] args) throws InterruptedException {
PythonGame_Java Game = new PythonGame_Java();
JTextArea textArea = new JTextArea();
textArea.addKeyListener(new KeyListener() {
public void keyPressed(keyEvent e){
String keyTest=KeyEvent.getKeyText(e.getKeyCode());
System.out.println(keyTest);
}
});
class DrawPanel extends JPanel{ //蛇身宽度=10
private boolean started=true;
private final int wait_time=300;
private int snake[][]=new int[10000][2];
private int length=0;
private int currx=0;
private int curry=0;
private int BonusX=10;
private int BonusY=10;
private int loopnum=0;
private String snake_dir="right";
public void main(String[] args){
game();
}
public void game(Graphics g) throws InterruptedException{
snake[0][0]=0;
snake[0][1]=0;
while(started==true){
g.setColor(Color.WHITE);
g.fillRect(0,0,900,600);
g.setColor(Color.BLUE);
for(int i=0;i<=length;i++)
g.fillRect(snake[i][0]*10,snake[i][1]*10,10,10);
switch(snake_dir){
case "left":
currx--;
case "right":
currx++;
case "up":
curry--;
case "down":
curry++;
}
if(currx<0)
currx=0;
if(curry<0)
curry=0;
if(currx>90)
currx=90;
if(curry>60)
curry=60;
snake[loopnum][0]=currx;
snake[loopnum][1]=curry;
loopnum++;
if(loopnum>length)
loopnum=0;
if(currx==BonusX && curry==BonusY){
length++;
BonusX=(int)(Math.random())*91;
BonusY=(int)(Math.random())*61;
}
Thread.sleep(wait_time);
} //游戏循环结束
} //游戏函数结束
} //子类结束
}} //父类结束?