虽然有点长,问题应该很简单,就是在keypressed事件中导入h.injured()里面不能传入monster
import java.awt.Color;import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameTest {
JFrame jf = new JFrame();
huabi hb = new huabi(0,0);
hunter h = new hunter();
Monster m = new Monster();
public void huamian(){
jf.setLocation(100, 100);
jf.setSize(500, 500);
jf.setVisible(true);
jf.add(hb);
jf.addKeyListener(new key());
}
@SuppressWarnings("serial")
class huabi extends JPanel{
int x;
int y;
public huabi(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.black);
g.drawRect(20, 20,20, 20);
}
}
class key extends KeyAdapter{
public void keyPressed(KeyEvent e){
super.keyPressed(e);
if(e.getKeyCode()==KeyEvent.VK_W) {
hb.y--;
}
else if(e.getKeyCode()==KeyEvent.VK_S){
hb.y++;
}
else if(e.getKeyCode()==KeyEvent.VK_A){
hb.x--;
}
else if(e.getKeyCode()==KeyEvent.VK_D){
hb.x++;
}
else if(e.getKeyCode()==KeyEvent.VK_Y){
h.fight(m);
}
hb.repaint();
jf.repaint();
}
}
public static void main(String args[]){
GameTest gm = new GameTest();
hunter h = new hunter();
h.name="德龙";
h.life=100;
h.islife=true;
Monster m = new Monster();
m.name="僵尸";
m.life=80;
m.islife=true;
gm.huamian();
}
}
class hunter{
int life;
String name;
boolean islife;
public void fight(Monster m){
if(m.islife==false)
{
return;
}
else
{
System.out.println("------------->"+name+"挥舞着武器"+"杀向"+m.name+"<---------------");
m.injured();
}
}
public void show(){
System.out.println("*************"+"猎人的life:"+life+"islive:"+islife+"************");
}
public void injured(){
life=life-2;
System.out.println(name+"被攻击了"+"当前生命为"+life);
if(life<=0)
dead();
}
public void dead(){
System.out.println("我竟然输给了你");
islife = false;
}
}
class Monster{
int life;
String name;
boolean islife;
public void injured(){
life=life-20;
if(life<0){
dead();
return;
}
System.out.println("*************"+name+"哇哇哇,呜呜呜"+"当前生命为:"+life+"*************");
}
public void dead(){
System.out.println("啊,我会来报仇的");
islife = false;
}
public void show()
{
System.out.println("*************"+"怪物的life:"+life+"islive:"+islife+"************");
}
public void attack(hunter h){
if(life<=0)
return;
else
{
System.out.println("******************"+name+"反击"+"当前生命为"+life);
h.injured();
}
}
}
补充:Java , Java SE