资源描述:
《贪吃蛇java代码》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、packagettt;importjava.awt.event.KeyEvent;importjava.awt.event.KeyListener;importjavax.swing.*;importjava.util.Arrays;importjava.util.LinkedList;importjava.util.Observable;importjava.util.Random;importjavax.swing.*;importjava.awt.*;importjava.util.Iterator;importjav
2、a.util.LinkedList;importjava.util.Observable;importjava.util.Observer;classSnakeViewimplementsObserver{SnakeControlcontrol=null;SnakeModelmodel=null;JFramemainFrame;CanvaspaintCanvas;JLabellabelScore;publicstaticfinalintcanvasWidth=200;publicstaticfinalintcanvasHei
3、ght=300;publicstaticfinalintnodeWidth=10;publicstaticfinalintnodeHeight=10;publicSnakeView(SnakeModelmodel,SnakeControlcontrol){this.model=model;this.control=control;mainFrame=newJFrame("GreedSnake");Containercp=mainFrame.getContentPane();//创建顶部的分数显示labelScore=newJ
4、Label("Score:");cp.add(labelScore,BorderLayout.NORTH);//创建中间的游戏显示区域paintCanvas=newCanvas();paintCanvas.setSize(canvasWidth+1,canvasHeight+1);paintCanvas.addKeyListener(control);cp.add(paintCanvas,BorderLayout.CENTER);//创建底下的帮助栏JPanelpanelButtom=newJPanel();panelBut
5、tom.setLayout(newBorderLayout());JLabellabelHelp;labelHelp=newJLabel("PageUp,PageDownforspeed;",JLabel.CENTER);panelButtom.add(labelHelp,BorderLayout.NORTH);labelHelp=newJLabel("ENTERorRorSforstart;",JLabel.CENTER);panelButtom.add(labelHelp,BorderLayout.CENTER);lab
6、elHelp=newJLabel("SPACEorPforpause",JLabel.CENTER);panelButtom.add(labelHelp,BorderLayout.SOUTH);cp.add(panelButtom,BorderLayout.SOUTH);mainFrame.addKeyListener(control);mainFrame.pack();mainFrame.setResizable(false);mainFrame.setDefaultCloseOperation(JFrame.EXIT_O
7、N_CLOSE);mainFrame.setVisible(true);}voidrepaint(){Graphicsg=paintCanvas.getGraphics();//drawbackgroundg.setColor(Color.WHITE);g.fillRect(0,0,canvasWidth,canvasHeight);//drawthesnakeg.setColor(Color.BLACK);LinkedListna=model.nodeArray;Iteratorit=na.iterator();while
8、(it.hasNext()){Noden=(Node)it.next();drawNode(g,n);}//drawthefoodg.setColor(Color.RED);Noden=model.food;drawNode(g,n);updateScore();}privatevoidd