代码拉取完成,页面将自动刷新
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;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。