急需用eclipse写的小游戏代码 比如贪吃蛇,五子棋,猜数字,俄罗斯方块等的小游戏代码
新建一个project,新建一个类
把代码贴进去,找到运行(run)这个按钮,按了就能运行,找不到的话快捷键是Ctrl + F11
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class SnakeGame {
public static void main(String[] args) {
SnakeFrame frame = new SnakeFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
// ----------记录状态的线程
class StatusRunnable implements Runnable {
public StatusRunnable(Snake snake, JLabel statusLabel, JLabel scoreLabel) {
this.statusLabel = statusLabel;
this.scoreLabel = scoreLabel;
this.snake = snake;
}
public void run() {
String sta = "";
String spe = "";
while (true) {
switch (snake.status) {
case Snake.RUNNING:
sta = "Running";
break;
case Snake.PAUSED:
sta = "Paused";
break;
case Snake.GAMEOVER:
sta = "GameOver";
break;
}
statusLabel.setText(sta);
scoreLabel.setText("" + snake.score);
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
private JLabel scoreLabel;
private JLabel statusLabel;
private Snake snake;
}
// ----------蛇运动以及记录分数的线程
class SnakeRunnable implements Runnable {
public SnakeRunnable(Snake snake, Component component) {
this.snake = snake;
this.component = component;
}
public void run() {
while (true) {
try {
snake.move();
component.repaint();
Thread.sleep(snake.speed);
} catch (Exception e) {
}
}
}
private Snake snake;
private Component component;
}
class Snake {
boolean isRun;// ---------是否运动中
ArrayListNode body;// -----蛇体
Node food;// --------食物
int derection;// --------方向
int score;
int status;
int speed;
public static final int SLOW = 500;
public static final int MID = 300;
public static final int FAST = 100;
public static final int RUNNING = 1;
public static final int PAUSED = 2;
public static final int GAMEOVER = 3;
public static final int LEFT = 1;
public static final int UP = 2;
public static final int RIGHT = 3;
public static final int DOWN = 4;
public Snake() {
speed = Snake.SLOW;
score = 0;
isRun = false;
status = Snake.PAUSED;
derection = Snake.RIGHT;
body = new ArrayListNode();
body.add(new Node(60, 20));
body.add(new Node(40, 20));
body.add(new Node(20, 20));
makeFood();
}
// ------------判断食物是否被蛇吃掉
// -------如果食物在蛇运行方向的正前方,并且与蛇头接触,则被吃掉
private boolean isEaten() {
Node head = body.get(0);
if (derection == Snake.RIGHT (head.x + Node.W) == food.x
head.y == food.y)
return true;
if (derection == Snake.LEFT (head.x - Node.W) == food.x
head.y == food.y)
return true;
if (derection == Snake.UP head.x == food.x
(head.y - Node.H) == food.y)
return true;
if (derection == Snake.DOWN head.x == food.x
(head.y + Node.H) == food.y)
return true;
else
return false;
}
// ----------是否碰撞
private boolean isCollsion() {
Node node = body.get(0);
// ------------碰壁
if (derection == Snake.RIGHT node.x == 280)
return true;
if (derection == Snake.UP node.y == 0)
return true;
if (derection == Snake.LEFT node.x == 0)
return true;
if (derection == Snake.DOWN node.y == 380)
return true;
// --------------蛇头碰到蛇身
Node temp = null;
int i = 0;
for (i = 3; i body.size(); i++) {
temp = body.get(i);
if (temp.x == node.x temp.y == node.y)
break;
}
if (i body.size())
return true;
else
return false;
}
// -------在随机的地方产生食物
public void makeFood() {
Node node = new Node(0, 0);
boolean isInBody = true;
int x = 0, y = 0;
int X = 0, Y = 0;
int i = 0;
while (isInBody) {
x = (int) (Math.random() * 15);
y = (int) (Math.random() * 20);
X = x * Node.W;
Y = y * Node.H;
for (i = 0; i body.size(); i++) {
if (X == body.get(i).x Y == body.get(i).y)
break;
}
if (i body.size())
isInBody = true;
else
isInBody = false;
}
food = new Node(X, Y);
}
// ---------改变运行方向
public void changeDerection(int newDer) {
if (derection % 2 != newDer % 2)// -------如果与原来方向相同或相反,则无法改变
derection = newDer;
}
public void move() {
if (isEaten()) {// -----如果食物被吃掉
body.add(0, food);// --------把食物当成蛇头成为新的蛇体
score += 10;
makeFood();// --------产生食物
} else if (isCollsion())// ---------如果碰壁或自身
{
isRun = false;
status = Snake.GAMEOVER;// -----结束
} else if (isRun) {// ----正常运行(不吃食物,不碰壁,不碰自身)
Node node = body.get(0);
int X = node.x;
int Y = node.y;
// ------------蛇头按运行方向前进一个单位
switch (derection) {
case 1:
X -= Node.W;
break;
case 2:
Y -= Node.H;
break;
case 3:
X += Node.W;
break;
case 4:
Y += Node.H;
break;
}
body.add(0, new Node(X, Y));
// ---------------去掉蛇尾
body.remove(body.size() - 1);
}
}
}
// ---------组成蛇身的单位,食物
class Node {
public static final int W = 20;
public static final int H = 20;
int x;
int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
// ------画板
class SnakePanel extends JPanel {
Snake snake;
public SnakePanel(Snake snake) {
this.snake = snake;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Node node = null;
for (int i = 0; i snake.body.size(); i++) {// ---红蓝间隔画蛇身
if (i % 2 == 0)
g.setColor(Color.blue);
else
g.setColor(Color.yellow);
node = snake.body.get(i);
g.fillRect(node.x, node.y, node.H, node.W);// *******************试用*********************
}
node = snake.food;
g.setColor(Color.red);
g.fillRect(node.x, node.y, node.H, node.W);
}
}
class SnakeFrame extends JFrame {
private JLabel statusLabel;
private JLabel speedLabel;
private JLabel scoreLabel;
private JPanel snakePanel;
private Snake snake;
private JMenuBar bar;
JMenu gameMenu;
JMenu helpMenu;
JMenu speedMenu;
JMenuItem newItem;
JMenuItem pauseItem;
JMenuItem beginItem;
JMenuItem helpItem;
JMenuItem aboutItem;
JMenuItem slowItem;
JMenuItem midItem;
JMenuItem fastItem;
public SnakeFrame() {
init();
ActionListener l = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == pauseItem)
snake.isRun = false;
if (e.getSource() == beginItem)
snake.isRun = true;
if (e.getSource() == newItem) {
newGame();
}
// ------------菜单控制运行速度
if (e.getSource() == slowItem) {
snake.speed = Snake.SLOW;
speedLabel.setText("Slow");
}
if (e.getSource() == midItem) {
snake.speed = Snake.MID;
speedLabel.setText("Mid");
}
if (e.getSource() == fastItem) {
snake.speed = Snake.FAST;
speedLabel.setText("Fast");
}
}
};
pauseItem.addActionListener(l);
beginItem.addActionListener(l);
newItem.addActionListener(l);
aboutItem.addActionListener(l);
slowItem.addActionListener(l);
midItem.addActionListener(l);
fastItem.addActionListener(l);
addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
// ------------方向键改变蛇运行方向
case KeyEvent.VK_DOWN://
snake.changeDerection(Snake.DOWN);
break;
case KeyEvent.VK_UP://
snake.changeDerection(Snake.UP);
break;
case KeyEvent.VK_LEFT://
snake.changeDerection(Snake.LEFT);
break;
case KeyEvent.VK_RIGHT://
snake.changeDerection(Snake.RIGHT);
break;
// 空格键,游戏暂停或继续
case KeyEvent.VK_SPACE://
if (snake.isRun == true) {
snake.isRun = false;
snake.status = Snake.PAUSED;
break;
}
if (snake.isRun == false) {
snake.isRun = true;
snake.status = Snake.RUNNING;
break;
}
}
}
public void keyReleased(KeyEvent k) {
}
public void keyTyped(KeyEvent k) {
}
});
}
private void init() {
speedLabel = new JLabel();
snake = new Snake();
setSize(380, 460);
setLayout(null);
this.setResizable(false);
bar = new JMenuBar();
gameMenu = new JMenu("Game");
newItem = new JMenuItem("New Game");
gameMenu.add(newItem);
pauseItem = new JMenuItem("Pause");
gameMenu.add(pauseItem);
beginItem = new JMenuItem("Continue");
gameMenu.add(beginItem);
helpMenu = new JMenu("Help");
aboutItem = new JMenuItem("About");
helpMenu.add(aboutItem);
speedMenu = new JMenu("Speed");
slowItem = new JMenuItem("Slow");
fastItem = new JMenuItem("Fast");
midItem = new JMenuItem("Middle");
speedMenu.add(slowItem);
speedMenu.add(midItem);
speedMenu.add(fastItem);
bar.add(gameMenu);
bar.add(helpMenu);
bar.add(speedMenu);
setJMenuBar(bar);
statusLabel = new JLabel();
scoreLabel = new JLabel();
snakePanel = new JPanel();
snakePanel.setBounds(0, 0, 300, 400);
snakePanel.setBorder(BorderFactory.createLineBorder(Color.darkGray));
add(snakePanel);
statusLabel.setBounds(300, 25, 60, 20);
add(statusLabel);
scoreLabel.setBounds(300, 20, 60, 20);
add(scoreLabel);
JLabel temp = new JLabel("状态");
temp.setBounds(310, 5, 60, 20);
add(temp);
temp = new JLabel("分数");
temp.setBounds(310, 105, 60, 20);
add(temp);
temp = new JLabel("速度");
temp.setBounds(310, 55, 60, 20);
add(temp);
speedLabel.setBounds(310, 75, 60, 20);
add(speedLabel);
}
private void newGame() {
this.remove(snakePanel);
this.remove(statusLabel);
this.remove(scoreLabel);
speedLabel.setText("Slow");
statusLabel = new JLabel();
scoreLabel = new JLabel();
snakePanel = new JPanel();
snake = new Snake();
snakePanel = new SnakePanel(snake);
snakePanel.setBounds(0, 0, 300, 400);
snakePanel.setBorder(BorderFactory.createLineBorder(Color.darkGray));
Runnable r1 = new SnakeRunnable(snake, snakePanel);
Runnable r2 = new StatusRunnable(snake, statusLabel, scoreLabel);
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
add(snakePanel);
statusLabel.setBounds(310, 25, 60, 20);
add(statusLabel);
scoreLabel.setBounds(310, 125, 60, 20);
add(scoreLabel);
}
}
java贪吃蛇代码注释求解
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
public class InterFace extends JFrame {
/**
* WIDTH:宽
* HEIGHT:高
* SLEEPTIME:可以看作蛇运动的速度
* L = 1,R = 2, U = 3, D = 4 左右上下代码
*/
public static final int WIDTH = 800, HEIGHT = 600, SLEEPTIME = 200, L = 1,R = 2, U = 3, D = 4;
BufferedImage offersetImage= new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_3BYTE_BGR);;
Rectangle rect = new Rectangle(20, 40, 15 * 50, 15 * 35);
Snake snake;
Node node;
public InterFace() {
//创建"蛇"对象
snake = new Snake(this);
//创建"食物"对象
createNode();
this.setBounds(100, 100, WIDTH, HEIGHT);
//添加键盘监听器
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent arg0) {
System.out.println(arg0.getKeyCode());
switch (arg0.getKeyCode()) {
//映射上下左右4个键位
case KeyEvent.VK_LEFT:
snake.dir = L;
break;
case KeyEvent.VK_RIGHT:
snake.dir = R;
break;
case KeyEvent.VK_UP:
snake.dir = U;
break;
case KeyEvent.VK_DOWN:
snake.dir = D;
}
}
});
this.setTitle("贪吃蛇 0.1 By : Easy");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
//启动线程,开始执行
new Thread(new ThreadUpadte()).start();
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) offersetImage.getGraphics();
g2d.setColor(Color.white);
g2d.fillRect(0, 0, WIDTH, HEIGHT);
g2d.setColor(Color.black);
g2d.drawRect(rect.x, rect.y, rect.width, rect.height);
//如果蛇碰撞(吃)到食物,则创建新食物
if (snake.hit(node)) {
createNode();
}
snake.draw(g2d);
node.draw(g2d);
g.drawImage(offersetImage, 0, 0, null);
}
class ThreadUpadte implements Runnable {
public void run() {
//无限重绘画面
while (true) {
try {
Thread.sleep(SLEEPTIME);
repaint(); //
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 创建食物
*/
public void createNode() {
//随机食物的出现位置
int x = (int) (Math.random() * 650) + 50,y = (int) (Math.random() * 500) + 50;
Color color = Color.blue;
node = new Node(x, y, color);
}
public static void main(String args[]) {
new InterFace();
}
}
/**
* 节点类(包括食物和蛇的身躯组成节点)
*/
class Node {
int x, y, width = 15, height = 15;
Color color;
public Node(int x, int y, Color color) {
this(x, y);
this.color = color;
}
public Node(int x, int y) {
this.x = x;
this.y = y;
this.color = color.black;
}
public void draw(Graphics2D g2d) {
g2d.setColor(color);
g2d.drawRect(x, y, width, height);
}
public Rectangle getRect() {
return new Rectangle(x, y, width, height);
}
}
/**
* 蛇
*/
class Snake {
public ListNode nodes = new ArrayListNode();
InterFace interFace;
int dir=InterFace.R;
public Snake(InterFace interFace) {
this.interFace = interFace;
nodes.add(new Node(20 + 150, 40 + 150));
addNode();
}
/**
* 是否碰撞到食物
* @return true 是 false 否
*/
public boolean hit(Node node) {
//遍历整个蛇体是否与食物碰撞
for (int i = 0; i nodes.size(); i++) {
if (nodes.get(i).getRect().intersects(node.getRect())) {
addNode();
return true;
}
}
return false;
}
public void draw(Graphics2D g2d) {
for (int i = 0; i nodes.size(); i++) {
nodes.get(i).draw(g2d);
}
move();
}
public void move() {
nodes.remove((nodes.size() - 1));
addNode();
}
public synchronized void addNode() {
Node nodeTempNode = nodes.get(0);
//如果方向
switch (dir) {
case InterFace.L:
//判断是否会撞墙
if (nodeTempNode.x = 20) {
nodeTempNode = new Node(20 + 15 * 50, nodeTempNode.y);
}
nodes.add(0, new Node(nodeTempNode.x - nodeTempNode.width,
nodeTempNode.y));
break;
case InterFace.R:
//判断是否会撞墙
if (nodeTempNode.x = 20 + 15 * 50 - nodeTempNode.width) {
nodeTempNode = new Node(20 - nodeTempNode.width, nodeTempNode.y);
}
nodes.add(0, new Node(nodeTempNode.x + nodeTempNode.width,
nodeTempNode.y));
break;
case InterFace.U:
//判断是否会撞墙
if (nodeTempNode.y = 40) {
nodeTempNode = new Node(nodeTempNode.x, 40 + 15 * 35);
}
nodes.add(0, new Node(nodeTempNode.x, nodeTempNode.y - nodeTempNode.height));
break;
case InterFace.D:
//判断是否会撞墙
if (nodeTempNode.y = 40 + 15 * 35 - nodeTempNode.height) {
nodeTempNode = new Node(nodeTempNode.x,40 - nodeTempNode.height);
}
nodes.add(0, new Node(nodeTempNode.x, nodeTempNode.y + nodeTempNode.height));
break;
}
}
}
java贪吃蛇的代码为什么无法运行?
Class里面必须有public static void main(String[] args)这么个method才能运行,如果有多于一个class的话你可能只是运行了不正确的class。
还有一种可能就是你的程序是个applet,那种情况下会有public class ... extends Applet。那样的话可以用textpad或eclipse来run java applet,或者在同一目录新建一个txt文件,在里面写上:
HTML
HEAD
TITLEsome title/TITLE
/HEAD
BODY
applet code="文件名.class" width=(宽度) height=(高度)
/applet
/BODY
/HTML
然后保存关掉把.txt改成.html再打开
求"贪吃蛇"小游戏JAVA源代码一份
贪吃蛇
import java.awt.*;
import java.awt.event.*;
public class GreedSnake //主类
{
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new MyWindow();
}
}
class MyPanel extends Panel implements KeyListener,Runnable//自定义面板类,继承了键盘和线程接口
{
Button snake[]; //定义蛇按钮
int shu=0; //蛇的节数
int food[]; //食物数组
boolean result=true; //判定结果是输 还是赢
Thread thread; //定义线程
static int weix,weiy; //食物位置
boolean t=true; //判定游戏是否结束
int fangxiang=0; //蛇移动方向
int x=0,y=0; //蛇头位置
MyPanel()
{
setLayout(null);
snake=new Button[20];
food=new int [20];
thread=new Thread(this);
for(int j=0;j20;j++)
{
food[j]=(int)(Math.random()*99);//定义20个随机食物
}
weix=(int)(food[0]*0.1)*60; //十位*60为横坐标
weiy=(int)(food[0]%10)*40; //个位*40为纵坐标
for(int i=0;i20;i++)
{
snake[i]=new Button();
}
add(snake[0]);
snake[0].setBackground(Color.black);
snake[0].addKeyListener(this); //为蛇头添加键盘监视器
snake[0].setBounds(0,0,10,10);
setBackground(Color.cyan);
}
public void run() //接收线程
{
while(t)
{
if(fangxiang==0)//向右
{
try
{
x+=10;
snake[0].setLocation(x, y);//设置蛇头位置
if(x==weixy==weiy) //吃到食物
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint(); //重绘下一个食物
add(snake[shu]); //增加蛇节数和位置
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100); //睡眠100ms
}
catch(Exception e){}
}
else if(fangxiang==1)//向左
{
try
{
x-=10;
snake[0].setLocation(x, y);
if(x==weixy==weiy)
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint();
add(snake[shu]);
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100);
}
catch(Exception e){}
}
else if(fangxiang==2)//向上
{
try
{
y-=10;
snake[0].setLocation(x, y);
if(x==weixy==weiy)
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint();
add(snake[shu]);
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100);
}
catch(Exception e){}
}
else if(fangxiang==3)//向下
{
try
{
y+=10;
snake[0].setLocation(x, y);
if(x==weixy==weiy)
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint();
add(snake[shu]);
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100);
}
catch(Exception e){}
}
int num1=shu;
while(num11)//判断是否咬自己的尾巴
{
if(snake[num1].getBounds().x==snake[0].getBounds().xsnake[num1].getBounds().y==snake[0].getBounds().y)
{
t=false;
result=false;
repaint();
}
num1--;
}
if(x0||x=this.getWidth()||y0||y=this.getHeight())//判断是否撞墙
{
t=false;
result=false;
repaint();
}
int num=shu;
while(num0) //设置蛇节位置
{
snake[num].setBounds(snake[num-1].getBounds());
num--;
}
if(shu==15) //如果蛇节数等于15则胜利
{
t=false;
result=true;
repaint();
}
}
}
public void keyPressed(KeyEvent e) //按下键盘方向键
{
if(e.getKeyCode()==KeyEvent.VK_RIGHT)//右键
{
if(fangxiang!=1)//如果先前方向不为左
fangxiang=0;
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT)
{ if(fangxiang!=0)
fangxiang=1;
}
else if(e.getKeyCode()==KeyEvent.VK_UP)
{ if(fangxiang!=3)
fangxiang=2;
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{ if(fangxiang!=2)
fangxiang=3;
}
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void paint(Graphics g) //在面板上绘图
{
int x1=this.getWidth()-1;
int y1=this.getHeight()-1;
g.setColor(Color.red);
g.fillOval(weix, weiy, 10, 10);//食物
g.drawRect(0, 0, x1, y1); //墙
if(t==falseresult==false)
g.drawString("GAME OVER!", 250, 200);//输出游戏失败
else if(t==falseresult==true)
g.drawString("YOU WIN!", 250, 200);//输出游戏成功
}
}
class MyWindow extends Frame implements ActionListener//自定义窗口类
{
MyPanel my;
Button btn;
Panel panel;
MyWindow()
{
super("GreedSnake");
my=new MyPanel();
btn=new Button("begin");
panel=new Panel();
btn.addActionListener(this);
panel.add(new Label("begin后请按Tab键选定蛇"));
panel.add(btn);
panel.add(new Label("按上下左右键控制蛇行动"));
add(panel,BorderLayout.NORTH);
add(my,BorderLayout.CENTER);
setBounds(100,100,610,500);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)//按下begin按钮
{
if(e.getSource()==btn)
{
try
{
my.thread.start(); //开始线程
my.validate();
}
catch(Exception ee){}
}
}
}
想要一个在eclipse上直接运行的贪吃蛇代码
第一个类:
/**
* 代表蛇的运行方向
* @author Administrator
*
*/
public enum Dir {
L, U, R, D
}
第二个类:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;
/**
* 代表蛋
* @author Administrator
*
*/
public class Egg {
int row, col;
int w = Yard.BLOCK_SIZE;
int h = Yard.BLOCK_SIZE;
private static Random r = new Random();
private Color color = Color.GREEN;
public Egg(int row, int col) {
this.row = row;
this.col = col;
}
public Egg() {
this(r.nextInt(Yard.ROWS-2) + 2, r.nextInt(Yard.COLS));
}
public void reAppear() {
this.row = r.nextInt(Yard.ROWS-2) + 2;
this.col = r.nextInt(Yard.COLS);
}
public Rectangle getRect() {
return new Rectangle(Yard.BLOCK_SIZE * col, Yard.BLOCK_SIZE * row, w, h);
}
public void draw(Graphics g) {
Color c = g.getColor();
g.setColor(color);
g.fillOval(Yard.BLOCK_SIZE * col, Yard.BLOCK_SIZE * row, w, h);
g.setColor(c);
if(color == Color.GREEN) color = Color.RED;
else color = Color.GREEN;
}
public int getCol() {
return col;
}
public void setCol(int col) {
this.col = col;
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
}
第三个类:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
/**
* 代表蛇
* @author Administrator
*
*/
public class Snake {
private Node head = null;
private Node tail = null;
private int size = 0;
private Node n = new Node(20, 30, Dir.L);
private Yard y;
public Snake(Yard y) {
head = n;
tail = n;
size = 1;
this.y = y;
}
public void addToTail() {
Node node = null;
switch(tail.dir) {
case L :
node = new Node(tail.row, tail.col + 1, tail.dir);
break;
case U :
node = new Node(tail.row + 1, tail.col, tail.dir);
break;
case R :
node = new Node(tail.row, tail.col - 1, tail.dir);
break;
case D :
node = new Node(tail.row - 1, tail.col, tail.dir);
break;
}
tail.next = node;
node.prev = tail;
tail = node;
size ++;
}
public void addToHead() {
Node node = null;
switch(head.dir) {
case L :
node = new Node(head.row, head.col - 1, head.dir);
break;
case U :
node = new Node(head.row - 1, head.col, head.dir);
break;
case R :
node = new Node(head.row, head.col + 1, head.dir);
break;
case D :
node = new Node(head.row + 1, head.col, head.dir);
break;
}
node.next = head;
head.prev = node;
head = node;
size ++;
}
public void draw(Graphics g) {
if(size = 0) return;
move();
for(Node n = head; n != null; n = n.next) {
n.draw(g);
}
}
private void move() {
addToHead();
deleteFromTail();
checkDead();
}
private void checkDead() {
if(head.row 2 || head.col 0 || head.row Yard.ROWS || head.col Yard.COLS) {
y.stop();
}
for(Node n = head.next; n != null; n = n.next) {
if(head.row == n.row head.col == n.col) {
y.stop();
}
}
}
private void deleteFromTail() {
if(size == 0) return;
tail = tail.prev;
tail.next = null;
}
private class Node {
int w = Yard.BLOCK_SIZE;
int h = Yard.BLOCK_SIZE;
int row , col;
Dir dir = Dir.L;
Node next = null;
Node prev = null;
Node(int row, int col, Dir dir) {
this.row = row;
this.col = col;
this.dir = dir;
}
void draw(Graphics g) {
Color c = g.getColor();
g.setColor(Color.BLACK);
g.fillRect(Yard.BLOCK_SIZE * col, Yard.BLOCK_SIZE * row, w, h);
g.setColor(c);
}
}
public void eat(Egg e) {
if(this.getRect().intersects(e.getRect())) {
e.reAppear();
this.addToHead();
y.setScore(y.getScore() + 5);
}
}
private Rectangle getRect() {
return new Rectangle(Yard.BLOCK_SIZE * head.col, Yard.BLOCK_SIZE * head.row, head.w, head.h);
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
switch(key) {
case KeyEvent.VK_LEFT :
if(head.dir != Dir.R)
head.dir = Dir.L;
break;
case KeyEvent.VK_UP :
if(head.dir != Dir.D)
head.dir = Dir.U;
break;
case KeyEvent.VK_RIGHT :
if(head.dir != Dir.L)
head.dir = Dir.R;
break;
case KeyEvent.VK_DOWN :
if(head.dir != Dir.U)
head.dir = Dir.D;
break;
}
}
}
第四个类:
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.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* 这个类代表贪吃蛇的活动场所
* @author bjsxt
* @version 1.0
*/
public class Yard extends Frame {
PaintThread paintThread = new PaintThread();
private boolean gameOver = false; //游戏是否结束
/**
* 行数
*/
public static final int ROWS = 30;
public static final int COLS = 30;
public static final int BLOCK_SIZE = 15;
private Font fontGameOver = new Font("宋体", Font.BOLD, 50);
private int score = 0;
Snake s = new Snake(this);
Egg e = new Egg();
Image offScreenImage = null;
public void launch() {
this.setLocation(200, 200);
this.setSize(COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.setVisible(true);
this.addKeyListener(new KeyMonitor());
new Thread(paintThread).start();
}
public static void main(String[] args) {
new Yard().launch();
}
public void stop() {
gameOver = true;
}
@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=1; iROWS; i++) {
g.drawLine(0, BLOCK_SIZE * i, COLS * BLOCK_SIZE, BLOCK_SIZE * i);
}
for(int i=1; iCOLS; i++) {
g.drawLine(BLOCK_SIZE * i, 0, BLOCK_SIZE * i, BLOCK_SIZE * ROWS);
}
g.setColor(Color.YELLOW);
g.drawString("score:" + score, 10, 60);
if(gameOver) {
g.setFont(fontGameOver);
g.drawString("游戏结束", 120, 180);
paintThread.pause();
}
g.setColor(c);
s.eat(e);
e.draw(g);
s.draw(g);
}
@Override
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);
}
private class PaintThread implements Runnable {
private boolean running = true;
private boolean pause = false;
public void run() {
while(running) {
if(pause) continue;
else repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void pause() {
this.pause = true;
}
public void reStart() {
this.pause = false;
s = new Snake(Yard.this);
gameOver = false;
}
public void gameOver() {
running = false;
}
}
private class KeyMonitor extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_F2) {
paintThread.reStart();
}
s.keyPressed(e);
}
}
/**
* 拿到所得的分数
* @return 分数
*/
public int getScore() {
return score;
}
/**
* 设置所得的分数
* @param score 分数
*/
public void setScore(int score) {
this.score = score;
}
}
仅供参考。