财富值给太少了吧
第三题
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class CrossDemo extends JFrame implements Runnable{
private BufferStrategy bs;
private volatile boolean running;
private Thread thread;
private Car car;
private int x_move, y_move;
public CrossDemo() {
x_move = 1;
y_move = 0;
}
protected void createAndShowGUI() {
Canvas canvas = new Canvas();
canvas.setSize( 600, 400 );
canvas.setBackground( Color.BLACK );
canvas.setIgnoreRepaint( true );
getContentPane().add( canvas );
setIgnoreRepaint( true );
pack();
setVisible( true );
canvas.createBufferStrategy( 2 );
bs = canvas.getBufferStrategy();
car = new Car(0, 200);
thread = new Thread( this );
thread.start();
}
public void run() {
running = true;
while( running ) {
updateObject();
renderFrame();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void updateObject() {
car.update(x_move, y_move);
if(car.x == 300 && car.y == 200) {
if(x_move == 1) {
x_move = 0;
y_move = 1;
} else if(y_move == -1) {
x_move = -1;
y_move = 0;
}
}
if(car.x == 0 && car.y == 200) {
x_move = 1;
}
if(car.x == 300 && car.y == 399) {
y_move = -1;
}
}
public void renderFrame() {
do {
do {
Graphics g = null;
try {
g = bs.getDrawGraphics();
g.clearRect( 0, 0, getWidth(), getHeight() );
render( g );
} finally {
if( g != null ) {
g.dispose();
}
}
} while( bs.contentsRestored() );
bs.show();
} while( bs.contentsLost() );
}
private void render( Graphics g ) {
g.setColor(Color.BLUE);
g.fillRect(0, 160, 600, 80);
g.fillRect(260, 0, 80, 400);
car.render(g);
}
protected void onWindowClosing() {
try {
running = false;
thread.join();
} catch( InterruptedException e ) {
e.printStackTrace();
}
System.exit( 0 );
}
public static void main( String[] args ) {
final CrossDemo app = new CrossDemo();
app.addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e ) {
app.onWindowClosing();
}
});
SwingUtilities.invokeLater( new Runnable() {
public void run() {
app.createAndShowGUI();
}
});
}
}
class Car {
int x, y;
public Car(int x, int y) {
this.x = x;
this.y = y;
}
public void update(int x_move, int y_move) {
x += x_move;
y += y_move;
}
public void render(Graphics g) {
g.setColor(Color.YELLOW);
g.drawRect(x - 15, y - 10, 30, 10);
g.drawOval(x - 15, y, 10, 10);
g.drawOval(x + 5, y, 10, 10);
}
}