/**************************************************************************
*關鍵點分析:
*1)主體部分已經集成為壹個object SnakeModel,操作通過鍵盤控制實現。
*************************************************************************/
導入Java . awt . *;
導入Java . awt . event . *;
導入javax . swing . *;
導入Java . util . *;
//=============================================
//主類
//=============================================
公共類GreedSnake實現KeyListener
{
JFrame主機;
畫布paintCanvas
JLabel labelScore//記分卡
SnakeModel snakeModel = null//蛇
public static final int canvas width = 200;
public static final int canvasHeight = 300;
公共靜態final int node width = 10;
public static final int nodeHeight = 10;
// -
///GreedSnake():初始化遊戲界面。
// -
公共GreedSnake()
{
//設置界面元素
mainFrame = new JFrame(" GreedSnake ");
container CP = mainframe . getcontentpane();
labelScore = new JLabel(" Score:");
cp.add(labelScore,BorderLayout。北);
paintCanvas =新畫布();
paint canvas . setsize(canvas width+1,canvas height+1);
paint canvas . addkey listener(this);
cp.add(paintCanvas,BorderLayout。中心);
JPanel panel buttom = new JPanel();
panel buttom . set layout(new BorderLayout());
JLabel labelHelp//幫助信息
labelHelp=new JLabel("PageUp,PageDown表示速度;,JLabel。中心);
panel button . add(label help,BorderLayout。北);
labelHelp=new JLabel("ENTER或R或S表示開始;",JLabel。中心);
panel button . add(label help,BorderLayout。中心);
labelHelp=new JLabel("空格或P表示暫停",JLabel。中心);
panel button . add(label help,BorderLayout。南);
CP . add(panel button,BorderLayout。南);
mainframe . addkey listener(this);
大型機. pack();
mainframe . setresizable(false);
mainframe . setdefaultcloseoperation(JFrame。EXIT _ ON _ CLOSE);
mainframe . set visible(true);
begin();
}
// -
//keyPressed():按鍵檢測
// -
公共void按鍵(按鍵事件e)
{
int key code = e . get key code();
if(snakeModel.running)開關(鍵碼)
{
案例關鍵事件。VK_UP:
snake model . change direction(snake model。UP);
打破;
案例關鍵事件。VK _唐:
snake model . change direction(snake model。向下);
打破;
案例關鍵事件。VK _左:
snake model . change direction(snake model。左);
打破;
案例關鍵事件。VK右:
snake model . change direction(snake model。對);
打破;
案例關鍵事件。VK _添加:
案例關鍵事件。VK _第_頁起:
snake model . speedup();//加速
打破;
案例關鍵事件。VK減去:
案例關鍵事件。VK _下壹頁:
snake model . speeddown();//慢下來
打破;
案例關鍵事件。VK _空間:
案例關鍵事件。VK_P:
snake model . changepousestate();//暫停或繼續
打破;
默認值:
}
//重新開始
if(keyCode==KeyEvent。VK_R || keyCode==KeyEvent。VK_S
|| keyCode==KeyEvent。VK _回車)
{
snakeModel.running = false
begin();
}
}
// -
//keyReleased():空函數
// -
公開無效密鑰釋放(密鑰事件e)
{
}
// -
//keyTyped():空函數
// -
公共void鍵入(KeyEvent e)
{
}
// -
//repaint():繪制遊戲界面(包括蛇和食物)
// -
void重畫()
{
graphics g = paint canvas . get graphics();
//繪制背景
g.setColor(顏色。白色);
g.fillRect(0,0,canvasWidth,canvas height);
//畫蛇
g.setColor(顏色。黑色);
linked list na = snake model . node array;
叠代器it = na . iterator();
while(it.hasNext())
{
節點n =(Node)it . next();
drawNode(g,n);
}
//畫出食物
g.setColor(顏色。紅色);
Node n = snakeModel.food
drawNode(g,n);
update score();
}
// -
//drawNode():繪制壹個節點(蛇或食物)
// -
私有void drawNode(圖形g,節點n)
{
g.fillRect(n.x*nodeWidth,n.y*nodeHeight,nodeWidth-1,node height-1);
}
// -
//updateScore():更改記分卡。
// -
公共void updateScore()
{
string s = " Score:"+snake model . Score;
labelScore.setText
}
// -
//begin():遊戲開始,放蛇。
// -
void begin()
{
if(snakeModel==null||!snakeModel.running)
{
snakeModel=new SnakeModel(this,canvasWidth/nodeWidth,
this . canvasheight/nodeHeight);
(新線程(snakeModel))。start();
}
}
// -
//main():主函數
// -
公共靜態void main(String[] args)
{
GreedSnake GS = new GreedSnake();
}
}
/**************************************************************************
*關鍵點分析:
*1)數據結構:矩陣[][]用於存儲地圖上的信息。如果沒有設置為假,
*設置為真;如果有食物或蛇;NodeArray是壹個LinkedList,用於保存每壹條蛇。
*部分;食物用來保存食物的位置;Node類存儲每個位置的信息。
*2)重要功能:
* change direction(int new direction),用於改變蛇的方向,並且只有。
*保存頭部的方向,因為其他方向已由位置指示。其中,newDirection
*它必須與原始方向不同,所以相反方向的值使用相同的奇偶性。測試
*使用了方向%2!=newDirection%2進行判斷。
* moveOn(),用於更新蛇的位置,對於當前方向,頭部位置也相應改變。如果妳越界了,
*結束;否則,檢測是否遇到食物(加頭)或身體(尾);如果什麽都沒有,加上頭,
*移除尾部。因為使用了LinkedList數據結構,省去了很多麻煩。
*************************************************************************/
// -
//Node:節點類
// -
類節點
{
int x;
int y;
Node(int x,int y)
{
this.x = x
this.y = y
}
}
// -
//SnakeModel:蛇模型
// -
SnakeModel類實現Runnable
{
GreedSnake gs
布爾[][]矩陣;//接口數據保存在數組中。
linked list node array = new linked list();
節點食物;
int maxX//最大寬度
int maxY//最大長度
int direction = 2;//方向
布爾運行=假;
int timeInterval = 200//間隔時間(速度)
double speedChangeRate = 0.75//速度變化程度
布爾暫停=假;//遊戲狀態
int得分= 0;
int count move = 0;
//上下是偶數,左右是奇數。
public static final int UP = 2;
public static final int DOWN = 4;
public static final int LEFT = 1;
public static final int RIGHT = 3;
// -
//GreedModel():初始化接口
// -
public SnakeModel(GreedSnake gs,int maxX,int maxY)
{
this.gs = gs
this.maxX = maxX
this.maxY = maxY
matrix = new boolean[maxX][];
for(int I = 0;我& ltmaxX++i)
{
matrix[I]= new boolean[maxY];
Arrays.fill(matrix[i],false);//在沒有蛇或食物的區域設置false。
}
//初始化Snake
int initArrayLength = maxX & gt20 ?10:maxX/2;
for(int I = 0;我& ltinitArrayLength++i)
{
int x = maxX/2+I;
int y = maxY/2;
nodeArray.addLast(新節點(x,y));
matrix[x][y]= true;//snake處置真
}
food = create food();
matrix[food . x][food . y]= true;//食品處理真
}
// -
//changeDirection():改變運動的方向。
// -
公共void change direction(int new direction)
{
如果(方向%2!=newDirection%2)//避免沖突
{
direction = newDirection
}
}
// -
//moveOn():蛇形運動函數
// -
公共布爾移動()
{
Node n =(Node)Node array . get first();
int x = n.x
int y = n.y
開關(方向)
{
案例向上:
y-;
打破;
案例向下:
y++;
打破;
案例左側:
x-;
打破;
案例權利:
x++;
打破;
}
如果((0 & lt= x & amp& ampx & ltmaxX)和amp& amp(0 & lty & amp& ampy & ltmaxY))
{
If(matrix[x][y])//吃食物或者打身體。
{
if(x = = food . x & amp;& ampY==food.y)//吃貨。
{
nodeArray.addFirst(食物);//在標頭中添加壹個節點。
//評分規則與移動長度和速度有關。
int score get =(10000-200 * count move)/time interval;
score+= score get & gt;0 ?score get:10;
count move = 0;
food = create food();
matrix[food . x][food . y]= true;
返回true
}
否則返回false//擊中身體
}
Else//我什麽都沒碰
{
nodeArray.addFirst(新節點(x,y));//添加頭部
matrix[x][y]= true;
n =(Node)Node array . remove last();//移除尾部
matrix[n . x][n . y]= false;
count move++;
返回true
}
}
返回false//越線(撞墻)
}
// -
//run():蛇形運動線程
// -
公共無效運行()
{
跑步=真;
(跑步時)
{
嘗試
{
Thread.sleep(時間間隔);
}catch(異常e)
{
打破;
}
如果(!暫停)
{
If(moveOn())//未完成
{
GS . repaint();
}
否則//遊戲結束
{
JOptionPane.showMessageDialog(空,“遊戲結束”,
“遊戲結束”,JOptionPane。信息_消息);
打破;
}
}
}
跑步=假;
}
// -
//createFood():生成食物並放置。
// -
私有節點createFood()
{
int x = 0;
int y = 0;
做
{
Random r = new Random();
x = r . nextint(maxX);
y = r . nextint(maxY);
} while(matrix[x][y]);
返回新節點(x,y);
}
// -
//speedUp():加快蛇的移動速度。
// -
公共void加速()
{
timeInterval * = speedChangeRate
}
// -
//speedDown():減緩蛇的速度。
// -
公共void減速()
{
time interval/= speed change rate;
}
// -
//changePauseState():改變遊戲狀態(暫停或繼續)
// -
public void changePauseState()
{
暫停了=!暫停;
}
}