求《贪食蛇》源代码 (Java编写的)
1个回答
2013-06-30
展开全部
建三个类,放在同一个包里,三个类如下:第一个:public class Node {
int x=0;
int y=0;
int nodewidth;
int nodeheight;
Node(int x,int y){
this.x=x;
this.y=y;
}
}第二个:import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;public class GreedSnake implements KeyListener{
Canvas canvas;
private JLabel jlabel;
private JPanel jpanel;
private JFrame jframe;
SnakeModel snakemodel;
private final static int canvaswidth=400;
private final static int canvasheight=300;
private final static int nodewidth=10;
private final static int nodeheight=10;
//construction
GreedSnake(){
jframe=new JFrame("The Greed Sanke!");
jframe.setLayout(new BorderLayout());
Container cp=jframe.getContentPane();
jlabel=new JLabel("welcome");
jlabel.setText("Welcome my friend! Enjoy your self!");
cp.add(jlabel,BorderLayout.NORTH);
canvas=new Canvas();
canvas.setSize(canvaswidth,canvasheight);
canvas.addKeyListener(this); cp.add(canvas,BorderLayout.CENTER);
jpanel=new JPanel();
jpanel.setLayout(new BorderLayout());
JLabel label=new JLabel("Pass enter or 'r' or 's' to start",JLabel.CENTER);
jpanel.add(label,BorderLayout.NORTH);
JLabel label2=new JLabel("Pass space to pause this game!",JLabel.CENTER);
jpanel.add(label2,BorderLayout.CENTER);
JLabel label3=new JLabel("Pass pageUp or pageDown to up or down the speed of the snake!",JLabel.CENTER);
jpanel.add(label3,BorderLayout.SOUTH);
cp.add(jpanel,BorderLayout.SOUTH);
jframe.addKeyListener(this);
jframe.pack();
jframe.setVisible(true);
jframe.setResizable(false);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
begin();
}//end construction
public void begin(){
snakemodel=new SnakeModel(this,canvaswidth/nodewidth,canvasheight/nodeheight);
(new Thread(snakemodel)).start();
}
void repaint(){
int score=snakemodel.getScore();
jlabel.setText("您的得分是:"+score);
Graphics g=canvas.getGraphics();///pay attention!
g.setColor(Color.white);
g.fillRect(0, 0, canvaswidth, canvasheight);
g.setColor(Color.blue);
LinkedList list=snakemodel.nodeArray;
for(int i=0;i<list.size();i++){
Node nn=(Node)list.get(i);
paintingNode(g,nn);
}
g.setColor(Color.green);
Node foodnode=new Node(snakemodel.food.x,snakemodel.food.y);
paintingNode(g,foodnode);
} public void paintingNode(Graphics gg,Node n){
gg.fillRect(n.x*nodewidth, n.y*nodeheight,nodewidth-1,nodeheight-1);
}
public void keyPressed(KeyEvent e) { int keycode=e.getKeyCode();
/* if(keycode==KeyEvent.VK_ENTER||keycode==KeyEvent.VK_R){
begin();
}*/
switch(keycode){
case KeyEvent.VK_LEFT:
snakemodel.chageDirection(SnakeModel.LEFT);
break;
case KeyEvent.VK_UP:
snakemodel.chageDirection(SnakeModel.UP);
break;
case KeyEvent.VK_RIGHT:
snakemodel.chageDirection(SnakeModel.RIGHT);
break;
case KeyEvent.VK_DOWN:
snakemodel.chageDirection(SnakeModel.DOWN);
break;
case KeyEvent.VK_PAGE_DOWN:
snakemodel.speedDown();
break;
case KeyEvent.VK_PAGE_UP:
snakemodel.speedUp();
break;
case KeyEvent.VK_ENTER:
case KeyEvent.VK_R:
begin();
break;
case KeyEvent.VK_SPACE:
case KeyEvent.VK_P:
snakemodel.chagePause();
default:
}//end switch
}//end keyPressed public void keyReleased(KeyEvent e) {/ } public void keyTyped(KeyEvent e)
}
public static void main(String[] args){
GreedSnake gs=new GreedSnake();
}
} 第三个:import java.util.*;import javax.swing.*;public class SnakeModel implements Runnable {
private GreedSnake gs;
//给每一个矩阵点确立一个boolean值
boolean[][] matrix;
private int maxX;
private int maxY;
//设置一个节点的列表;
LinkedList nodeArray = new LinkedList();
Node food=null;
int direction=UP;
int score=0;
//定义方向
public final static int LEFT=1;
public final static int UP=2;
public final static int RIGHT=3;
public final static int DOWN=4;
private int interval=200; //停顿时间的间隔
boolean pause=false; //定义暂停
private double speedRate=0.5; //定义速度的变更幅度
//constructor
public SnakeModel(GreedSnake gs,int maxx,int maxy){
this.gs=gs;
this.maxX=maxx;
this.maxY=maxy;
//this.matrix=null;
////////////////////////////////////////////////////////////////////
//init matrix[][];
matrix=new boolean[maxX][]; //***********************不初始化是不行滴
for(int i=0;i<maxX;i++){
matrix[i]=new boolean[maxY];//将矩阵的每一行定义成列的集合
Arrays.fill(matrix[i], false);///使用java.util.Arrays的static方法fill,将matrix[]数组里面的元素全部定义成false
//至此,矩阵里面所有的点的boolean值都是flase
//for(int j=0;j<maxY;j++){
//matrix[i][j]=false;
//}
}
////////////////////////////////////////////////////////////////////
//init nodeArray
int initlength=10;
for(int i=0;i<initlength;i++){
//确保snake出现在屏幕的中央 assure that the greedy snake appears in the center of the model
//snake的长度由maxX来确定
int x=maxX/2+i;
int y=maxY/2;
nodeArray.addFirst(new Node(x,y));
matrix[x][y]=true;
}
//////////////////////////////////////////////////////////////////////
//创建食物
food=createFood();
System.out.println("some test!");
matrix[food.x][food.y]=true;
}//end constructor
//snake动起
public boolean moveOn(){
Node head=(Node)nodeArray.getFirst();
int x=head.x;
int y=head.y;
switch(direction){
case LEFT:
x--;break;
case UP:
y--;break;
case RIGHT:
x++;break;
case DOWN:
y++;break;
default:
}
if((x >= 0 && x < maxX) && (y >= 0 && y < maxY)){
if(matrix[x][y]){//当蛇头转至一个bool值为true的点时
if(x==food.x&&y==food.y){//该点是食物
nodeArray.addFirst(food);
//吃掉补上
food=createFood();
matrix[food.x][food.y]=true;
score+=10;
return true;
}
else //该点不是食物,(蛇尾巴)
return false;
}
else{
nodeArray.addFirst(new Node(x,y));
matrix[x][y]=true;
Node nn=(Node)nodeArray.removeLast();//移除并且返回列表中的最后一个元素
matrix[nn.x][nn.y]=false;
return true;
}
}
return false;
}//end moveOn
public void run() {
boolean running=true;
while(running){
try{
Thread.sleep(interval);
}
catch(InterruptedException e){
e.printStackTrace();
}
if(!pause){
if(moveOn()){
gs.repaint();
}
else{
JOptionPane.showMessageDialog(null, "sorry myboy,GAME OVER!", "message", JOptionPane.INFORMATION_MESSAGE);
running=false;
}
}
}
/*boolean running=true;
while(running){
try{
Thread.sleep(interval);
}
catch (InterruptedException e){
e.printStackTrace();
}
if(!pause){
if(moveOn()){
gs.repaint();
}
else{
JOptionPane.showMessageDialog(null,"i am sorry ,you failed!","message",JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}//end while
running=false;//当且仅当失败退出的时候;
*/
}
//获取当前游戏得分
public int getScore(){
return this.score;
}
//加速
public void speedUp(){
interval*=speedRate;
}
//减速
public void speedDown(){
interval/=speedRate;
}
//设置暂停
public void chagePause(){
pause=!pause;
}
//设置方向
public void chageDirection(int newdirection){
if(direction % 2 != newdirection % 2){
direction=newdirection;
}
}
//生成食物
private Node createFood() {
/*
* 创建一个随机数的生成器,这个是java.util.Random类
* 与java.lang.Math类中的random()方法有不一样的地方,彼方法返回一个0-1之间的随机数
* */
Random random=new Random();
int foodx=random.nextInt(maxX);
int foody=random.nextInt(maxY);
Node food=new Node(foodx,foody);
return food;
}}
效果如下: 声明:这个不是本人做的,只是为了帮助你,谢谢。
int x=0;
int y=0;
int nodewidth;
int nodeheight;
Node(int x,int y){
this.x=x;
this.y=y;
}
}第二个:import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;public class GreedSnake implements KeyListener{
Canvas canvas;
private JLabel jlabel;
private JPanel jpanel;
private JFrame jframe;
SnakeModel snakemodel;
private final static int canvaswidth=400;
private final static int canvasheight=300;
private final static int nodewidth=10;
private final static int nodeheight=10;
//construction
GreedSnake(){
jframe=new JFrame("The Greed Sanke!");
jframe.setLayout(new BorderLayout());
Container cp=jframe.getContentPane();
jlabel=new JLabel("welcome");
jlabel.setText("Welcome my friend! Enjoy your self!");
cp.add(jlabel,BorderLayout.NORTH);
canvas=new Canvas();
canvas.setSize(canvaswidth,canvasheight);
canvas.addKeyListener(this); cp.add(canvas,BorderLayout.CENTER);
jpanel=new JPanel();
jpanel.setLayout(new BorderLayout());
JLabel label=new JLabel("Pass enter or 'r' or 's' to start",JLabel.CENTER);
jpanel.add(label,BorderLayout.NORTH);
JLabel label2=new JLabel("Pass space to pause this game!",JLabel.CENTER);
jpanel.add(label2,BorderLayout.CENTER);
JLabel label3=new JLabel("Pass pageUp or pageDown to up or down the speed of the snake!",JLabel.CENTER);
jpanel.add(label3,BorderLayout.SOUTH);
cp.add(jpanel,BorderLayout.SOUTH);
jframe.addKeyListener(this);
jframe.pack();
jframe.setVisible(true);
jframe.setResizable(false);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
begin();
}//end construction
public void begin(){
snakemodel=new SnakeModel(this,canvaswidth/nodewidth,canvasheight/nodeheight);
(new Thread(snakemodel)).start();
}
void repaint(){
int score=snakemodel.getScore();
jlabel.setText("您的得分是:"+score);
Graphics g=canvas.getGraphics();///pay attention!
g.setColor(Color.white);
g.fillRect(0, 0, canvaswidth, canvasheight);
g.setColor(Color.blue);
LinkedList list=snakemodel.nodeArray;
for(int i=0;i<list.size();i++){
Node nn=(Node)list.get(i);
paintingNode(g,nn);
}
g.setColor(Color.green);
Node foodnode=new Node(snakemodel.food.x,snakemodel.food.y);
paintingNode(g,foodnode);
} public void paintingNode(Graphics gg,Node n){
gg.fillRect(n.x*nodewidth, n.y*nodeheight,nodewidth-1,nodeheight-1);
}
public void keyPressed(KeyEvent e) { int keycode=e.getKeyCode();
/* if(keycode==KeyEvent.VK_ENTER||keycode==KeyEvent.VK_R){
begin();
}*/
switch(keycode){
case KeyEvent.VK_LEFT:
snakemodel.chageDirection(SnakeModel.LEFT);
break;
case KeyEvent.VK_UP:
snakemodel.chageDirection(SnakeModel.UP);
break;
case KeyEvent.VK_RIGHT:
snakemodel.chageDirection(SnakeModel.RIGHT);
break;
case KeyEvent.VK_DOWN:
snakemodel.chageDirection(SnakeModel.DOWN);
break;
case KeyEvent.VK_PAGE_DOWN:
snakemodel.speedDown();
break;
case KeyEvent.VK_PAGE_UP:
snakemodel.speedUp();
break;
case KeyEvent.VK_ENTER:
case KeyEvent.VK_R:
begin();
break;
case KeyEvent.VK_SPACE:
case KeyEvent.VK_P:
snakemodel.chagePause();
default:
}//end switch
}//end keyPressed public void keyReleased(KeyEvent e) {/ } public void keyTyped(KeyEvent e)
}
public static void main(String[] args){
GreedSnake gs=new GreedSnake();
}
} 第三个:import java.util.*;import javax.swing.*;public class SnakeModel implements Runnable {
private GreedSnake gs;
//给每一个矩阵点确立一个boolean值
boolean[][] matrix;
private int maxX;
private int maxY;
//设置一个节点的列表;
LinkedList nodeArray = new LinkedList();
Node food=null;
int direction=UP;
int score=0;
//定义方向
public final static int LEFT=1;
public final static int UP=2;
public final static int RIGHT=3;
public final static int DOWN=4;
private int interval=200; //停顿时间的间隔
boolean pause=false; //定义暂停
private double speedRate=0.5; //定义速度的变更幅度
//constructor
public SnakeModel(GreedSnake gs,int maxx,int maxy){
this.gs=gs;
this.maxX=maxx;
this.maxY=maxy;
//this.matrix=null;
////////////////////////////////////////////////////////////////////
//init matrix[][];
matrix=new boolean[maxX][]; //***********************不初始化是不行滴
for(int i=0;i<maxX;i++){
matrix[i]=new boolean[maxY];//将矩阵的每一行定义成列的集合
Arrays.fill(matrix[i], false);///使用java.util.Arrays的static方法fill,将matrix[]数组里面的元素全部定义成false
//至此,矩阵里面所有的点的boolean值都是flase
//for(int j=0;j<maxY;j++){
//matrix[i][j]=false;
//}
}
////////////////////////////////////////////////////////////////////
//init nodeArray
int initlength=10;
for(int i=0;i<initlength;i++){
//确保snake出现在屏幕的中央 assure that the greedy snake appears in the center of the model
//snake的长度由maxX来确定
int x=maxX/2+i;
int y=maxY/2;
nodeArray.addFirst(new Node(x,y));
matrix[x][y]=true;
}
//////////////////////////////////////////////////////////////////////
//创建食物
food=createFood();
System.out.println("some test!");
matrix[food.x][food.y]=true;
}//end constructor
//snake动起
public boolean moveOn(){
Node head=(Node)nodeArray.getFirst();
int x=head.x;
int y=head.y;
switch(direction){
case LEFT:
x--;break;
case UP:
y--;break;
case RIGHT:
x++;break;
case DOWN:
y++;break;
default:
}
if((x >= 0 && x < maxX) && (y >= 0 && y < maxY)){
if(matrix[x][y]){//当蛇头转至一个bool值为true的点时
if(x==food.x&&y==food.y){//该点是食物
nodeArray.addFirst(food);
//吃掉补上
food=createFood();
matrix[food.x][food.y]=true;
score+=10;
return true;
}
else //该点不是食物,(蛇尾巴)
return false;
}
else{
nodeArray.addFirst(new Node(x,y));
matrix[x][y]=true;
Node nn=(Node)nodeArray.removeLast();//移除并且返回列表中的最后一个元素
matrix[nn.x][nn.y]=false;
return true;
}
}
return false;
}//end moveOn
public void run() {
boolean running=true;
while(running){
try{
Thread.sleep(interval);
}
catch(InterruptedException e){
e.printStackTrace();
}
if(!pause){
if(moveOn()){
gs.repaint();
}
else{
JOptionPane.showMessageDialog(null, "sorry myboy,GAME OVER!", "message", JOptionPane.INFORMATION_MESSAGE);
running=false;
}
}
}
/*boolean running=true;
while(running){
try{
Thread.sleep(interval);
}
catch (InterruptedException e){
e.printStackTrace();
}
if(!pause){
if(moveOn()){
gs.repaint();
}
else{
JOptionPane.showMessageDialog(null,"i am sorry ,you failed!","message",JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}//end while
running=false;//当且仅当失败退出的时候;
*/
}
//获取当前游戏得分
public int getScore(){
return this.score;
}
//加速
public void speedUp(){
interval*=speedRate;
}
//减速
public void speedDown(){
interval/=speedRate;
}
//设置暂停
public void chagePause(){
pause=!pause;
}
//设置方向
public void chageDirection(int newdirection){
if(direction % 2 != newdirection % 2){
direction=newdirection;
}
}
//生成食物
private Node createFood() {
/*
* 创建一个随机数的生成器,这个是java.util.Random类
* 与java.lang.Math类中的random()方法有不一样的地方,彼方法返回一个0-1之间的随机数
* */
Random random=new Random();
int foodx=random.nextInt(maxX);
int foody=random.nextInt(maxY);
Node food=new Node(foodx,foody);
return food;
}}
效果如下: 声明:这个不是本人做的,只是为了帮助你,谢谢。
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询