importjavafx.scene.layout.CornerRadii;import java.awt.*;importjava.awt.event.KeyAdapter;importjava.awt.event.KeyEvent;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;public class Yard extendsFrame {
PaintThread paintThread= newPaintThread();private boolean gameOver = false;public static final int ROWS = 50;public static final int COLS = 50;public static final int BLOCK_SIZE = 15;private int score = 0;
Snake s= new Snake(this);
Egg e= newEgg();public voidlaunch() {this.setLocation(0, 0);this.setSize(COLS * BLOCK_SIZE, ROWS *BLOCK_SIZE);this.addWindowListener(newWindowAdapter() {
@Overridepublic voidwindowClosing(WindowEvent e) {
System.exit(0);
}
});this.addKeyListener(newKeyMonitor());this.setVisible(true);newThread(paintThread).start();
}public static voidmain(String[] args) {newYard().launch();
}public voidstop(){
gameOver= true;
}public intgetScore() {returnscore;
}public void setScore(intscore) {this.score =score;
}public voidpaint(Graphics g) {
Color c=g.getColor();
g.setColor(Color.gray);
g.fillRect(0, 0, COLS * BLOCK_SIZE, ROWS *BLOCK_SIZE);
g.setColor(Color.darkGray);for (int i = 0; i < ROWS - 1; i++) {
g.drawLine(0, BLOCK_SIZE * i, COLS * BLOCK_SIZE, BLOCK_SIZE *i);
}for (int i = 0; i < COLS - 1; i++) {
g.drawLine(BLOCK_SIZE* i, 0, BLOCK_SIZE * i, ROWS *BLOCK_SIZE);
}
g.setColor(Color.YELLOW);
g.drawString("score:"+score,10,60);
g.setColor(c);
s.eat(e);
s.draw(g);
e.draw(g);
g.setColor(Color.cyan);if(gameOver){
g.setFont(new Font("华文彩云",Font.BOLD,50));
g.drawString("游戏结束",120,180);
paintThread.gameOver();
}
g.setColor(c);
}
@Overridepublic voidupdate(Graphics g) {
Image offScreenImage= null;if (offScreenImage == null) {
offScreenImage= this.createImage(BLOCK_SIZE * COLS, BLOCK_SIZE *ROWS);
}
Graphics gOff=offScreenImage.getGraphics();
paint(gOff);
g.drawImage(offScreenImage,0, 0, null);
}private class PaintThread implementsRunnable {private boolean running = true;public voidrun() {while(running) {
repaint();try{
Thread.sleep(50);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}public voidgameOver(){
running= false;
}
}private class KeyMonitor extendsKeyAdapter {
@Overridepublic voidkeyPressed(KeyEvent e) {
s.keyPressed(e);
}
}
}