J2ME貪吃蛇源代碼——200行左右,包含詳細注釋 package snake;import javax.microedition.midlet.*;
主要從事網頁設計、PC網站建設(電腦版網站建設)、wap網站建設(手機版網站建設)、自適應網站建設、程序開發(fā)、微網站、小程序開發(fā)等,憑借多年來在互聯網的打拼,我們在互聯網網站建設行業(yè)積累了豐富的網站設計、成都做網站、網絡營銷經驗,集策劃、開發(fā)、設計、營銷、管理等多方位專業(yè)化運作于一體,具備承接不同規(guī)模與類型的建設項目的能力。
import javax.microedition.lcdui.*;public class SnakeMIDlet extends MIDlet {
SnakeCanvas displayable = new SnakeCanvas();
public SnakeMIDlet() {
Display.getDisplay(this).setCurrent(displayable);
}public void startApp() {}public void pauseApp() {}public void destroyApp(boolean unconditional) {}}//文件名:SnakeCanvas.javapackage snake;import java.util.*;
import javax.microedition.lcdui.*;/**
* 貪吃蛇游戲
*/
public class SnakeCanvas extends Canvas implements Runnable{
/**存儲貪吃蛇節(jié)點坐標,其中第二維下標為0的代表x坐標,第二維下標是1的代表y坐標*/
int[][] snake = new int[200][2];
/**已經使用的節(jié)點數量*/
int snakeNum;
/**貪吃蛇運動方向,0代表向上,1代表向下,2代表向左,3代表向右*/
int direction;
/*移動方向*/
/**向上*/
private final int DIRECTION_UP = 0;
/**向下*/
private final int DIRECTION_DOWN = 1;
/**向左*/
private final int DIRECTION_LEFT = 2;
/**向右*/
private final int DIRECTION_RIGHT = 3;/**游戲區(qū)域寬度*/
int width;
/**游戲區(qū)域高度*/
int height;/**蛇身單元寬度*/
private final byte SNAKEWIDTH = 4;/**是否處于暫停狀態(tài),true代表暫停*/
boolean isPaused = false;
/**是否處于運行狀態(tài),true代表運行*/
boolean isRun = true;/**時間間隔*/
private final int SLEEP_TIME = 300;
/**食物的X坐標*/
int foodX;
/**食物的Y坐標*/
int foodY;
/**食物的閃爍控制*/
boolean b = true;
/**Random對象*/
Random random = new Random();
public SnakeCanvas() {
//初始化
init();
width = this.getWidth();
height = this.getHeight();
//啟動線程
new Thread(this).start();
}/**
* 初始化開始數據
*/
private void init(){
//初始化節(jié)點數量
snakeNum = 7;
//初始化節(jié)點數據
for(int i = 0;i snakeNum;i++){
snake[i][0] = 100 - SNAKEWIDTH * i;
snake[i][1] = 40;
}
//初始化移動方向
direction = DIRECTION_RIGHT;
//初始化食物坐標
foodX = 100;
foodY = 100;
}protected void paint(Graphics g) {
//清屏
g.setColor(0xffffff);
g.fillRect(0,0,width,height);
g.setColor(0);//繪制蛇身
for(int i = 0;i snakeNum;i++){
g.fillRect(snake[i][0],snake[i][1],SNAKEWIDTH,SNAKEWIDTH);
}
//繪制食物
if(b){
g.fillRect(foodX,foodY,SNAKEWIDTH,SNAKEWIDTH);
}
}private void move(int direction){
//蛇身移動
for(int i = snakeNum - 1;i 0;i--){
snake[i][0] = snake[i - 1][0];
snake[i][1] = snake[i - 1][1];
}//第一個單元格移動
switch(direction){
case DIRECTION_UP:
snake[0][1] = snake[0][1] - SNAKEWIDTH;
break;
case DIRECTION_DOWN:
snake[0][1] = snake[0][1] + SNAKEWIDTH;
break;
case DIRECTION_LEFT:
snake[0][0] = snake[0][0] - SNAKEWIDTH;
break;
case DIRECTION_RIGHT:
snake[0][0] = snake[0][0] + SNAKEWIDTH;
break;
}
}
/**
* 吃掉食物,自身增長
*/
private void eatFood(){
//判別蛇頭是否和食物重疊
if(snake[0][0] == foodX snake[0][1] == foodY){
snakeNum++;
generateFood();
}
}
/**
* 產生食物
* 說明:食物的坐標必須位于屏幕內,且不能和蛇身重合
*/
private void generateFood(){
while(true){
foodX = Math.abs(random.nextInt() % (width - SNAKEWIDTH + 1))
/ SNAKEWIDTH * SNAKEWIDTH;
foodY = Math.abs(random.nextInt() % (height - SNAKEWIDTH + 1))
/ SNAKEWIDTH * SNAKEWIDTH;
boolean b = true;
for(int i = 0;i snakeNum;i++){
if(foodX == snake[i][0] snake[i][1] == foodY){
b = false;
break;
}
}
if(b){
break;
}
}
}
/**
* 判斷游戲是否結束
* 結束條件:
* 1、蛇頭超出邊界
* 2、蛇頭碰到自身
*/
private boolean isGameOver(){
//邊界判別
if(snake[0][0] 0 || snake[0][0] (width - SNAKEWIDTH) ||
snake[0][1] 0 || snake[0][1] (height - SNAKEWIDTH)){
return true;
}
//碰到自身
for(int i = 4;i snakeNum;i++){
if(snake[0][0] == snake[i][0]
snake[0][1] == snake[i][1]){
return true;
}
}
return false;
}/**
* 事件處理
*/
public void keyPressed(int keyCode){
int action = this.getGameAction(keyCode);
//改變方向
switch(action){
case UP:
if(direction != DIRECTION_DOWN){
direction = DIRECTION_UP;
}
break;
case DOWN:
if(direction != DIRECTION_UP){
direction = DIRECTION_DOWN;
}
break;
case LEFT:
if(direction != DIRECTION_RIGHT){
direction = DIRECTION_LEFT;
}
break;
case RIGHT:
if(direction != DIRECTION_LEFT){
direction = DIRECTION_RIGHT;
}
break;
case FIRE:
//暫停和繼續(xù)
isPaused = !isPaused;
break;
}
}/**
* 線程方法
* 使用精確延時
*/
public void run(){
try{
while (isRun) {
//開始時間
long start = System.currentTimeMillis();
if(!isPaused){
//吃食物
eatFood();
//移動
move(direction);
//結束游戲
if(isGameOver()){
break;
}
//控制閃爍
b = !b;
}
//重新繪制
repaint();
long end = System.currentTimeMillis();
//延時
if(end - start SLEEP_TIME){
Thread.sleep(SLEEP_TIME - (end - start));
}
}
}catch(Exception e){}
}
}
貪吃蛇
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; //蛇的節(jié)數
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); //為蛇頭添加鍵盤監(jiān)視器
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]); //增加蛇節(jié)數和位置
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) //設置蛇節(jié)位置
{
snake[num].setBounds(snake[num-1].getBounds());
num--;
}
if(shu==15) //如果蛇節(jié)數等于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){}
}
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class SnakeGame extends JFrame implements KeyListener{
private int stat=1,direction=0,bodylen=6,headx=7,heady=8,
tailx=1,taily=8,tail,foodx,foody,food;//初始化定義變量
public final int EAST=1,WEST=2,SOUTH=3,NORTH=4;//方向常量
int [][] fillblock=new int [20][20];//定義蛇身所占位置
public SnakeGame() {//構造函數
super("貪吃蛇");
setSize(510,510);
setVisible(true);//設定窗口屬性
addKeyListener(this);//添加監(jiān)聽
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for(int i=1;i=7;i++) fillblock[i][8]=EAST;//初始化蛇身屬性
direction=EAST;//方向初始化的設置
FoodLocate(); //定位食物
while (stat==1){
fillblock[headx][heady]=direction;
switch(direction){
case 1:headx++;break;
case 2:headx--;break;
case 3:heady++;break;
case 4:heady--;break;
}//蛇頭的前進
if(heady19||headx19||tailx19||taily19||heady0||headx0||tailx0||taily0||fillblock[headx][heady]!=0){
stat=0;
break;
} //判斷游戲是否結束
try{
Thread.sleep(150); }
catch(InterruptedException e){}//延遲
fillblock[headx][heady]=direction;
if(headx==foodxheady==foody){//吃到食物
FoodLocate();
food=2;
try{
Thread.sleep(100); }
catch(InterruptedException e){}//延遲
}
if(food!=0)food--;
else{tail=fillblock[tailx][taily];
fillblock[tailx][taily]=0;//蛇尾的消除
switch(tail){
case 1:tailx++;break;
case 2:tailx--;break;
case 3:taily++;break;
case 4:taily--;break;
}//蛇尾的前進
}
repaint();
}
if(stat==0)
JOptionPane.showMessageDialog(null,"GAME OVER","Game Over",JOptionPane.INFORMATION_MESSAGE);
}
public void keyPressed(KeyEvent e) {//按鍵響應
int keyCode=e.getKeyCode();
if(stat==1) switch(keyCode){
case KeyEvent.VK_UP:if(direction!=SOUTH) direction=NORTH;break;
case KeyEvent.VK_DOWN:if(direction!=NORTH)direction=SOUTH;break;
case KeyEvent.VK_LEFT:if(direction!=EAST)direction=WEST;break;
case KeyEvent.VK_RIGHT:if (direction!=WEST)direction=EAST;break;
}
}
public void keyReleased(KeyEvent e){}//空函數
public void keyTyped(KeyEvent e){} //空函數
public void FoodLocate(){//定位食物坐標
do{
Random r=new Random();
foodx=r.nextInt(20);
foody=r.nextInt(20);
}while (fillblock[foodx][foody]!=0);
}
public void paint(Graphics g){//畫圖
super.paint(g);
g.setColor(Color.BLUE);
for(int i=0;i20;i++)
for(int j=0;j20;j++)
if (fillblock[i][j]!=0)
g.fillRect(25*i+5,25*j+5,24,24);
g.setColor(Color.RED);
g.fillRect(foodx*25+5,foody*25+5,24,24);
}
public static void main(String[] args) {//主程序
SnakeGame application=new SnakeGame();
}
}