当前位置: 代码迷 >> Java相关 >> 小弟我这有一段java实现贪吃蛇的代码 希望可以改进!
  详细解决方案

小弟我这有一段java实现贪吃蛇的代码 希望可以改进!

热度:1962   发布时间:2013-02-25 21:46:04.0
我这有一段java实现贪吃蛇的代码 希望可以改进!!!急~~
color=#FF0000]代码实现的功能不变 添加一个选择界面 在游戏运行之前 选择内容就是游戏等级 只有选择完之后 才能进入游戏界面 游戏界面里面的等级功能 可以去掉 也可以不去掉 [/color]import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
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;//---------是否运动中
 ArrayList<Node> 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.LOW;
  score = 0;
  isRun = false;
  status = Snake.RUNNING;
  derection = Snake.RIGHT;
  body = new ArrayList<Node>();
  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;
  相关解决方案