我正在使用java applet构建一个简单的赛车游戏,但它无法正常工作 即使经过多次干运行,我也没有看到代码中的任何错误。 为什么变量' i'我的代码没有增加......
import java.awt.*;
import java.awt.Dimension;
import java.util.Random;
import java.awt.event.*;
import java.applet.*;
import javax.swing.JApplet;
import javax.swing.JOptionPane;
/*
<applet code= "car.class" height=1000 width=2000>
<param name="my" value="opp1_car.png">
<param name="you" value="opp2_car.png">
</applet>
*/
public class car extends Applet implements KeyListener,Runnable
{ int x=0,y=0,x1=0,a=50,i=0;
Image car,car_opp;
int width,height,width_op1=0,width_op2=0;
Thread t;
public void init()
{
addKeyListener(this);
setBackground(Color.gray);
this.requestFocus();
Dimension dim=Toolkit.getDefaultToolkit().getScreenSize();
width= (int)(dim.getWidth())/2;
height=(int)dim.getHeight();
}
public void paint(Graphics g)
{
g.setColor(Color.green);
g.fillRect(0,0,600,1000);
g.setColor(Color.green);
g.fillRect(1400,0,600,1000);
car_opp = getImage(getDocumentBase(),getParameter("you"));
g.drawImage(car_opp,width+width_op1,i,this); // this is not moving
car = getImage(getDocumentBase(),getParameter("my")); // this moves on LEFT or RIGHT keyEvent
g.drawImage(car,width+x,700,this);
String s="("+width_op1+",x="+x+",y="+y+")";
g.setColor(Color.red);
g.drawString(s,200,500);
}
public void keyPressed(KeyEvent e) {
int k=e.getKeyCode();
switch(k)
{
case KeyEvent.VK_LEFT: if(x>-360 ) x=x-20; break;
case KeyEvent.VK_RIGHT: if( x<340 ) x=x+20; break;
}
repaint();
}
public void start()
{
t = new Thread();
t.start();
}
public void run()
{
while(true)
{ Random random= new Random();
try
{
i=i+50;
t.wait(100);
if(i>1000)
{
i=100;
width_op1=random.nextInt(340 + 360 + 1) -360;
width_op2=random.nextInt(340 + 360 + 1) -360;
width_op1=200;
}
repaint();
}
catch(Exception e){}
/*if((i>680&& i<780) && (x < width_op1+50 && x>width_op1-50))
{
System.exit(0);
}*/
}
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
}
答案 0 :(得分:1)
您误解了线程的工作原理。要在线程中运行Runnable,必须将其传递给构造函数,然后运行Thread。
试试这个:
public void start(){
t = new Thread(this);
t.start();
}