游戲的各個類存放的位置如圖所示
備注:
-
header圖片為窗口上部分圖片,像素為850*64
-
body圖片為小蛇的身體圖片,像素為25*25
-
food圖片為小蛇的食物圖片,像素為25*25
-
讀者可以根據所提供的像素自己制作小蛇的相關圖片。
游戲的啟動程序
package EatSnake;
import javax.swing.*;
//開始游戲主程序
public class StartGame {
public static void main(String[] args) {
JFrame frame=new JFrame();
frame.setResizable(false);
frame.setBounds(10,10,900,720);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(new GamePanel());
frame.setVisible(true);
}
}
游戲的圖片資源
package EatSnake;
import javax.swing.*;
import java.net.URL;
//獲得各個圖片資源
public class Data {
public static URL headerURl=Data.class.getResource("statics/header.png");
public static ImageIcon header=new ImageIcon(headerURl); //頭部封面
public static URL rightURl=Data.class.getResource("statics/right.png");
public static ImageIcon right=new ImageIcon(rightURl);
public static URL leftURL=Data.class.getResource("statics/lift.png");
public static ImageIcon left=new ImageIcon(leftURL);
public static URL upURL=Data.class.getResource("statics/up.png");
public static ImageIcon up=new ImageIcon(upURL);
public static URL downURL=Data.class.getResource("statics/down.png");
public static ImageIcon down=new ImageIcon(downURL);
public static URL bodyURL=Data.class.getResource("statics/body.png");
public static ImageIcon body=new ImageIcon(bodyURL);
public static URL foodURL=Data.class.getResource("statics/food.png");
public static ImageIcon food=new ImageIcon(foodURL); //食物圖標
}
游戲的繪制面板
package EatSnake;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class GamePanel extends JPanel implements KeyListener,ActionListener {
//定義蛇的數據結構
int length;
int[] snakeX=new int[600];
int[] snakeY=new int[500];
String fx; //初始化蛇頭方向
//設置食物的相關屬性
int foodX,foodY;
Random random=new Random();
int score; //定義在游戲中獲得的積分.
//設置游戲當前狀態為不開始
boolean isStart=false; //設置游戲的初始狀態是沒開始
boolean isFail=false; //判斷游戲是否失敗,默認沒失敗
//設置定時器--->通過時間監聽來完成
//以毫秒為單位,一秒刷新十次
Timer timer=new Timer(100,this);
//構造器
public GamePanel(){
init();
this.setFocusable(true); //獲取焦點事件
this.addKeyListener(this); //添加鍵盤監聽事件
timer.start();
}
public void init(){
length=3;
snakeX[0]=100;snakeY[0]=100; //腦袋的坐標
snakeX[1]=75;snakeY[1]=100; //第一個身體的坐標
snakeX[2]=50;snakeY[2]=100; //第二個身體的坐標
fx="R";
//把食物隨機分布在界面上
foodX=25+25* random.nextInt(34); //random隨機產生一個[0,34)的數字
foodY=75+25*random.nextInt(24); //random隨機產生一個[0,24)的數字
score=0;
}