加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Yard.java 2.57 KB
一键复制 编辑 原始数据 按行查看 历史
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Yard extends Frame{
public static int ROWS=30;
public static int COLS=30;
public static int BLOCK_SIZE=15;
boolean gameOver=false;
Snake snake=new Snake(this);
Egg egg=new Egg();
Image offScreenImage=null;
MyThread my=new MyThread();
int score=0;
public static void main(String[] args) {
new Yard().launch();
}
public void launch() {
this.setVisible(true);
this.setLocation(200,200);
this.setSize(COLS*BLOCK_SIZE,ROWS*BLOCK_SIZE);
this.addWindowListener(new WindowMonitor());
this.addKeyListener(new KeyMonitor());
new Thread(my).start();
}
@Override
public void paint(Graphics g) {
Color c=g.getColor();
g.setColor(Color.GRAY);
g.fillRect(0, 0, COLS*BLOCK_SIZE,ROWS*BLOCK_SIZE);
g.setColor(Color.DARK_GRAY);
for(int i=0;i<ROWS;i++) {
g.drawLine(0, BLOCK_SIZE*i, BLOCK_SIZE*COLS, BLOCK_SIZE*i);
}
for(int j=1;j<COLS;j++) {
g.drawLine(BLOCK_SIZE*j,0,BLOCK_SIZE*j , BLOCK_SIZE*ROWS);
}
g.setColor(Color.YELLOW);
g.drawString("Score:"+score,10,60);
if(gameOver==true) {
g.setFont(new Font("IJ",Font.BOLD|Font.HANGING_BASELINE,50));
g.drawString("Game Over", 80, 200);
my.GameOver();
}
g.setColor(c);
snake.eat(egg);
snake.draw(g);
egg.draw(g);
snake.checkDead();
}
public void update(Graphics g) {
if(offScreenImage==null) {
offScreenImage=this.createImage(COLS*BLOCK_SIZE,ROWS*BLOCK_SIZE);
}
Graphics gOff=offScreenImage.getGraphics();
paint (gOff);
g.drawImage(offScreenImage, 0, 0, null);
}
public class MyThread implements Runnable {
boolean flag=true;
@Override
public void run() {
while(flag) {
repaint();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void GameOver() {
flag=false;
}
public void reStart() {
this.flag=true;
}
}
public class WindowMonitor extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
public class KeyMonitor extends KeyAdapter {
public void keyPressed(KeyEvent e) {
snake.keyPressed(e);
int key=e.getKeyCode();
if(key==KeyEvent.VK_F2) {
//my.reStart();
}
}
}
public void stop() {
gameOver = true;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化