java贪吃蛇项目_java SE 学习第一个项目-贪吃蛇

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);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值