java贪吃蛇游戏源代码代码怎样生成游戏

下次自动登录
现在的位置:
& 综合 & 正文
简易贪吃蛇(JAVA版)源代码
import java.awt.BorderL
import java.awt.C
import java.awt.F
import java.awt.G
import java.awt.P
import java.awt.event.KeyE
import java.awt.event.KeyL
import java.util.LinkedL
import javax.swing.*;
class snakeModel extends JPanel implements Runnable{
public snakeModel(){
createFood();
private int[][] map=new int[90][50];
private LinkedList snakeBody=new LinkedList();//记录snake状态
//private LinkedList rcrdS//记录snake坐标值
private LinkedList rcrdS//记录snake坐标值
private JButton startButton=new JButton("开始"),
pauseButton=new JButton("暂停"),
exitButton=new JButton("退出");
private int foodLocationX,foodLocationY;
private int direct=1,status=0;//1=右,2=左,5=上,6=下
private int speedTime=100;//设置snake运动速度
protected void iniMap(){//初始化游戏,没有实体部分全部设置为0
for(int i=0;i&90;i++){
for(int j=0;j&50;j++)
map[i][j]=0;
/**初始化snake**/
addSnakeBody(44,25);
addSnakeBody(45,25);
addSnakeBody(46,25);
protected void addSnakeBody(int x,int y){//记录snake状态
rcrdSnake=new LinkedList();//记录snake坐标值
rcrdSnake.add(x);
rcrdSnake.addLast(y);
map[x][y]=1;
snakeBody.addFirst(rcrdSnake);
protected void removeSnakeBody(){
rcrdSnake=(LinkedList) snakeBody.getLast();
x=(int)rcrdSnake.getFirst();
y=(int)rcrdSnake.getLast();
map[x][y]=0;
snakeBody.removeLast();
protected boolean move(){
rcrdSnake=(LinkedList) snakeBody.getFirst();
x=(int)rcrdSnake.getFirst();
y=(int)rcrdSnake.getLast();
switch(direct){
case 1://向右运动
case 2://向左运动
case 5://向上运动
case 6://向下运动
if(x&89||x&0||y&0||y&49){//碰到边界
//drawString("Failed");
else if(x==foodLocationX&&y==foodLocationY){//吃到食物
addSnakeBody(x,y);
createFood();
else {//普通移动
if(map[x][y]==1){
System.out.printf("\nfoodX%d foodY%d\n",foodLocationX,foodLocationY);
System.out.printf("\nX%d Y%d\n",x,y);
System.out.printf("\n蛇体%d\n",map[x][y]);
else{//碰到自己
System.out.printf("\nX%d Y%d\n",x,y);
System.out.printf("\n蛇体%d\n",map[x][y]);
addSnakeBody(x,y);
//snakeBody.removeLast();
removeSnakeBody();//移除snake最后一个点
System.out.println(snakeBody.size());
protected void changeDirect(int newDirect){
if(Math.abs(newDirect-direct)!=1)
direct=newD
protected void createFood(){//生成食物
i=(int)Math.rint(Math.random()*89);
j=(int)Math.rint(Math.random()*49);
}while(map[i][j]==1);
map[i][j]=1;
foodLocationX=i;
foodLocationY=j;
System.out.println("createFooding....");
public void run() {
// TODO Auto-generated method stub
while(move()){
System.out.println("running");
repaint();
Thread.sleep(speedTime);
}catch(InterruptedException e){
System.out.println(e);
public void paintComponent(Graphics g){//绘制贪吃蛇并创建食物
super.paintComponent(g);
g.setColor(Color.RED);
g.drawRect(10, 0, 544, 304);//绘制游戏边框
for(int i=0;i&snakeBody.size();i++){
rcrdSnake= (LinkedList) snakeBody.get(i);
x=(int) rcrdSnake.get(0);
y=(int) rcrdSnake.get(1);
g.fillRect(x*6+12, y*6+2, 6, 6);
Font font=new Font("",50,30);
//System.out.println(status);
if(status==1){
g.setFont(font);
g.drawString("Game over", 10, 10);
g.fillRect(foodLocationX*6+12, foodLocationY*6+2, 6, 6);
//g.fillRect(50, 50, 6, 6);
class gameWindow extends JFrame implements KeyListener{
private static final long serialVersionUID = 1L;
protected snakeModel panelActive=new snakeModel();
protected JPanel panelMenu=new JPanel();
private int newD
public gameWindow(){
super("贪吃蛇");
setLayout(null);
panelActive.setBackground(Color.cyan);
panelMenu.setBackground(Color.darkGray);
panelMenu.setBounds(0, 325, 600, 50);
panelActive.setBounds(10, 10, 580, 310);
add(panelActive);
add(panelMenu);
addKeyListener(this);
setSize(600,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Thread moveThread=new Thread(panelActive);
moveThread.start();
//repaint();
public void keyPressed(KeyEvent key) {
// TODO Auto-generated method stub
if(key.getKeyCode()==38){//向上
newDirect=5;
panelActive.changeDirect(newDirect);
else if(key.getKeyCode()==40){//向下
newDirect=6;
panelActive.changeDirect(newDirect);
else if(key.getKeyCode()==39){//向右
newDirect=1;
panelActive.changeDirect(newDirect);
else if(key.getKeyCode()==37){//向左
newDirect=2;
panelActive.changeDirect(newDirect);
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
public class Snake {
public static void main(String args[]){
new gameWindow();
//int i=(int)(Math.random()*10);
System.out.println("hello world");
//System.out.println(i);
&&&&推荐文章:
【上篇】【下篇】导读:用Java编写的贪吃蛇代码,下面是我用java编写的一个贪吃蛇游戏源代码.我个人是比较喜欢玩游戏的,很想做个游戏程序,其一是因为此游戏界面容易设计,今天我就把我程序的代码和算法介绍一下,程序中一个关于游戏信息的类如下,intm_gameS//游戏速度,intm_speedN//游戏速度数,boolm_//游戏状态,voidGameOver(void);//游戏结束函数,
用Java编写的贪吃蛇代码
下面是我用java编写的一个贪吃蛇游戏源代码.我个人是比较喜欢玩游戏的,所以学习编程二年多了,很想做个游戏程序,由于能力有限,一直没能做好,后来突然看同学在手机上玩“贪吃蛇”,故想做出来,其一是因为此游戏界面容易设计,算法也比较简单,今天我就把我程序的代码和算法介绍一下,顺便把程序界面皮肤设计说一下......
程序中一个关于游戏信息的类如下,由于类的说明在程序中写的很清楚了,就不再多解释了:#include &time.h&
//方向定义
const CPoint UP(CPoint(0,-1));
const CPoint DOWN(CPoint(0,1));
const CPoint LEFT(CPoint(-1,0));
const CPoint RIGHT(CPoint(1,0));
//速度快慢定义
const int HIGH = 75;
const int NORMAL = 180;
const int SLOW = 300;
const int MAX = 80; //表示转向数
const int LENGTH = 10;
class GameMsg
GameMsg(void)
: m_icon(0)
InitGame();
void InitGame(int up = VK_UP, int down = VK_DOWN, int left = VK_LEFT, int right = VK_RIGHT)
srand((unsigned)time(NULL));
m_gameSpeed = NORMAL;
m_speedNum = 2;
m_snakeNum = 4;
for(int i=0; i&m_snakeN ++i)
m_snakePoint[i] = CPoint(5+LENGTH*2*5+LENGTH,LENGTH*2*(i+5));
m_direction = RIGHT;
turnDOWN =
turnLEFT =
turnRIGHT =
int m_gameS//游戏速度
int m_speedN//游戏速度数
CPoint m_foodP //食物定义
bool m_//游戏状态,运得态还是暂停(结束)态
CPoint m_snakePoint[MAX]; //蛇身定义
CPoint m_//蛇运动方向
int m_snakeN //蛇身结点数
int m_//用来设定食物是那种图标的
int turnUP;//用来表示玩家“上”键设的键int turnDOWN;//用来表示玩家“下”键设的键int turnLEFT;//用来表示玩家“左”键设的键int turnRIGHT;//用来表示玩家“右”键设的键
int m_//用来记录所选水果的编号
再让读者看一下程序主干类的设计,其中以下只列出由我们自己添加的一些变量的说明,其他的是由程序向导自动生成的,我就不说了:
afx_msg void OnTimer(UINT_PTR nIDEvent);//程序中运行函数,即是一个定时器,时间就是上面类中的m_gameSpeed来控制的CStatic *m_staticA//这是一个蛇定义,是用来显示蛇的,上面只告诉蛇身结点的中心点位置坐标,然后在此中心画一个控件就类似于蛇身了afx_msg void OnClose();//结束,主要是在其中销毁定时器的
void GameOver(void);//游戏结束函数
afx_msg void OnRButtonDown(UINT nFlags, CPoint point);//当点击鼠标右键出现菜单afx_msg void OnNewGame();//菜单选项,新游戏afx_msg void OnPauseOrStart();//菜单选项,暂停/开始 游戏afx_msg void OnUpdateQuick(CCmdUI *pCmdUI);//这3个函数本来是来标记速度的,和上面类中的m_speedNum对应,但是没有标记成功
afx_msg void OnUpdateNormal(CCmdUI *pCmdUI);
afx_msg void OnUpdateSlow(CCmdUI *pCmdUI);
afx_msg void OnNormal();//菜单选项,设定为普通速度afx_msg void OnSlow();//菜单选项,设定为慢速度afx_msg void OnQuick();//菜单选项,设定为快速度afx_msg void OnIntroduce();//游戏介绍,就是弹出一个对话框而以
afx_msg void OnMoreprogram();//进入我的博客的函数
afx_msg void OnAbout();//关于“贪吃蛇”说明的对话框
afx_msg void OnExit();//退出游戏
CFont m_//这就是上图中显示“空心字体”的字体设置void ShowHollowFont(int cx, int cy, CString str);//显示空心字体函数,在(Cx,Cy)处显示字符串str
afx_msg void OnBnClickedExit();//退出游戏
int m_icon1;//表明蛇吃第1种水果的个数
int m_icon2;//表明蛇吃第2种水果的个数
int m_icon3;//表明蛇吃第3种水果的个数
然后给读者写的是我程序运行很重要的一个函数,WM_TIMER显示函数,里面有食物位置随机出现,判断蛇死,蛇移动等:
void CSnakeDlg::OnTimer(UINT_PTR nIDEvent)
if(game.m_snakePoint[0].x & 0 || game.m_snakePoint[0].y & LENGTH || game.m_snakePoint[0].x & 700 || game.m_snakePoint[0].y & 500)//当蛇跑出边界,游戏结束
GameOver();
for(int j=game.m_snakeNum-1; j&0; --j)//蛇移动的量的变化,当重新设定这些控件的位置时也就是让蛇移动起来game.m_snakePoint[j] = game.m_snakePoint[j-1];
game.m_snakePoint[0].x += game.m_direction.x * LENGTH * 2;//蛇头移动game.m_snakePoint[0].y += game.m_direction.y * LENGTH * 2;
for(int i=0; i&game.m_snakeN ++i)
包含总结汇报、外语学习、旅游景点、文档下载、办公文档、党团工作、人文社科、教学研究以及用java编写的贪吃蛇游戏代码等内容。本文共3页
相关内容搜索本帖子已过去太久远了,不再提供回复功能。Swing贪吃蛇游戏(一):基本功能实现 - Java学习: 让积累成为一种习惯 - ITeye技术网站
博客分类:
本文将提供一个Swing版本的贪吃蛇游戏,游戏包括最基本的功能:
1. 用Timer来管理贪吃蛇线程。
2. 实现按钮,键盘的事件响应。
3. 随机产生食物。
4. 游戏结束的判断:蛇头触碰到蛇身或者蛇头触碰到边界。
5. 实现游戏过程中的暂停以及贪吃蛇运行速度调整。
6. … …
程序界面如下:左边是贪吃蛇运行的范围,右边暂时只有分数信息,当蛇吃到食物的时候分数加10.
暂停,调整蛇体运行速度界面如下:
主要的代码如下:
package my.games.snake.
import java.awt.C
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.S
import my.games.snake.contants.SnakeGameC
* 贪吃蛇游戏用到的格子类
* @author Eric
public class Grid implements Serializable {
private static final long serialVersionUID = 6028563L;
// x location
// y location
private C // color for square
public Grid() {
public Grid(int x, int y, Color color) {
this.color =
* Draw Grid
* @param g2
public void draw(Graphics2D g2) {
int clientX = SnakeGameConstant.SNAKE_GAME_PANEL_LEFT + x
* SnakeGameConstant.GRID_SIZE;
int clientY = SnakeGameConstant.SNAKE_GAME_PANEL_TOP + y
* SnakeGameConstant.GRID_SIZE;
Rectangle2D.Double rect = new Rectangle2D.Double(clientX, clientY,
SnakeGameConstant.GRID_SIZE, SnakeGameConstant.GRID_SIZE);
g2.setPaint(color);
g2.fill(rect);
g2.setPaint(Color.BLACK);
g2.draw(rect);
* @return the color
public Color getColor() {
* @param color
the color to set
public void setColor(Color color) {
this.color =
* @return the x
public int getX() {
* @param x
the x to set
public void setX(int x) {
* @return the y
public int getY() {
* @param y
the y to set
public void setY(int y) {
package my.games.snake.
import java.awt.Graphics2D;
import java.io.S
import java.util.LinkedL
import java.util.L
import my.games.snake.contants.SnakeGameC
import my.games.snake.enums.D
public class Snake implements Serializable {
private static final long serialVersionUID = -4550631L;
private List&Grid& list =
private Direction direction = Direction.RIGHT;
public Snake() {
this.list = new LinkedList&Grid&();
public void changeDirection(Direction direction) {
if (direction.isUpDirection()) {
if (!this.direction.isUpDirection()
&& !this.direction.isDownDirection()) {
this.direction =
} else if (direction.isRightDirection()) {
if (!this.direction.isRightDirection()
&& !this.direction.isLeftDirection()) {
this.direction =
} else if (direction.isDownDirection()) {
if (!this.direction.isUpDirection()
&& !this.direction.isDownDirection()) {
this.direction =
} else if (direction.isLeftDirection()) {
if (!this.direction.isRightDirection()
&& !this.direction.isLeftDirection()) {
this.direction =
public void draw(Graphics2D g2) {
for (Grid grid : list) {
grid.draw(g2);
* @return the list
public List&Grid& getList() {
* @param list
the list to set
public void setList(List&Grid& list) {
this.list =
* @return the direction
public Direction getDirection() {
* @param direction
the direction to set
public void setDirection(Direction direction) {
this.direction =
public void move() {
Grid currentHead = list.get(0);
int headX = currentHead.getX();
int headY = currentHead.getY();
currentHead.setColor(SnakeGameConstant.SNAKE_BODY_COLOR);
if (direction.isDownDirection()) {
list.add(0, new Grid(headX, headY + 1,
SnakeGameConstant.SNAKE_HEADER_COLOR));
list.remove(list.size() - 1);
} else if (direction.isUpDirection()) {
list.add(0, new Grid(headX, headY - 1,
SnakeGameConstant.SNAKE_HEADER_COLOR));
list.remove(list.size() - 1);
} else if (direction.isRightDirection()) {
list.add(0, new Grid(headX + 1, headY,
SnakeGameConstant.SNAKE_HEADER_COLOR));
list.remove(list.size() - 1);
} else if (direction.isLeftDirection()) {
list.add(0, new Grid(headX - 1, headY,
SnakeGameConstant.SNAKE_HEADER_COLOR));
list.remove(list.size() - 1);
package my.games.snake.
import java.awt.C
import java.awt.event.ActionE
import java.awt.event.ActionL
import javax.swing.ButtonG
import javax.swing.JF
import javax.swing.JM
import javax.swing.JMenuB
import javax.swing.JMenuI
import javax.swing.JOptionP
import javax.swing.JRadioButtonMenuI
import my.games.snake.contants.SnakeGameC
import my.games.snake.enums.GameS
public class SnakeGameFrame extends JFrame {
private static final long serialVersionUID = 506026L;
private SnakeGameP
private Container contentP
private JMenuItem startMI = new JMenuItem("Start");
private JMenuItem pauseMI = new JMenuItem("Pause");
private JMenu speedMenu = new JMenu("Speed");
private JMenuItem exitMI = new JMenuItem("Exit");
private JMenuItem aboutMI = new JMenuItem("About");
private JRadioButtonMenuItem speedMI1 = new JRadioButtonMenuItem("Speed1",
private JRadioButtonMenuItem speedMI2 = new JRadioButtonMenuItem("Speed2",
private JRadioButtonMenuItem speedMI3 = new JRadioButtonMenuItem("Speed3",
private JRadioButtonMenuItem speedMI4 = new JRadioButtonMenuItem("Speed4",
private JRadioButtonMenuItem speedMI5 = new JRadioButtonMenuItem("Speed5",
public int speedFlag = 1;
public SnakeGameFrame() {
setTitle(SnakeGameConstant.SNAKE_GAME);
setSize(SnakeGameConstant.SNAKE_GAME_FRAME_WIDTH,
SnakeGameConstant.SNAKE_GAME_FRAME_HEIGHT);
setResizable(false);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu setMenu = new JMenu("Set");
JMenu helpMenu = new JMenu("Help");
setMenu.setMnemonic('s');
setMenu.setMnemonic('H');
menuBar.add(setMenu);
menuBar.add(helpMenu);
setMenu.add(startMI);
setMenu.add(pauseMI);
setMenu.addSeparator();
setMenu.addSeparator();
setMenu.add(speedMenu);
setMenu.addSeparator();
setMenu.add(exitMI);
ButtonGroup group = new ButtonGroup();
group.add(speedMI1);
group.add(speedMI2);
group.add(speedMI3);
group.add(speedMI4);
group.add(speedMI5);
speedMenu.add(speedMI1);
speedMenu.add(speedMI2);
speedMenu.add(speedMI3);
speedMenu.add(speedMI4);
speedMenu.add(speedMI5);
startMI.addActionListener(new StartAction());
pauseMI.addActionListener(new PauseAction());
exitMI.addActionListener(new ExitAction());
speedMI1.addActionListener(new SpeedAction());
speedMI2.addActionListener(new SpeedAction());
speedMI3.addActionListener(new SpeedAction());
speedMI4.addActionListener(new SpeedAction());
speedMI5.addActionListener(new SpeedAction());
helpMenu.add(aboutMI);
aboutMI.addActionListener(new AboutAction());
contentPane = getContentPane();
panel = new SnakeGamePanel(this);
contentPane.add(panel);
startMI.setEnabled(true);
pauseMI.setEnabled(false);
// 设置游戏状态是初始化状态
panel.setGameState(GameState.INITIALIZE);
private class StartAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
startMI.setEnabled(false);
pauseMI.setEnabled(true);
panel.setGameState(GameState.RUN);
panel.getTimer().start();
private class PauseAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
pauseMI.setEnabled(false);
startMI.setEnabled(true);
panel.setGameState(GameState.PAUSE);
if (panel.getTimer().isRunning()) {
panel.getTimer().stop();
private class SpeedAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
Object speed = event.getSource();
if (speed == speedMI1) {
speedFlag = 1;
} else if (speed == speedMI2) {
speedFlag = 2;
} else if (speed == speedMI3) {
speedFlag = 3;
} else if (speed == speedMI4) {
speedFlag = 4;
} else if (speed == speedMI5) {
speedFlag = 5;
panel.getTimer().setDelay(1000 - 200 * (speedFlag - 1));
private class ExitAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
int result = JOptionPane.showConfirmDialog(SnakeGameFrame.this,
SnakeGameConstant.QUIT_GAME, SnakeGameConstant.SNAKE_GAME,
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
System.exit(0);
private class AboutAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
String string = SnakeGameConstant.KEYBOARDS_DESCRIPTION;
JOptionPane.showMessageDialog(SnakeGameFrame.this, string);
package my.games.snake.
import java.awt.C
import java.awt.G
import java.awt.Graphics2D;
import java.awt.event.ActionE
import java.awt.event.ActionL
import java.awt.event.KeyE
import java.awt.event.KeyL
import java.awt.geom.Rectangle2D;
import java.io.S
import java.util.LinkedL
import java.util.L
import java.util.R
import javax.swing.JOptionP
import javax.swing.JP
import javax.swing.T
import my.games.snake.contants.SnakeGameC
import my.games.snake.enums.D
import my.games.snake.enums.GameS
import my.games.snake.model.G
import my.games.snake.model.S
public class SnakeGamePanel extends JPanel {
private static final long serialVersionUID = -1265176L;
private int flag[][] = new int[SnakeGameConstant.GRID_COLUMN_NUMBER][SnakeGameConstant.GRID_ROW_NUMBER];// 在一个20*30的界面中,设置每个方块的flag
private Color color[][] = new Color[SnakeGameConstant.GRID_COLUMN_NUMBER][SnakeGameConstant.GRID_ROW_NUMBER];// 在一个20*30的界面中,设置每个方块的颜色
public TimerAction timerA
private SnakeGameF
private GameState gameState = GameState.INITIALIZE;
//private GameOverType gameOverType = GameOverType.TOUCH_EDGE;
private boolean needToGenerateFood =
public SnakeGamePanel(SnakeGameFrame frame) {
for (int i = SnakeGameConstant.LEFT; i &= SnakeGameConstant.RIGHT; i++) {
for (int j = SnakeGameConstant.UP; j &= SnakeGameConstant.DOWN; j++) {
flag[i][j] = 0;
addKeyListener(new KeyHandler());
setFocusable(true);
timerAction = new TimerAction();
timer = new Timer(1000, timerAction);
score = 0;
this.frame =
grid = new Grid();
private void init() {
initSnake();
initFood();
private void initSnake() {
snake = new Snake();
List&Grid& list = new LinkedList&Grid&();
list.add(new Grid(4, 1, SnakeGameConstant.SNAKE_BODY_COLOR));
list.add(0, new Grid(5, 1, SnakeGameConstant.SNAKE_HEADER_COLOR));
snake.setList(list);
private void initFood() {
food = new Grid();
needToGenerateFood =
this.generateFoodByRandom();
public void setGameState(GameState state) {
gameState =
private void judgeGameOver() {
if (isSnakeHeadTouchEdge() || isSnakeHeadTouchBody()) {
gameState = GameState.OVER;
int result = JOptionPane.showConfirmDialog(frame,
SnakeGameConstant.GAME_OVER, SnakeGameConstant.SNAKE_GAME,
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
for (int i = SnakeGameConstant.LEFT; i &= SnakeGameConstant.RIGHT; i++) {
for (int j = SnakeGameConstant.UP; j &= SnakeGameConstant.DOWN; j++) {
flag[i][j] = 0;
gameState = GameState.RUN;
score = 0;
timer.start();
System.exit(0);
public void drawGameFrame(Graphics2D g2) {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)
g2.draw(new Rectangle2D.Double(SnakeGameConstant.SNAKE_GAME_PANEL_LEFT,
SnakeGameConstant.SNAKE_GAME_PANEL_TOP,
SnakeGameConstant.SNAKE_GAME_PANEL_RIGHT,
SnakeGameConstant.SNAKEGAME_PANEL_BOTTOM));
if (gameState.isInitializedState()) {
drawScore(g);
private void draw(Graphics2D g2) {
drawSnake(g2);
drawFood(g2);
for (int i = SnakeGameConstant.LEFT; i &= SnakeGameConstant.RIGHT; i++) {
for (int j = SnakeGameConstant.UP; j &= SnakeGameConstant.DOWN; j++) {
if (flag[i][j] == 1) {
grid.setX(i);
grid.setY(j);
grid.setColor(color[i][j]);
grid.draw(g2);
private void drawScore(Graphics g) {
g.drawString("Score: " + score,
SnakeGameConstant.SNAKE_GAME_PANEL_RIGHT + 20, 200);
private void drawSnake(Graphics2D g2) {
snake.draw(g2);
private void drawFood(Graphics2D g2) {
food.draw(g2);
private class KeyHandler implements KeyListener {
public void keyPressed(KeyEvent event) {
if (!gameState.isRunState()) {
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.VK_LEFT:
snake.changeDirection(Direction.LEFT);
case KeyEvent.VK_RIGHT:
snake.changeDirection(Direction.RIGHT);
case KeyEvent.VK_UP:
snake.changeDirection(Direction.UP);
case KeyEvent.VK_DOWN:
snake.changeDirection(Direction.DOWN);
repaint();
public void keyReleased(KeyEvent event) {
public void keyTyped(KeyEvent event) {
private class TimerAction implements ActionListener, Serializable {
private static final long serialVersionUID = 207272L;
public void actionPerformed(ActionEvent e) {
if (!gameState.isRunState()) {
generateFoodByRandom();
snake.move();
eatFood();
judgeGameOver();
repaint();
private boolean isFoodAvailable(int x, int y) {
for (Grid grid : snake.getList()) {
if (x == grid.getX() && y == grid.getY()) {
private void generateFoodByRandom() {
if (needToGenerateFood) {
Random r = new Random();
int randomX = r.nextInt(SnakeGameConstant.GRID_COLUMN_NUMBER);
int randomY = r.nextInt(SnakeGameConstant.GRID_ROW_NUMBER);
if (isFoodAvailable(randomX, randomX)) {
food = new Grid(randomX, randomY, SnakeGameConstant.FOOD_COLOR);
needToGenerateFood =
generateFoodByRandom();
private boolean isSnakeHeadTouchEdge() {
Grid head = this.snake.getList().get(0);
if ((head.getX() &= SnakeGameConstant.GRID_COLUMN_NUMBER)
|| (head.getX() & 0)) {
//this.gameOverType = GameOverType.TOUCH_EDGE;
if ((head.getY() &= SnakeGameConstant.GRID_ROW_NUMBER)
|| (head.getY() & 0)) {
//this.gameOverType = GameOverType.TOUCH_EDGE;
private boolean isSnakeHeadTouchBody() {
Grid head = this.snake.getList().get(0);
int length = snake.getList().size();
for (int i = 1; i & i++) {
if (head.getX() == snake.getList().get(i).getX()
&& head.getY() == snake.getList().get(i).getY()) {
//this.gameOverType = GameOverType.TOUCH_BODY;
private boolean isFoodTouched() {
Grid head = snake.getList().get(0);
return head.getX() == food.getX() && head.getY() == food.getY();
private void eatFood() {
if (isFoodTouched()) {
Grid tail = snake.getList().get(snake.getList().size() - 1);
snake.getList().add(tail);
this.needToGenerateFood =
this.score += 10;
* @return the timer
public Timer getTimer() {
* @param timer
the timer to set
public void setTimer(Timer timer) {
this.timer =
完整的代码,请参考附件MySnakeGame.7z,有需要的朋友可以下载。
后续的博文将添加如下功能:
(二)添加随机障碍物。
(三)添加游戏进度的存储和读取
(四)完成游戏排行榜
... ...
下载次数: 48
MouseLearnJava
浏览: 184233 次
来自: 杭州
simpleDean 写道请问,Logger.setLevel ...
我运行了这个例子,怎么结果是这样的:2号车泊车6号车泊车5号车 ...
nanjiwubing123 写道参考你的用法,用如下方式实现 ...
SurnameDictionary文章我没看完,现在懂了
SurnameDictionary.populateCorre ...}

我要回帖

更多关于 java贪吃蛇代码详解 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信