蛇喫膽

三個文件,樓主看好:
運行可以,但是並不能鼓吹是一個具有好的風格的代碼,。

//文件一
package greedysnake_cx;

public class Node {
int x=0;
int y=0;

int nodewidth;
int nodeheight;

Node(int x,int y){
this.x=x;
this.y=y;
}
}

//文件二
package greedysnake_cx;

/**
* 實現一個greedysnake的模型,具有功能:
* 1)移動,moveOn()----從director參數中獲取方向信息,如果方向定義的下一個點的邏輯值是true,檢查是不是food,是則將food添加到
* 列表的頭部,snake繼續移動,不是則停止移動(撞到蛇尾巴了)
* 2)加速,speedUp()----將現成的停滯時間間隔interval按照一定的比率 speedRate進行擴大
* 3)減速,speedDown()----....
*
* 該類實現Runnable接口,
* */

//定義snake的模型
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;
}

}

//文件三
package greedysnake_cx;

/**
* 在repaint()方法中,繪畫上下文對象是從canvas對象使用getContentPane()獲取的!!
* */
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();
//在jframe面板中添加各種組件
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的進程,並且開始改進程
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);
}
//繪製food
g.setColor(Color.green);
Node foodnode=new Node(snakemodel.food.x,snakemodel.food.y);
paintingNode(g,foodnode);
}

public void paintingNode(Graphics gg,Node n){
/*
* 使用Graphics 的fillRect方法,填充一個矩形,
* 矩形的起點需要乘以一個NODE的長寬,以避免重疊
* */
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) {//鍵入某一個鍵時,調用此方法!
}
//main
public static void main(String[] args){
GreedSnake gs=new GreedSnake();
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章