java 小游戏程序
//您好!以下是
回答的程序。
//本人试了一下。这个程序非常值得学习。
//只要把该对话框内所有的字复制粘贴到Eclipse或者JGrasp就可以运行了。
/**************************************************************************
*要点分析:
*1)主要部分已经集成为一个对象SnakeModel,利用键盘控制实现操作。
*************************************************************************/
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
importjava.util.*;
//=============================================
//MainClass
//=============================================
publicclassGreedSnakeimplementsKeyListener
JFramemainFrame;
CanvaspaintCanvas;
JLabellabelScore;//计分牌
SnakeModelsnakeModel=null;//蛇
publicstaticfinaLINtcanvasWidth=200;
publicstaticfinalintcanvasHeight=300;
publicstaticfinalintnodeWidth=10;
publicstaticfinalintnodeHeight=10;
//----------------------------------------------------------------------
//GreedSnake():初始化游戏界面
//----------------------------------------------------------------------
publicGreedSnake()
//设置界面元素
mainFrame=newJFrame("GreedSnake");
Containercp=mainFrame.getContentPane();
labelScore=newJLabel("Score:");
cp.add(labelScore,BorderLayout.NORTH);
paintCanvas=newCanvas();
paintCanvas.setSize(canvasWidth+1,canvasHeight+1);
paintCanvas.addKeyListener(this);
cp.add(paintCanvas,BorderLayout.CENTER);
JPanelpanelButtom=newJPanel();
panelButtom.setLayout(newBorderLayout());
JLabellabelHelp;//帮助信息
labelHelp=newJLabel("PageUp,PageDownforspeed;",JLabel.CENTER);
panelButtom.add(labelHelp,BorderLayout.NORTH);
labelHelp=newJLabel("ENTERorRorSforstart;",JLabel.CENTER);
panelButtom.add(labelHelp,BorderLayout.CENTER);
labelHelp=newJLabel("SPACEorPforpause",JLabel.CENTER);
panelButtom.add(labelHelp,BorderLayout.SOUTH);
cp.add(panelButtom,BorderLayout.SOUTH);
mainFrame.addKeyListener(this);
mainFrame.pack();
mainFrame.setResizable(false);
mainFrame.setdefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
begin();
//----------------------------------------------------------------------
//keyPressed():按键检测
//----------------------------------------------------------------------
publicvoidkeyPressed(KeyEvente)
intkeyCode=e.getKeyCode();
if(snakeModel.running)switch(keyCode)
caseKeyEvent.VK_UP:
snakeModel.changeDirection(SnakeModel.UP);
break;
caseKeyEvent.VK_DOWN:
snakeModel.changeDirection(SnakeModel.DOWN);
break;
caseKeyEvent.VK_LEFT:
snakeModel.changeDirection(SnakeModel.LEFT);
break;
caseKeyEvent.VK_RIGHT:
snakeModel.changeDirection(SnakeModel.RIGHT);
break;
caseKeyEvent.VK_ADD:
caseKeyEvent.VK_PAGE_UP:
snakeModel.speedUp();//加速
break;
caseKeyEvent.VK_SUBTRACT:
caseKeyEvent.VK_PAGE_DOWN:
snakeModel.speedDown();//减速
break;
caseKeyEvent.VK_SPACE:
caseKeyEvent.VK_P:
snakeModel.changePauseState();//暂停或继续
break;
default:
//重新开始
if(keyCode==KeyEvent.VK_R||keyCode==KeyEvent.VK_S
||keyCode==KeyEvent.VK_ENTER)
snakeModel.running=false;
begin();
//----------------------------------------------------------------------
//keyReleased():空函数
//----------------------------------------------------------------------
publicvoidkeyReleased(KeyEvente)
//----------------------------------------------------------------------
//keyTyped():空函数
//----------------------------------------------------------------------
publicvoidkeyTyped(KeyEvente)
//----------------------------------------------------------------------
//repaint():绘制游戏界面(包括蛇和食物)
//----------------------------------------------------------------------
voidrepaint()
Graphicsg=paintCanvas.getGraphics();
//drawbackground
g.setColor(Color.WHITE);
g.fillRect(0,0,canvasWidth,canvasHeight);
//drawthesnake
g.setColor(Color.BLACK);
LinkedListna=snakeModel.nodeArray;
Iteratorit=na.iterator();
while(it.hasNext())
Noden=(Node)it.next();
drawNode(g,n);
//drawthefood
g.setColor(Color.RED);
Noden=snakeModel.food;
drawNode(g,n);
updateScore();
//----------------------------------------------------------------------
//drawNode():绘画某一结点(蛇身或食物)
//----------------------------------------------------------------------
privatevoiddrawNode(Graphicsg,Noden)
g.fillRect(n.x*nodeWidth,n.y*nodeHeight,nodeWidth-1,nodeHeight-1);
//----------------------------------------------------------------------
//updateScore():改变计分牌
//----------------------------------------------------------------------
publicvoidupdateScore()
Strings="Score:"+snakeModel.score;
labelScore.setText(s);
//----------------------------------------------------------------------
//begin():游戏开始,放置贪吃蛇
//----------------------------------------------------------------------
voidbegin()
if(snakeModel==null||!snakeModel.running)
snakeModel=neWSNakeModel(this,canvasWidth/nodeWidth,
this.canvasHeight/nodeHeight);
(newThread(snakeModel)).start();
//----------------------------------------------------------------------
//main():主函数
//----------------------------------------------------------------------
publicstaticvoidmain(String[]args)
GreedSnakegs=newGreedSnake();
/**************************************************************************
*要点分析:
*1)数据结构:matrix[][]用来存储地图上面的信息,如果什么也没有设置为false,
*如果有食物或蛇,设置为true;nodeArray,一个LinkedList,用来保存蛇的每
*一节;food用来保存食物的位置;而Node类是保存每个位置的信息。
*2)重要函数:
*changeDirection(intnewDirection),用来改变蛇前进的方向,而且只是
*保存头部的前进方向,因为其他的前进方向已经用位置来指明了。其中newDirection
*必须和原来的direction不是相反方向,所以相反方向的值用了同样的奇偶性。在测试
*的时候使用了direction%2!=newDirection%2进行判断。
*moveOn(),用来更新蛇的位置,对于当前方向,把头部位置进行相应改变。如果越界,
*结束;否则,检测是否遇到食物(加头部)或身体(结束);如果什么都没有,加上头部,
*去掉尾部。由于用了LinkedList数据结构,省去了相当多的麻烦。
*************************************************************************/
//----------------------------------------------------------------------
//Node:结点类
//----------------------------------------------------------------------
classNode
intx;
inty;
Node(intx,inty)
this.x=x;
this.y=y;
//----------------------------------------------------------------------
//SnakeModel:贪吃蛇模型
//----------------------------------------------------------------------
classSnakeModelimplementsRunnable
GreedSnakegs;
boolean[][]matrix;//界面数据保存在数组里
LinkedListnodeArray=newLinkedList();
Nodefood;
intmaxX;//最大宽度
intmaxY;//最大长度
intdirection=2;//方向
booleanrunning=false;
inttimeInterval=200;//间隔时间(速度)
doublespeedChangeRate=0.75;//速度改变程度
booleanpaused=false;//游戏状态
intscore=0;
intcountMove=0;
//UP和DOWN是偶数,RIGHT和LEFT是奇数
publicstaticfinalintUP=2;
publicstaticfinalintDOWN=4;
publicstaticfinalintLEFT=1;
publicstaticfinalintRIGHT=3;
//----------------------------------------------------------------------
//GreedModel():初始化界面
//----------------------------------------------------------------------
publicSnakeModel(GreedSnakegs,intmaxX,intmaxY)
this.gs=gs;
this.maxX=maxX;
this.maxY=maxY;
matrix=newboolean[maxX][];
for(inti=0;i
matrix[i]=newboolean[maxY];
Arrays.fill(matrix[i],false);//没有蛇和食物的地区置false
//初始化贪吃蛇
intinitArrayLength=maxX>20?10:maxX/2;
for(inti=0;i
intx=maxX/2+i;
inty=maxY/2;
nodeArray.addLast(newNode(x,y));
matrix[x][y]=true;//蛇身处置true
food=createFood();
matrix[food.x][food.y]=true;//食物处置true
//----------------------------------------------------------------------
//changeDirection():改变运动方向
//----------------------------------------------------------------------
publicvoidchangeDirection(intnewDirection)
if(direction%2!=newDirection%2)//避免冲突
direction=newDirection;
//----------------------------------------------------------------------
//moveOn():贪吃蛇运动函数
//----------------------------------------------------------------------
publicbooleanmoveOn()
Noden=(Node)nodeArray.getFirst();
intx=n.x;
inty=n.y;
switch(direction)
caseUP:
break;
caseDOWN:
break;
caseLEFT:
break;
caseRIGHT:
break;
if((0<=x&&x
if(matrix[x][y])//吃到食物或者撞到身体
if(x==food.x&&y==food.y)//吃到食物
nodeArray.addFirst(food);//在头部加上一结点
//计分规则与移动长度和速度有关
intscoreGet=(10000-200*countMove)/timeInterval;
score+=scoreGet>0?scoreGet:10;
countMove=0;
food=createFood();
matrix[food.x][food.y]=true;
returntrue;
elsereturnfalse;//撞到身体
else//什么都没有碰到
nodeArray.addFirst(newNode(x,y));//加上头部
matrix[x][y]=true;
n=(Node)nodeArray.removeLast();//去掉尾部
matrix[n.x][n.y]=false;
countMove++;
returntrue;
returnfalse;//越界(撞到墙壁)
//----------------------------------------------------------------------
//run():贪吃蛇运动线程
//----------------------------------------------------------------------
publicvoidrun()
running=true;
while(running)
Thread.sleep(timeInterval);
}catch(Exceptione)
break;
if(!paused)
if(moveOn())//未结束
gs.repaint();
else//游戏结束
JOptionPane.showMessageDialog(null,"GAMEOVER",
"GameOver",JOptionPane.INFORMATION_MESSAGE);
break;
running=false;
//----------------------------------------------------------------------
//createFood():生成食物及放置地点
//----------------------------------------------------------------------
privateNodecreateFood()
intx=0;
inty=0;
Randomr=newRandom();
x=r.nextInt(maxX);
y=r.nextInt(maxY);
}while(matrix[x][y]);
returnnewNode(x,y);
//----------------------------------------------------------------------
//speedUp():加快蛇运动速度
//----------------------------------------------------------------------
publicvoidspeedUp()
timeInterval*=speedChangeRate;
//----------------------------------------------------------------------
//speedDown():放慢蛇运动速度
//----------------------------------------------------------------------
publicvoidspeedDown()
timeInterval/=speedChangeRate;
//----------------------------------------------------------------------
//changePauseState():改变游戏状态(暂停或继续)
//----------------------------------------------------------------------
publicvoidchangePauseState()
paused=!paused;
我想用Java编写一款小游戏 需要下载什么软件 学习什么
1. 下载jdk并安装;2. 配置环境变量;3. 下载Eclipse或者MyEclipse并安装。你需要学习java语言