贪吃蛇游戏源程序

合集下载

JAVA程序源代码(贪吃蛇)

JAVA程序源代码(贪吃蛇)

贪吃蛇源代码将Location、LocationRO、SnakeFrame、SnakeModel、SnakePanel放到命名为snake的文件夹里,主函数MainApp放到外面运行主函数即可实现。

主函数package snake;import javax.swing.*;import snake.*;public class MainApp {public static void main(String[] args) {JFrame.setDefaultLookAndFeelDecorated(true);SnakeFrame frame=new SnakeFrame();frame.setSize(350,350);frame.setResizable(false);frame.setLocation(330,220);frame.setTitle("贪吃蛇");frame.setV isible(true);}}package snake;public class Location {private int x;private int y;Location(int x,int y){this.x=x;this.y=y;}int getX(){return x;}int getY(){return y;}void setX(int x){this.x=x;}void setY(int y){this.y=y;}public boolean equalOrRev(Location e){return ((e.getX()==getX())&&(e.getY()==getY()))||((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}public boolean equals(Location e){return(e.getX()==getX())&&(e.getY()==getY());}public boolean reverse(Location e){return ((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}}package snake;public class LocationRO{private int x;private int y;LocationRO(int x,int y){this.x=x;this.y=y;}int getX(){return x;}int getY(){return y;}public boolean equalOrRev(LocationRO e){return ((e.getX()==getX())&&(e.getY()==getY()))||((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}public boolean equals(LocationRO e){return(e.getX()==getX())&&(e.getY()==getY());}public boolean reverse(LocationRO e){return ((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}}package snake;import java.awt.*;import java.awt.event.*;import javax.swing.*;class SnakeFrame extends JFrame implements ActionListener{final SnakePanel p=new SnakePanel(this);JMenuBar menubar=new JMenuBar();JMenu fileMenu=new JMenu("文件");JMenuItem newgameitem=new JMenuItem("开始");JMenuItem stopitem=new JMenuItem("暂停");JMenuItem runitem=new JMenuItem("继续");JMenuItem exititem=new JMenuItem("退出");//"设置"菜单JMenu optionMenu=new JMenu("设置");//等级选项ButtonGroup groupDegree = new ButtonGroup();JRadioButtonMenuItem oneItem= new JRadioButtonMenuItem("初级");JRadioButtonMenuItem twoItem= new JRadioButtonMenuItem("中级");JRadioButtonMenuItem threeItem= new JRadioButtonMenuItem("高级");JMenu degreeMenu=new JMenu("等级");JMenu helpMenu=new JMenu("帮助");JMenuItem helpitem=new JMenuItem("操作指南");final JCheckBoxMenuItem showGridItem = new JCheckBoxMenuItem("显示网格");JLabel scorelabel;public JTextField scoreField;private long speedtime=200;private String helpstr = "游戏说明:\n1 :方向键控制蛇移动的方向."+"\n2 :单击菜单'文件->开始'开始游戏."+"\n3 :单击菜单'文件->暂停'或者单击键盘空格键暂停游戏."+"\n4 :单击菜单'文件->继续'继续游戏."+"\n5 :单击菜单'设置->等级'可以设置难度等级."+"\n6 :单击菜单'设置->显示网格'可以设置是否显示网格."+ "\n7 :红色为食物,吃一个得10分同时蛇身加长."+"\n8 :蛇不可以出界或自身相交,否则结束游戏.";SnakeFrame(){setJMenuBar(menubar);fileMenu.add(newgameitem);fileMenu.add(stopitem);fileMenu.add(runitem);fileMenu.add(exititem);menubar.add(fileMenu);oneItem.setSelected(true);groupDegree.add(oneItem);groupDegree.add(twoItem);groupDegree.add(threeItem);degreeMenu.add(oneItem);degreeMenu.add(twoItem);degreeMenu.add(threeItem);optionMenu.add(degreeMenu);// 风格选项showGridItem.setSelected(true);optionMenu.add(showGridItem);menubar.add(optionMenu);helpMenu.add(helpitem);menubar.add(helpMenu);Container contentpane=getContentPane();contentpane.setLayout(new FlowLayout());contentpane.add(p);scorelabel=new JLabel("得分: ");scoreField=new JTextField("0",15);scoreField.setEnabled(false);scoreField.setHorizontalAlignment(0);JPanel toolPanel=new JPanel();toolPanel.add(scorelabel);toolPanel.add(scoreField);contentpane.add(toolPanel);oneItem.addActionListener(this);twoItem.addActionListener(this);threeItem.addActionListener(this);newgameitem.addActionListener(this);stopitem.addActionListener(this);runitem.addActionListener(this);exititem.addActionListener(this);helpitem.addActionListener(this);showGridItem.addActionListener(this);}public void actionPerformed(ActionEvent e){try{if(e.getSource()==helpitem){JOptionPane.showConfirmDialog(p,helpstr,"操纵说明",JOptionPane.PLAIN_MESSAGE);}else if(e.getSource()==exititem)System.exit(0);else if(e.getSource()==newgameitem)p.newGame(speedtime);else if(e.getSource()==stopitem)p.stopGame();else if(e.getSource()==runitem)p.returnGame();else if(e.getSource()==showGridItem){if(!showGridItem.isSelected()){p.setBackground(Color.lightGray);}else{p.setBackground(Color.darkGray);}}else if(e.getSource()==oneItem) speedtime=200;else if(e.getSource()==twoItem) speedtime=100;else if(e.getSource()==threeItem) speedtime=50;}catch(Exception ee){ee.printStackTrace();}}}package snake;import java.util.*;import javax.swing.JOptionPane;public class SnakeModel {private int rows,cols;//行列数private Location snakeHead,runingDiriction;//运行方向private LocationRO[][] locRO;//LocationRO类数组private LinkedList snake,playBlocks;//蛇及其它区域块private LocationRO snakeFood;//目标食物private int gameScore=0; //分数private boolean AddScore=false;//加分// 获得蛇头public LocationRO getSnakeHead(){return (LocationRO)(snake.getLast());}//蛇尾public LocationRO getSnakeTail(){return (LocationRO)(snake.getFirst());}//运行路线public Location getRuningDiriction(){return runingDiriction;}//获得蛇实体区域public LinkedList getSnake(){return snake;}//其他区域public LinkedList getOthers(){return playBlocks;}//获得总分public int getScore(){return gameScore;}//获得增加分数public boolean getAddScore(){return AddScore;}//设置蛇头方向private void setSnakeHead(Location snakeHead){ this.snakeHead=snakeHead;}//获得目标食物public LocationRO getSnakeFood(){return snakeFood;}//随机设置目标食物private void setSnakeFood(){snakeFood=(LocationRO)(playBlocks.get((int)(Math.random()*playBlocks.size()))); }//移动private void moveTo(Object a,LinkedList fromlist,LinkedList tolist){fromlist.remove(a);tolist.add(a);}//初始设置public void init(){playBlocks.clear();snake.clear();gameScore=0;for(int i=0;i<rows;i++){for(int j=0;j<cols;j++){playBlocks.add(locRO[i][j]);}}//初始化蛇的形状for(int i=4;i<7;i++){moveTo(locRO[4][i],playBlocks,snake);}//蛇头位置snakeHead=new Location(4,6);//设置随机块snakeFood=new LocationRO(0,0);setSnakeFood();//初始化运动方向runingDiriction=new Location(0,1);}//Snake构造器public SnakeModel(int rows1,int cols1){rows=rows1;cols=cols1;locRO=new LocationRO[rows][cols];snake=new LinkedList();playBlocks=new LinkedList();for(int i=0;i<rows;i++){for(int j=0;j<cols;j++){locRO[i][j]=new LocationRO(i,j);}}init();}/**定义布尔型move方法,如果运行成功则返回true,否则返回false*参数direction是Location类型,*direction 的值:(-1,0)表示向上;(1,0)表示向下;*(0,-1)表示向左;(0,1)表示向右;**/public boolean move(Location direction){//判断设定的方向跟运行方向是不是相反if (direction.reverse(runingDiriction)){snakeHead.setX(snakeHead.getX()+runingDiriction.getX());snakeHead.setY(snakeHead.getY()+runingDiriction.getY());}else{snakeHead.setX(snakeHead.getX()+direction.getX());snakeHead.setY(snakeHead.getY()+direction.getY());}//如果蛇吃到了目标食物try{if ((snakeHead.getX()==snakeFood.getX())&&(snakeHead.getY()==snakeFood.getY())){moveTo(locRO[snakeHead.getX()][snakeHead.getY()],playBlocks,snake);setSnakeFood();gameScore+=10;AddScore=true;}else{AddScore=false;//是否出界if((snakeHead.getX()<rows)&&(snakeHead.getY()<cols)&&(snakeHead.getX()>=0&&(snak eHead.getY()>=0))){//如果不出界,判断是否与自身相交if(snake.contains(locRO[snakeHead.getX()][snakeHead.getY()])){//如果相交,结束游戏JOptionPane.showMessageDialog(null, "Game Over!", "游戏结束",RMA TION_MESSAGE);return false;}else{//如果不相交,就把snakeHead加到snake里面,并且把尾巴移出moveTo(locRO[snakeHead.getX()][snakeHead.getY()],playBlocks,snake);moveTo(snake.getFirst(),snake,playBlocks);}}else{//出界,游戏结束JOptionPane.showMessageDialog(null, "Game Over!", "游戏结束", RMA TION_MESSAGE);return false;}}}catch(ArrayIndexOutOfBoundsException e){return false;}//设置运行方向if (!(direction.reverse(runingDiriction)||direction.equals(runingDiriction))){runingDiriction.setX(direction.getX());runingDiriction.setY(direction.getY());}return true;}}package snake;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.util.*;public class SnakePanel extends JPanel implements Runnable,KeyListener{JFrame parent=new JFrame();private int row=20; //网格行数private int col=30; //列数private JPanel[][] gridsPanel; //面板网格private Location direction;//方向定位private SnakeModel snake; //贪吃蛇private LinkedList snakeBody; //蛇的身体private LinkedList otherBlocks; //其他区域private LocationRO snakeHead; //蛇的头部private LocationRO snakeFood; //目标食物private Color bodyColor=Color.orange;//蛇的身体颜色private Color headColor=Color.black; //蛇的头部颜色private Color foodColor=Color.red; //目标食物颜色private Color othersColor=Color.lightGray;//其他区域颜色private int gameScore=0; //总分private long speed; //速度(难度设置)private boolean AddScore; //加分private Thread t; //线程private boolean isEnd; //暂停private static boolean notExit;// 构造器,初始化操作public SnakePanel(SnakeFrame parent){this.parent=parent;gridsPanel=new JPanel[row][col];otherBlocks=new LinkedList();snakeBody=new LinkedList();snakeHead=new LocationRO(0,0);snakeFood=new LocationRO(0,0);direction=new Location(0,1);// 布局setLayout(new GridLayout(row,col,1,1));for(int i=0;i<row;i++){for(int j=0;j<col;j++){gridsPanel[i][j]=new JPanel();gridsPanel[i][j].setBackground(othersColor);add(gridsPanel[i][j]);}}addKeyListener(this);}// 开始游戏public void newGame(long speed){this.speed=speed;if (notExit) {snake.init();}else{snake=new SnakeModel(row,col);notExit=true;t=new Thread(this);t.start();}requestFocus();direction.setX(0);direction.setY(1);gameScore=0;updateTextFiled(""+gameScore);isEnd=false;}// 暂停游戏public void stopGame(){requestFocus();isEnd=true;}// 继续public void returnGame(){requestFocus();isEnd=false;}// 获得总分public int getGameScore(){return gameScore;}//更新总分private void updateTextFiled(String str){((SnakeFrame)parent).scoreField.setText(str); }//更新各相关单元颜色private void updateColors(){// 设定蛇身颜色snakeBody=snake.getSnake();Iterator i =snakeBody.iterator();while(i.hasNext()){LocationRO t=(LocationRO)(i.next());gridsPanel[t.getX()][t.getY()].setBackground(bodyColor);}//设定蛇头颜色snakeHead=snake.getSnakeHead();gridsPanel[snakeHead.getX()][snakeHead.getY()].setBackground(headColor);//设定背景颜色otherBlocks=snake.getOthers();i =otherBlocks.iterator();while(i.hasNext()){LocationRO t=(LocationRO)(i.next());gridsPanel[t.getX()][t.getY()].setBackground(othersColor);}//设定临时块的颜色snakeFood=snake.getSnakeFood();gridsPanel[snakeFood.getX()][snakeFood.getY()].setBackground(foodColor); }public boolean isFocusTraversable(){return true;}//实现Runnable接口public void run(){while(true){try{Thread.sleep(speed);}catch (InterruptedException e){}if(!isEnd){isEnd=!snake.move(direction);updateColors();if(snake.getAddScore()){gameScore+=10;updateTextFiled(""+gameScore);}}}}//实现KeyListener接口public void keyPressed(KeyEvent event){int keyCode = event.getKeyCode();if(notExit){if (keyCode == KeyEvent.VK_LEFT) { //向左direction.setX(0);direction.setY(-1);}else if (keyCode == KeyEvent.VK_RIGHT) { //向右direction.setX(0);direction.setY(1);}else if (keyCode == KeyEvent.VK_UP) { //向上direction.setX(-1);direction.setY(0);}else if (keyCode == KeyEvent.VK_DOWN) { //向下direction.setX(1);direction.setY(0);}else if (keyCode == KeyEvent.VK_SPACE){ //空格键isEnd=!isEnd;}}}public void keyReleased(KeyEvent event){}public void keyTyped(KeyEvent event){}}。

贪吃蛇游戏安卓源代码

贪吃蛇游戏安卓源代码

附录1.SnakeView类package com.example.android_snake.view;import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.Timer;import java.util.TimerTask;import com.example.android_snake.R;import com.example.android_snake.food.Food;import com.example.android_snake.snake.Body;import com.example.android_snake.snake.Head;import com.example.android_snake.snake.Snake;import com.example.android_snake.snake.SnakeDirection; import com.example.android_snake.stone.Stone;import android.annotation.SuppressLint;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Paint.Style;import android.os.Handler;import android.util.DisplayMetrics;import android.view.Display;import android.view.MotionEvent;import android.view.View;import android.view.ViewManager;import android.view.WindowManager;import android.widget.Toast;public class SnakeView extends View {private Context context;private Bitmap headBitmap;private Bitmap bodyBitmap;private Bitmap foodBitmap;private Bitmap stoneBitmap;// 屏幕的高度和宽度private int screenHeight;private int screenWidth;// 每个小格子的高度和宽度private int eachHeight;private int eachWidth;private Snake snake;private Food food;private Stone stone;private int [] listx;private int [] listy;private Timer timer = new Timer();Handler handler = new Handler() {public void handleMessage(android.os.Message msg) {moveSnake();invalidate();}};public SnakeView(Context context) {super(context);this.context = context;listx =new int[100];listy =new int[100];// 获得屏幕的高和宽DisplayMetrics metrics = new DisplayMetrics();WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);windowManager.getDefaultDisplay().getMetrics(metrics);screenHeight = metrics.heightPixels;screenWidth = metrics.widthPixels;eachHeight = screenHeight / 32;eachWidth = screenWidth / 20;// 初始化图片headBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.head);bodyBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.body);foodBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.food);stoneBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.stone);this.initSnake();this.initFood();this.initstone();gameRun();}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);Paint paint = new Paint();// 定义画笔paint.setColor(Color.GRAY);// 设置画笔颜色paint.setAntiAlias(true);// 去除锯齿paint.setStyle(Style.STROKE);// 设置空心实心paint.setTextSize(40);drawLines(canvas, paint);drawStone(canvas, paint);if(isCollide()){canvas.drawText("Game Over!", screenWidth/4, screenHeight/3, paint);canvas.drawText("得分", screenWidth/4, screenHeight/2, paint);timer.cancel();}else{this.drawSnake(canvas, paint);}boolean flag = IsRectCollision(snake.getHead().getPointX(), snake.getHead().getPointY(), eachWidth, eachHeight,food.getPointX(), food.getPointY(), eachWidth, eachHeight);if (flag) {food = null;snake.getBodyList().add(new Body());this.initFood();this.initstone();} else {this.drawFood(canvas, paint);this.drawStone(canvas, paint);}}//方向控制@Overridepublic boolean onTouchEvent(MotionEvent event) {int x = (int) event.getX();int y = (int) event.getY();SnakeDirection nowDir = snake.getSnakeDirection();int m = -screenHeight * x + screenHeight * screenWidth - screenWidth * y;int n = screenHeight * x - screenWidth * y;if ((m > 0 && n > 0) && (nowDir != SnakeDirection.DOWN)) {snake.setSnakeDirection(SnakeDirection.UP);} else if ((m > 0 && n < 0) && (nowDir != SnakeDirection.RIGHT)) { snake.setSnakeDirection(SnakeDirection.LEFT);} else if ((m < 0 && n > 0) && (nowDir != SnakeDirection.LEFT)) { snake.setSnakeDirection(SnakeDirection.RIGHT);} else if ((m < 0 && n < 0) && (nowDir != SnakeDirection.UP)) { snake.setSnakeDirection(SnakeDirection.DOWN);}return super.onTouchEvent(event);}public void gameRun() {timer.scheduleAtFixedRate(new TimerTask() {public void run() {handler.obtainMessage().sendToTarget();}}, 100, 400);}/** 画网格线*/public void drawLines(Canvas canvas, Paint paint) {int startX = 0, startY = 0;for (int i = 0; i < 100; i++) {canvas.drawLine(0, startY, screenWidth, startY, paint);startY = startY + eachHeight;}for (int i = 0; i < 100; i++) {canvas.drawLine(startX, 0, startX, screenHeight, paint);startX = startX + eachWidth;}canvas.drawLine(0, 0, screenWidth, screenHeight, paint);canvas.drawLine(0, screenHeight, screenWidth, 0, paint);}// 初始化蛇public void initSnake() {List<Body> bodies = new ArrayList<Body>();Head head = new Head(eachWidth * 4, eachHeight * 2, headBitmap);Body body1 = new Body(eachWidth * 3, eachHeight * 2, bodyBitmap);Body body2 = new Body(eachWidth * 2, eachHeight * 2, bodyBitmap);Body body3 = new Body(eachWidth * 1, eachHeight * 2, bodyBitmap);Body body4 = new Body(eachWidth * 0, eachHeight * 2, bodyBitmap);bodies.add(body1);bodies.add(body2);bodies.add(body3);bodies.add(body4);snake = new Snake(head, bodies, SnakeDirection.RIGHT);}// 画蛇public void drawSnake(Canvas canvas, Paint paint) {canvas.drawBitmap(headBitmap, snake.getHead().getPointX(), snake .getHead().getPointY(), paint);for (int i = 0; i < snake.getBodyList().size(); i++) {canvas.drawBitmap(bodyBitmap, snake.getBodyList().get(i).getPointX(), snake.getBodyList().get(i).getPointY(), paint);}}// 改变蛇身的位置public void changSnakePosition(int pointX, int pointY) {for (int i = snake.getBodyList().size() - 1; i > 0; i--) {snake.getBodyList().get(i).setPointX(snake.getBodyList().get(i - 1).getPointX());snake.getBodyList().get(i).setPointY(snake.getBodyList().get(i - 1).getPointY());}snake.getBodyList().get(0).setPointX(snake.getHead().getPointX());snake.getBodyList().get(0).setPointY(snake.getHead().getPointY());}// 移动蛇public void moveSnake() {int nowPointX = snake.getHead().getPointX();int nowPointY = snake.getHead().getPointY();if (snake.getSnakeDirection() == SnakeDirection.RIGHT) {changSnakePosition(nowPointX, nowPointY);if (nowPointX >= screenWidth - eachWidth) {snake.getHead().setPointX(0);} else {snake.getHead().setPointX(nowPointX + eachWidth);}} else if (snake.getSnakeDirection() == SnakeDirection.DOWN) { changSnakePosition(nowPointX, nowPointY);if (nowPointY >= screenHeight - eachHeight) {snake.getHead().setPointY(0);} else {snake.getHead().setPointY(nowPointY + eachHeight);}} else if (snake.getSnakeDirection() == SnakeDirection.LEFT) {changSnakePosition(nowPointX, nowPointY);if (nowPointX <= 0) {snake.getHead().setPointX(screenWidth - eachWidth);} else {snake.getHead().setPointX(nowPointX - eachWidth);}} else if (snake.getSnakeDirection() == SnakeDirection.UP) {changSnakePosition(nowPointX, nowPointY);if (nowPointY <= 0) {snake.getHead().setPointY(screenHeight - eachHeight);} else {snake.getHead().setPointY(nowPointY - eachHeight);}}}// 初始化foodpublic void initFood() {int x = new Random().nextInt(19);int y = new Random().nextInt(29);food = new Food(eachWidth * x, eachHeight * y, foodBitmap);}// 在界面上画出Foodpublic void drawFood(Canvas canvas, Paint paint) {if (food != null) {canvas.drawBitmap(foodBitmap, food.getPointX(), food.getPointY(),paint);}}// 初始化stonepublic void initstone() {int x = new Random().nextInt(17);int y = new Random().nextInt(23);stone = new Stone(eachWidth * x, eachHeight * y, stoneBitmap);int i=0,j=0;listx[i++]=x;listy[j++]=y;}// 在界面上画出Stonepublic void drawStone(Canvas canvas, Paint paint) {if (true) {canvas.drawBitmap(stoneBitmap, stone.getPointX(), stone.getPointY(),paint);for(int k=0;k<100;k++){//food = new Food(eachWidth * listx[k], eachHeight * listy[k], foodBitmap);//canvas.drawBitmap(stoneBitmap,listx[k], listy[k],paint);}}}/*** 矩形碰撞检测参数为x,y,width,height** @param x1* 第一个矩形的x* @param y1* 第一个矩形的y* @param w1* 第一个矩形的w* @param h1* 第一个矩形的h* @param x2* 第二个矩形的x* @param y2* 第二个矩形的y* @param w2* 第二个矩形的w* @param h2* 第二个矩形的h* @return是否碰撞*/public boolean IsRectCollision(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2) {if (x2 > x1 && x2 >= x1 + w1) {return false;} else if (x2 < x1 && x2 <= x1 - w2) {return false;} else if (y2 > y1 && y2 >= y1 + h1) {return false;} else if (y2 < y1 && y2 <= y1 - h2) {return false;} else {return true;}}//检测蛇头是否与蛇身碰撞//检测蛇头与墙的碰撞//public boolean isCollide() {boolean flag = false;for (int i = 0; i < snake.getBodyList().size(); i++) {flag = IsRectCollision(snake.getHead().getPointX(),snake.getHead().getPointY(), eachWidth, eachHeight,snake.getBodyList().get(i).getPointX(),snake.getBodyList().get(i).getPointY(),eachWidth,eachHeight);for(int j=0;j<100;j++){flag = IsRectCollision(snake.getHead().getPointX(),snake.getHead().getPointY(), eachWidth, eachHeight,listx[j],listy[j], eachWidth,eachHeight);if(flag){break;}}if ((snake.getHead().getPointX() < 1) ||(snake.getHead().getPointY() < 1) ||(snake.getHead().getPointX() > screenWidth - 1)||(snake.getHead().getPointY() > screenHeight - 1)){flag = true;}if(flag){break;}}return flag;}}2.MainActivity类package com.example.android_snake;import com.example.android_snake.R;import com.example.android_snake.view.SnakeView;//Downloads By import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.MenuItem;import android.view.Window;import android.view.WindowManager;public class MainActivity extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);//设置全屏getWindow().setFlags(youtParams.FLAG_FULLSCREEN, youtParams.FLAG_FULLSCREEN);SnakeView view = new SnakeView(this);setContentView(view);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu);return true;}}3.Food类package com.example.android_snake.food;import android.graphics.Bitmap;public class Food {private int pointX;private int pointY;private Bitmap foodBitmap;public Food() {super();}public Food(int pointX, int pointY, Bitmap foodBitmap) { super();this.pointX = pointX;this.pointY = pointY;this.foodBitmap = foodBitmap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getFoodBitmap() {return foodBitmap;}public void setFoodBitmap(Bitmap foodBitmap) {this.foodBitmap = foodBitmap;}}4.Body类package com.example.android_snake.snake;import android.graphics.Bitmap;public class Body {private int pointX;private int pointY;private Bitmap bodyBitMap;public Body() {super();}public Body(int pointX, int pointY, Bitmap bodyBitMap) { super();this.pointX = pointX;this.pointY = pointY;this.bodyBitMap = bodyBitMap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getBodyBitMap() {return bodyBitMap;}public void setBodyBitMap(Bitmap bodyBitMap) {this.bodyBitMap = bodyBitMap;}}5.Head类package com.example.android_snake.snake;import android.graphics.Bitmap;public class Head {private int pointX;private int pointY;private Bitmap headBitMap;public Head() {super();}public Head(int pointX, int pointY, Bitmap headBitMap) {super();this.pointX = pointX;this.pointY = pointY;this.headBitMap = headBitMap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getHeadBitMap() {return headBitMap;}public void setHeadBitMap(Bitmap headBitMap) {this.headBitMap = headBitMap;}}6.Snake类package com.example.android_snake.snake;import java.util.ArrayList;import java.util.List;import android.graphics.Bitmap;public class Snake {private Head head;private Body body;private List<Body> bodyList;private SnakeDirection snakeDirection;public Snake(){}public Snake(Head head,List<Body> bodyList,SnakeDirection snakeDirection){ super();this.head = head;this.bodyList = bodyList;this.snakeDirection = snakeDirection;}public Head getHead() {return head;}public void setHead(Head head) {this.head = head;}public Body getBody() {return body;}public void setBody(Body body) {this.body = body;}public List<Body> getBodyList() {return bodyList;}public void setBodyList(List<Body> bodyList) {this.bodyList = bodyList;}public SnakeDirection getSnakeDirection() {return snakeDirection;}public void setSnakeDirection(SnakeDirection snakeDirection) { this.snakeDirection = snakeDirection;}}7.SnakeDirection类package com.example.android_snake.snake;public enum SnakeDirection {UP,DOWN,LEFT,RIGHT;}8.Stone类package com.example.android_snake.stone;import android.graphics.Bitmap;public class Stone {private int pointX;private int pointY;private Bitmap stoneBitmap;public Stone() {super();}public Stone(int pointX, int pointY, Bitmap foodBitmap) { super();this.pointX = pointX;this.pointY = pointY;this.stoneBitmap = stoneBitmap;}public int getPointX() {return pointX;}public void setPointX(int pointX) {this.pointX = pointX;}public int getPointY() {return pointY;}public void setPointY(int pointY) {this.pointY = pointY;}public Bitmap getStoneBitmap() {return stoneBitmap;}public void setFoodBitmap(Bitmap foodBitmap) { this.stoneBitmap = stoneBitmap;}}。

贪吃蛇游戏c语言源代码

贪吃蛇游戏c语言源代码

#include <stdlib.h>#include <graphics.h>#include <bios.h>#include <dos.h>#include <conio.h>#define Enter 7181#define ESC 283#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#ifdef __cplusplus#define __CPPARGS ...#else#define __CPPARGS#endifvoid interrupt (*oldhandler)(__CPPARGS);void interrupt newhandler(__CPPARGS);void SetTimer(void interrupt (*IntProc)(__CPPARGS));void KillTimer(void);void Initgra(void);void TheFirstBlock(void);void DrawMap(void);void Initsnake(void);void Initfood(void);void Snake_Headmv(void);void Flag(int,int,int,int);void GameOver(void);void Snake_Bodymv(void);void Snake_Bodyadd(void);void PrntScore(void);void Timer(void);void Win(void);void TheSecondBlock(void);void Food(void);void Dsnkorfd(int,int,int);void Delay(int);struct Snake{int x;int y;int color;}Snk[12];struct Food{int x;int y;int color;}Fd;int flag1=1,flag2=0,flag3=0,flag4=0,flag5=0,flag6=0,checkx,checky,num,key=0,Times,Score,Hscore,Snkspeed,TimerCounter,TureorFalse; char Sco[2],Time[6];void main(){ Initgra();SetTimer(newhandler);TheFirstBlock();while(1){DrawMap();Snake_Headmv();GameOver();Snake_Bodymv();Snake_Bodyadd();PrntScore();Timer();Win();if(key==ESC)break;if(key==Enter){cleardevice();TheFirstBlock();}TheSecondBlock();Food();Delay(Snkspeed);}closegraph();KillTimer();}void interrupt newhandler(__CPPARGS){TimerCounter++;oldhandler();}void SetTimer(void interrupt (*IntProc)(__CPPARGS)) {oldhandler=getvect(0x1c);disable();setvect(0x1c,IntProc);enable();}void KillTimer(){disable();setvect(0x1c,oldhandler);enable();}void Initgra(){int gd=DETECT,gm;initgraph(&gd,&gm,"d:\\tc");}void TheFirstBlock(){setcolor(11);settextstyle(0,0,4);outtextxy(100,220,"The First Block");loop:key=bioskey(0);if(key==Enter){cleardevice();Initsnake();Initfood();Score=0;Hscore=1;Snkspeed=10;num=2;Times=0;key=0;TureorFalse=1;TimerCounter=0;Time[0]='0';Time[1]='0';Time[2]=':';Time[3]='1';Time[4]='0';Time[5]='\0'; }else if(key==ESC) cleardevice();else goto loop;}void DrawMap(){line(10,10,470,10);line(470,10,470,470);line(470,470,10,470);line(10,470,10,10);line(480,20,620,20);line(620,20,620,460);line(620,460,480,460);line(480,460,480,20);}void Initsnake(){randomize();num=2;Snk[0].x=random(440);Snk[0].x=Snk[0].x-Snk[0].x%20+50;Snk[0].y=random(440);Snk[0].y=Snk[0].y-Snk[0].y%20+50;Snk[0].color=4;Snk[1].x=Snk[0].x;Snk[1].y=Snk[0].y+20;Snk[1].color=4;}void Initfood(){randomize();Fd.x=random(440);Fd.x=Fd.x-Fd.x%20+30;Fd.y=random(440);Fd.y=Fd.y-Fd.y%20+30;Fd.color=random(14)+1;}void Snake_Headmv(){if(bioskey(1)){key=bioskey(0);switch(key){case UP:Flag(1,0,0,0);break;case DOWN:Flag(0,1,0,0);break;case LEFT:Flag(0,0,1,0);break;case RIGHT:Flag(0,0,0,1);break;default:break;}}if(flag1){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].y-=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color); }if(flag2){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].y+=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color); }if(flag3){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].x-=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color);}if(flag4){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].x+=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color);}}void Flag(int a,int b,int c,int d){flag1=a;flag2=b;flag3=c;flag4=d;}void GameOver(){int i;if(Snk[0].x<20||Snk[0].x>460||Snk[0].y<20||Snk[0].y>460) {cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"Game Over");loop1:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();}elseif(key==ESC)cleardevice();elsegoto loop1;}for(i=3;i<num;i++){if(Snk[0].x==Snk[i].x&&Snk[0].y==Snk[i].y) {cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"Game Over");loop2:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();}elseif(key==ESC)cleardevice();else goto loop2;}}}void Snake_Bodymv(){int i,s,t;for(i=1;i<num;i++){Dsnkorfd(checkx,checky,Snk[i].color); Dsnkorfd(Snk[i].x,Snk[i].y,0);s=Snk[i].x;t=Snk[i].y;Snk[i].x=checkx;Snk[i].y=checky;checkx=s;checky=t;}}void Food(){if(flag5){randomize();Fd.x=random(440);Fd.x=Fd.x-Fd.x%20+30;Fd.y=random(440);Fd.y=Fd.y-Fd.y%20+30;Fd.color=random(14)+1;flag5=0;}Dsnkorfd(Fd.x,Fd.y,Fd.color);}void Snake_Bodyadd(){if(Snk[0].x==Fd.x&&Snk[0].y==Fd.y) {if(Snk[num-1].x>Snk[num-2].x){num++;Snk[num-1].x=Snk[num-2].x+20;Snk[num-1].y=Snk[num-2].y;Snk[num-1].color=Fd.color;}elseif(Snk[num-1].x<Snk[num-2].x){num++;Snk[num-1].x=Snk[num-2].x-20;Snk[num-1].y=Snk[num-2].y;Snk[num-1].color=Fd.color;}elseif(Snk[num-1].y>Snk[num-2].y) {num++;Snk[num-1].x=Snk[num-2].x; Snk[num-1].y=Snk[num-2].y+20; Snk[num-1].color=Fd.color;}elseif(Snk[num-1].y<Snk[num-2].y) {num++;Snk[num-1].x=Snk[num-2].x; Snk[num-1].y=Snk[num-2].y-20; Snk[num-1].color=Fd.color;}flag5=1;Score++;}}void PrntScore(){if(Hscore!=Score){setcolor(11);settextstyle(0,0,3); outtextxy(490,100,"SCORE"); setcolor(2);setfillstyle(1,0);rectangle(520,140,580,180); floodfill(530,145,2);Sco[0]=(char)(Score+48);Sco[1]='\0';Hscore=Score;setcolor(4);settextstyle(0,0,3); outtextxy(540,150,Sco);}}void Timer(){if(TimerCounter>18){Time[4]=(char)(Time[4]-1); if(Time[4]<'0'){Time[4]='9';Time[3]=(char)(Time[3]-1);}if(Time[3]<'0'){Time[3]='5';Time[1]=(char)(Time[1]-1);}if(TureorFalse){setcolor(11);settextstyle(0,0,3);outtextxy(490,240,"TIMER");setcolor(2);setfillstyle(1,0);rectangle(490,280,610,320);floodfill(530,300,2);setcolor(11);settextstyle(0,0,3);outtextxy(495,290,Time);TureorFalse=0;}if(Time[1]=='0'&&Time[3]=='0'&&Time[4]=='0') {setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"Game Over");loop:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();}else if(key==ESC) cleardevice();else goto loop;}TimerCounter=0;TureorFalse=1;}}void Win(){if(Score==3)Times++;if(Times==2){cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"You Win");loop:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();key=0;}else if(key==ESC) cleardevice();else goto loop;}}void TheSecondBlock(){if(Score==3){cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(100,220,"The Second Block"); loop:key=bioskey(0);if(key==Enter){cleardevice();Initsnake();Initfood();Score=0;Hscore=1;Snkspeed=8;num=2;key=0;}else if(key==ESC) cleardevice();else goto loop;}}void Dsnkorfd(int x,int y,int color) {setcolor(color);setfillstyle(1,color);circle(x,y,10);floodfill(x,y,color);}void Delay(int times){int i;for(i=1;i<=times;i++)delay(15000);}。

贪吃蛇的c语言源程序

贪吃蛇的c语言源程序

#include<stdio.h>#include<graphics.h>#include<stdlib.h>#include<dos.h>#include<bios.h>#include<time.h>#define NULL 0#define UP 4471#define LEFT 7777#define DOWN 8051#define RIGHT 8292#define PAUSE 6512#define ESC 283#define SNAKE_COLOR 4#define SNAKE_BOND_COLOR 2#define SNAKE_STYLE LTBKSLASH_FILL #define FOOD_STYLE CLOSE_DOT_FILL #define MAP_COLOR 8#define MAP_BOND_COLOR 6#define MAP_STYLE SOLID_FILLtypedef struct Snake_Node{int x,y;struct Snake_Node *next;}Snake_Node,*P_Snake_Node;struct{int x,y,color;}Food;struct{int dx;int dy;}Direct={0,1};static int speed=1,len=4,px,py;static P_Snake_Node Head;static P_Snake_Node Map;void paint_node(int,int,int,int,int);void Put_Food(int);void Put_Snake_Node(P_Snake_Node,int); void Init();void Grow_up(int,int);void Make_Map();void Auto_Make_Map();void Load_Game();void Auto_Start();int Snake_Dead();void GO_GO_GO();void Play_Game();void Exit_Save();void Failed();void main();void paint_node(int x,int y,int color1,int color2,int style){setfillstyle(SOLID_FILL,color2);bar(x*10,479-y*10,x*10+9,479-y*10-9);setfillstyle(style,color1);bar(x*10+1,479-y*10-1,x*10+9-1,479-y*10-9+1);setfillstyle(SOLID_FILL,15);}void Put_Food(int color){randomize();Food.x=random(46)+1;Food.y=random(46)+1;Food.color=color;paint_node(Food.x,Food.y,Food.color,Food.color,FOOD_STYLE);}void Put_Snake_Node(P_Snake_Node p,int flag){if(flag)paint_node(p->x,p->y,SNAKE_COLOR,SNAKE_BOND_COLOR,SNAKE_STYLE);elsepaint_node(p->x,p->y,getbkcolor(),getbkcolor(),SOLID_FILL);}void Init(){int gdrive=VGA,gmode=VGAHI;initgraph(&gdrive,&gmode,"d:\\TC20\\turboc2");setfillstyle(XHATCH_FILL,2);bar(490,0,509,479);setfillstyle(SOLID_FILL,6);bar(480,0,489,479);setfillstyle(SOLID_FILL,15);setcolor(9);setlinestyle(CENTER_LINE,0,3);line(490,0,490,479);setcolor(3);setlinestyle(SOLID_LINE,0,3);line(509,0,509,479);line(509,479,639,479);line(639,479,639,0);line(639,0,509,0);setlinestyle(SOLID_LINE,0,0);setcolor(10);settextstyle(TRIPLEX_FONT,HORIZ_DIR,3); outtextxy(530,12,"GREEDY");outtextxy(537,40,"SNAKE");settextstyle(0,0,0);setcolor(13);outtextxy(510,80,"<<============>>"); setcolor(1);setlinestyle(CENTER_LINE,0,3);line(573,90,573,305);outtextxy(510,310,"+++++++++++++++++"); setcolor(5);settextstyle(GOTHIC_FONT,0,5);outtextxy(512,390,"~~~~~~~");outtextxy(512,392,"~~~~~~~");outtextxy(512,388,"~~~~~~~");setcolor(10);settextstyle(SANS_SERIF_FONT,1,1); outtextxy(510,115,"->");outtextxy(510,165,"<-");settextstyle(SANS_SERIF_FONT,0,1); outtextxy(512,215,"->");outtextxy(512,265,"<-");setcolor(14);settextstyle(DEFAULT_FONT,0,1); outtextxy(550,128,":W");outtextxy(550,175,":S");outtextxy(550,222,":A");outtextxy(550,272,":D");setcolor(10);settextstyle(SMALL_FONT,0,5);outtextxy(575,125,"PAUSE /");outtextxy(575,140,"CONTINUE:");outtextxy(580,250,"EXIT:");/*************/}void Grow_Up(int x,int y){P_Snake_Node p;p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=x;p->y=y;p->next=Head->next;Head->next=p;Head=p;++len;++speed;}void Auto_Make_Map(){P_Snake_Node p,q;p=q=Map=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=0;p->y=0;p->next=NULL;while(1){p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=(q->x)+1;p->y=q->y;q->next=p;p->next=NULL;q=p;if((p->x)==47) break;}while(1){p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=q->x;p->y=(q->y)+1;q->next=p;p->next=NULL;q=p;if((p->y)==47) break;}while(1){p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=(q->x)-1;p->y=q->y;q->next=p;p->next=NULL;q=p;if((p->x)==0) break;}while(1){p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=q->x;p->y=(q->y)-1;q->next=p;p->next=NULL;q=p;if((p->y)==1) break;}p=Map;while(p){paint_node(p->x,p->y,MAP_COLOR,MAP_BOND_COLOR,MAP_STYLE);p=p->next;}}void Auto_Start(){int i=1;P_Snake_Node p,q;Head=p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=24;p->y=24-3;p->next=NULL;q=p;while(i<=3){q=(P_Snake_Node)malloc(sizeof(Snake_Node));p->next=q;q->x=p->x;q->y=(p->y)+1;q->next=NULL;p=q;++i;}p->next=Head;Head=p;while(i>=1){Put_Snake_Node(p,1);p=p->next;i--;}Put_Food(14);Auto_Make_Map();}int Snake_Dead(){P_Snake_Node p;int i=1;p=Head->next->next;while(i<=len-4){if(p->x==px && p->y==py)return(1);++i;p=p->next;}p=Map;while(p){if(p->x==px && p->y==py)return(1);p=p->next;}return(0);}void GO_GO_GO(){px=(Head->x)+(Direct.dx);py=(Head->y)+(Direct.dy);if(!Snake_Dead()){if(px==Food.x&&py==Food.y){Grow_Up(px,py);Put_Snake_Node(Head,1);Put_Food(14);}else{Head=Head->next;Put_Snake_Node(Head,0);Head->x=px;Head->y=py;Put_Snake_Node(Head,1);}}elseFailed();}void Play_Game(){int wait;while(1){while(!kbhit()){GO_GO_GO();wait=0;while(wait<=2){delay(30000);++wait;}}switch(bioskey(0)){case UP:{if(Direct.dx!=0&&Direct.dy!=-1){Direct.dx=0;Direct.dy=1;}break;}case LEFT:{if(Direct.dx!=1&&Direct.dy!=0){Direct.dx=-1;Direct.dy=0;}break;}case DOWN:{if(Direct.dx!=0&&Direct.dy!=1){Direct.dx=0;Direct.dy=-1;}break;}case RIGHT:{if(Direct.dx!=-1&&Direct.dy!=0){Direct.dx=1;Direct.dy=0;}break;}case ESC:{exit(1);break;}}}}void Failed(){setcolor(4);settextstyle(TRIPLEX_FONT, HORIZ_DIR, 6);outtextxy(90,200,"GAME OVER!");getch();exit(1);/**********/ }void main(){Init();getch();Auto_Start();Play_Game();getch(); closegraph();}。

贪吃蛇游戏C语言源代码学习

贪吃蛇游戏C语言源代码学习

贪吃蛇游戏C语言源代码学习阅读学习了源代码,并做了简单的注释和修改,里面只用了链表数据结构,非常适合C语言入门者学习阅读。

程序可在VS2013下编译运行。

1 #include<stdio.h>2 #include<time.h>3 #include<windows.h>4 #include<stdlib.h>56#define U 17#define D 28#define L 39#define R 4 //蛇的状态,U:上;D:下;L:左 R:右1011 typedef struct SNAKE //蛇身的一个节点12 {13int x;14int y;15struct SNAKE *next;16 }snake;1718//全局变量//19int score = 0, add = 10;//总得分与每次吃食物得分。

20int status, sleeptime = 200;//每次运行的时间间隔21 snake *head, *food;//蛇头指针,食物指针22 snake *q;//遍历蛇的时候用到的指针23int endGamestatus = 0; //游戏结束的情况,1:撞到墙;2:咬到自己;3:主动退出游戏。

2425//声明全部函数//26void Pos();27void creatMap();28void initSnake();29int biteSelf();30void createFood();31void cantCrossWall();32void snakeMove();33void pause();34void runGame();35void initGame();36void endGame();37void gameStart();3839void Pos(int x, int y)//设置光标位置40 {41 COORD pos;42 HANDLE hOutput;43 pos.X = x;44 pos.Y = y;45 hOutput = GetStdHandle(STD_OUTPUT_HANDLE);//返回标准的输入、输出或错误的设备的句柄,也就是获得输入、输出/错误的屏幕缓冲区的句柄46 SetConsoleCursorPosition(hOutput, pos);47 }4849void creatMap()//创建地图50 {51int i;52for (i = 0; i<58; i += 2)//打印上下边框53 {54 Pos(i, 0);55 printf("■");//一个方块占两个位置56 Pos(i, 26);57 printf("■");58 }59for (i = 1; i<26; i++)//打印左右边框60 {61 Pos(0, i);62 printf("■");63 Pos(56, i);64 printf("■");65 }66 }6768void initSnake()//初始化蛇身69 {70 snake *tail;71int i;72 tail = (snake*)malloc(sizeof(snake));//从蛇尾开始,头插法,以x,y设定开始的位置//73 tail->x = 24;74 tail->y = 5;75 tail->next = NULL;76for (i = 1; i <= 4; i++)//初始长度为477 {78 head = (snake*)malloc(sizeof(snake));79 head->next = tail;80 head->x = 24 + 2 * i;81 head->y = 5;82 tail = head;83 }84while (tail != NULL)//从头到为,输出蛇身85 {86 Pos(tail->x, tail->y);87 printf("■");88 tail = tail->next;89 }90 }91//??92int biteSelf()//判断是否咬到了自己93 {94 snake *self;95 self = head->next;96while (self != NULL)97 {98if (self->x == head->x && self->y == head->y)99 {100return1;101 }102 self = self->next;103 }104return0;105 }106107void createFood()//随机出现食物108 {109 snake *food_1;110 srand((unsigned)time(NULL));//为了防止每次产生的随机数相同,种子设置为time111 food_1 = (snake*)malloc(sizeof(snake));112while ((food_1->x % 2) != 0) //保证其为偶数,使得食物能与蛇头对其113 {114 food_1->x = rand() % 52 + 2;115 }116 food_1->y = rand() % 24 + 1;117 q = head;118while (q->next == NULL)119 {120if (q->x == food_1->x && q->y == food_1->y) //判断蛇身是否与食物重合121 {122free(food_1);123 createFood();124 }125 q = q->next;126 }127 Pos(food_1->x, food_1->y);128 food = food_1;129 printf("■");130 }131132void cantCrossWall()//不能穿墙133 {134if (head->x == 0 || head->x == 56 || head->y == 0 || head->y == 26)135 {136 endGamestatus = 1;137 endGame();138 }139 }140141void snakeMove()//蛇前进,上U,下D,左L,右R142 {143 snake * nexthead;144 cantCrossWall();145146 nexthead = (snake*)malloc(sizeof(snake));147if (status == U)148 {149 nexthead->x = head->x;150 nexthead->y = head->y - 1;151if (nexthead->x == food->x && nexthead->y == food->y)//如果下一个有食物//152 {153 nexthead->next = head;154 head = nexthead;155 q = head;156while (q != NULL)157 {158 Pos(q->x, q->y);159 printf("■");160 q = q->next;161 }162 score = score + add;163 createFood();164 }165else//如果没有食物//166 {167 nexthead->next = head;168 head = nexthead;169 q = head;170while (q->next->next != NULL)171 {172 Pos(q->x, q->y);173 printf("■");174 q = q->next;175 }176 Pos(q->next->x, q->next->y);177 printf("");178free(q->next);179 q->next = NULL;180 }181 }182if (status == D)183 {184 nexthead->x = head->x;185 nexthead->y = head->y + 1;186if (nexthead->x == food->x && nexthead->y == food->y) //有食物187 {188 nexthead->next = head;189 head = nexthead;190 q = head;191while (q != NULL)192 {193 Pos(q->x, q->y);194 printf("■");195 q = q->next;196 }197 score = score + add;198 createFood();199 }200else//没有食物201 {202 nexthead->next = head;203 head = nexthead;204 q = head;205while (q->next->next != NULL)206 {207 Pos(q->x, q->y);208 printf("■");209 q = q->next;210 }211 Pos(q->next->x, q->next->y);212 printf("");213free(q->next);214 q->next = NULL;215 }216 }217if (status == L)218 {219 nexthead->x = head->x - 2;220 nexthead->y = head->y;221if (nexthead->x == food->x && nexthead->y == food->y)//有食物222 {223 nexthead->next = head;224 head = nexthead;225 q = head;226while (q != NULL)227 {228 Pos(q->x, q->y);229 printf("■");230 q = q->next;231 }232 score = score + add;233 createFood();234 }235else//没有食物236 {237 nexthead->next = head;238 head = nexthead;239 q = head;240while (q->next->next != NULL)241 {242 Pos(q->x, q->y);243 printf("■");244 q = q->next;245 }246 Pos(q->next->x, q->next->y);247 printf("");248free(q->next);249 q->next = NULL;250 }251 }252if (status == R)253 {254 nexthead->x = head->x + 2;255 nexthead->y = head->y;256if (nexthead->x == food->x && nexthead->y == food->y)//有食物257 {258 nexthead->next = head;259 head = nexthead;260 q = head;261while (q != NULL)262 {263 Pos(q->x, q->y);264 printf("■");265 q = q->next;266 }267 score = score + add;268 createFood();269 }270else//没有食物271 {272 nexthead->next = head;273 head = nexthead;274 q = head;275while (q->next->next != NULL)276 {277 Pos(q->x, q->y);278 printf("■");279 q = q->next;280 }281 Pos(q->next->x, q->next->y);282 printf("");283free(q->next);284 q->next = NULL;285 }286 }287if (biteSelf() == 1) //判断是否会咬到自己288 {289 endGamestatus = 2;290 endGame();291 }292 }293294void pause()//暂停295 {296while (1)297 {298 Sleep(300);299if (GetAsyncKeyState(VK_SPACE))300 {301break;302 }303304 }305 }306307void runGame()//控制游戏308 {309310 Pos(64, 15);311 printf("不能穿墙,不能咬到自己\n");312 Pos(64, 16);313 printf("用↑.↓.←.→分别控制蛇的移动.");314 Pos(64, 17);315 printf("F1 为加速,F2 为减速\n");316 Pos(64, 18);317 printf("ESC :退出游戏.space:暂停游戏.");318 Pos(64, 20);319 printf("C语言研究中心 ");320 status = R;321while (1)322 {323 Pos(64, 10);324 printf("得分:%d ", score);325 Pos(64, 11);326 printf("每个食物得分:%d分", add);327if (GetAsyncKeyState(VK_UP) && status != D)328 {329 status = U;330 }331else if (GetAsyncKeyState(VK_DOWN) && status != U) 332 {333 status = D;334 }335else if (GetAsyncKeyState(VK_LEFT) && status != R) 336 {337 status = L;338 }339else if (GetAsyncKeyState(VK_RIGHT) && status != L) 340 {341 status = R;342 }343else if (GetAsyncKeyState(VK_SPACE))344 {345 pause();346 }347else if (GetAsyncKeyState(VK_ESCAPE))348 {349 endGamestatus = 3;350break;351 }352else if (GetAsyncKeyState(VK_F1))353 {354if (sleeptime >= 50)355 {356 sleeptime = sleeptime - 30;357 add = add + 2;358if (sleeptime == 320)359 {360 add = 2;//防止减到1之后再加回来有错361 }362 }363 }364else if (GetAsyncKeyState(VK_F2))365 {366if (sleeptime<350)367 {368 sleeptime = sleeptime + 30;369 add = add - 2;370if (sleeptime == 350)371 {372 add = 1; //保证最低分为1373 }374 }375 }376 Sleep(sleeptime);377 snakeMove();378 }379 }380381void initGame()//开始界面382 {383 Pos(40, 12);384385 system("title C语言研究中心 ");386 printf("欢迎来到贪食蛇游戏!");387 Pos(40, 25);388 printf(" C语言研究中心 .\n"); 389 system("pause");390 system("cls");391 Pos(25, 12);392 printf("用↑.↓.←.→分别控制蛇的移动, F1 为加速,2 为减速\n");393 Pos(25, 13);394 printf("加速将能得到更高的分数。

C语言课程设计报告——贪吃蛇源程序

C语言课程设计报告——贪吃蛇源程序

C 语言课程设计(小游戏贪吃蛇得程序设计报告)设计人:班级:201年月号目录一:概述1:研究背景及意义2:设计得任务与需要知识点3:具体完成设计内容二:需求分析1:功能需求2:操作方法三:总体设计1:模块划分2:数据结构设计四:详细设计1:主空摸块设计2:绘制游戏界面3:游戏得具体过程4:游戏得结束处理5:显示排行榜信息模块五:程序得调试与测试1:动画与音乐同步2:蛇得运行3:终止程序六:结论七::结束语八:程序清单九:参考文献一. 概述本课程设计以软件工程方法为指导,采用了结构化,模块化得程序设计方法,以C语言技术为基础,使用TurboC++3、0为主要开发工具,对贪吃蛇游戏进行了需求分析,总体设计,详细设计,最终完成系统得实现与测试。

1、1 研究得背景及意义随着社会得发展,人们生活得节奏日益加快,越来越多得人加入了全球化得世界。

人们不再拘泥与一小块天地,加班,出差成了现代人不可避免得公务。

而此时一款可以随时随地娱乐得游戏成为了人们得需要。

此次课程设计完成得贪吃蛇小游戏,正就是为了满足上述需求而设计出来得。

贪吃蛇游戏虽小,却设计诸多得知识点。

通过开发贪吃蛇游戏系统,可使读者初步了解使用软件工程得与那个发,技术与工具开发软件得过程,进一步掌握结构化,模块化得程序设计方法与步骤,进一步掌握总体数据结构设计,模块划分方法,掌握局部变量,全局变量,结构体,共用体,数组,指针,文件等数据结构得使用方法,掌握图形,声音,随机数等多种库函数得使用方法,学习动画,音乐,窗口,菜单,键盘等多项编程技术,进一步学会软件调试,测试,组装等软件测试方法,为后续课程得学习与将来实际软件开发打下坚实得基础。

1、2设计得任务与需要得知识点1、2、1 课程设计主要完成得任务1)、通过编写“贪吃蛇游戏”程序,掌握结构化,模块块化程序设计得思想,培养解决实际问题得能力。

2)有同步播放动画,声音效果。

3)设计好数组元素与蛇,食物得对应关系。

贪吃蛇C语言源代码

贪吃蛇C语言源代码

#include <stdio.h>#include <stdlib.h>#include <Windows.h>//windows编程头文件#include <time.h>#include <conio.h>//控制台输入输出头文件#ifndef __cplusplustypedef char bool;#define false 0#define true 1#endif//将光标移动到控制台的(x,y)坐标点处void gotoxy(int x, int y){COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }#define SNAKESIZE 100//蛇的身体最大节数#define MAPWIDTH 78//宽度#define MAPHEIGHT 24//高度//食物的坐标struct {int x;int y;}food;//蛇的相关属性struct {int speed;//蛇移动的速度int len;//蛇的长度int x[SNAKESIZE];//组成蛇身的每一个小方块中x的坐标int y[SNAKESIZE];//组成蛇身的每一个小方块中y的坐标}snake;//绘制游戏边框void drawMap();//随机生成食物void createFood();//按键操作void keyDown();//蛇的状态bool snakeStatus();//从控制台移动光标void gotoxy(int x, int y);int key = 72;//表示蛇移动的方向,72为按下“↑”所代表的数字//用来判断蛇是否吃掉了食物,这一步很重要,涉及到是否会有蛇身移动的效果以及蛇身增长的效果int changeFlag = 0;int sorce = 0;//记录玩家的得分int i;void drawMap(){//打印上下边框for (i = 0; i <= MAPWIDTH; i += 2)//i+=2是因为横向占用的是两个位置{//将光标移动依次到(i,0)处打印上边框gotoxy(i, 0);printf("■");//将光标移动依次到(i,MAPHEIGHT)处打印下边框gotoxy(i, MAPHEIGHT);printf("■");}//打印左右边框for (i = 1; i < MAPHEIGHT; i++){//将光标移动依次到(0,i)处打印左边框gotoxy(0, i);printf("■");//将光标移动依次到(MAPWIDTH, i)处打印左边框gotoxy(MAPWIDTH, i);printf("■");}//随机生成初试食物while (1){srand((unsigned int)time(NULL));food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;//生成的食物横坐标的奇偶必须和初试时蛇头所在坐标的奇偶一致,因为一个字符占两个字节位置,若不一致//会导致吃食物的时候只吃到一半if (food.x % 2 == 0)break;}//将光标移到食物的坐标处打印食物gotoxy(food.x, food.y);printf("*");//初始化蛇的属性snake.len = 3;snake.speed = 200;//在屏幕中间生成蛇头snake.x[0] = MAPWIDTH / 2 + 1;//x坐标为偶数snake.y[0] = MAPHEIGHT / 2;//打印蛇头gotoxy(snake.x[0], snake.y[0]);printf("■");//生成初试的蛇身for (i = 1; i < snake.len; i++){//蛇身的打印,纵坐标不变,横坐标为上一节蛇身的坐标值+2snake.x[i] = snake.x[i - 1] + 2;snake.y[i] = snake.y[i - 1];gotoxy(snake.x[i], snake.y[i]);printf("■");}//打印完蛇身后将光标移到屏幕最上方,避免光标在蛇身处一直闪烁gotoxy(MAPWIDTH - 2, 0);return;}void keyDown(){int pre_key = key;//记录前一个按键的方向if (_kbhit())//如果用户按下了键盘中的某个键{fflush(stdin);//清空缓冲区的字符//getch()读取方向键的时候,会返回两次,第一次调用返回0或者224,第二次调用返回的才是实际值key = _getch();//第一次调用返回的不是实际值key = _getch();//第二次调用返回实际值}/**蛇移动时候先擦去蛇尾的一节*changeFlag为0表明此时没有吃到食物,因此每走一步就要擦除掉蛇尾,以此营造一个移动的效果*为1表明吃到了食物,就不需要擦除蛇尾,以此营造一个蛇身增长的效果*/if (changeFlag == 0){gotoxy(snake.x[snake.len - 1], snake.y[snake.len - 1]);printf(" ");//在蛇尾处输出空格即擦去蛇尾}//将蛇的每一节依次向前移动一节(蛇头除外)for (i = snake.len - 1; i > 0; i--){snake.x[i] = snake.x[i - 1];snake.y[i] = snake.y[i - 1];}//蛇当前移动的方向不能和前一次的方向相反,比如蛇往左走的时候不能直接按右键往右走//如果当前移动方向和前一次方向相反的话,把当前移动的方向改为前一次的方向if (pre_key == 72 && key == 80)key = 72;if (pre_key == 80 && key == 72)key = 80;if (pre_key == 75 && key == 77)key = 75;if (pre_key == 77 && key == 75)key = 77;/***控制台按键所代表的数字*“↑”:72*“↓”:80*“←”:75*“→”:77*///判断蛇头应该往哪个方向移动switch (key){case 75:snake.x[0] -= 2;//往左break;case 77:snake.x[0] += 2;//往右break;case 72:snake.y[0]--;//往上break;case 80:snake.y[0]++;//往下break;}//打印出蛇头gotoxy(snake.x[0], snake.y[0]);printf("■");gotoxy(MAPWIDTH - 2, 0);//由于目前没有吃到食物,changFlag值为0changeFlag = 0;return;}void createFood(){if (snake.x[0] == food.x && snake.y[0] == food.y)//蛇头碰到食物{//蛇头碰到食物即为要吃掉这个食物了,因此需要再次生成一个食物while (1){int flag = 1;srand((unsigned int)time(NULL));food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;//随机生成的食物不能在蛇的身体上for (i = 0; i < snake.len; i++){if (snake.x[i] == food.x && snake.y[i] == food.y){flag = 0;break;}}//随机生成的食物不能横坐标为奇数,也不能在蛇身,否则重新生成if (flag && food.x % 2 == 0)break;}//绘制食物gotoxy(food.x, food.y);printf("*");snake.len++;//吃到食物,蛇身长度加1sorce += 10;//每个食物得10分snake.speed -= 5;//随着吃的食物越来越多,速度会越来越快changeFlag = 1;//很重要,因为吃到了食物,就不用再擦除蛇尾的那一节,以此来造成蛇身体增长的效果}return;}bool snakeStatus(){//蛇头碰到上下边界,游戏结束if (snake.y[0] == 0 || snake.y[0] == MAPHEIGHT)return false;//蛇头碰到左右边界,游戏结束if (snake.x[0] == 0 || snake.x[0] == MAPWIDTH)return false;//蛇头碰到蛇身,游戏结束for (i = 1; i < snake.len; i++){if (snake.x[i] == snake.x[0] && snake.y[i] == snake.y[0])return false;}return true;}int main(){drawMap();while (1){keyDown();if (!snakeStatus())break;createFood();Sleep(snake.speed);}gotoxy(MAPWIDTH / 2, MAPHEIGHT / 2);printf("Game Over!\n");gotoxy(MAPWIDTH / 2, MAPHEIGHT / 2 + 1);printf("本次游戏得分为:%d\n", sorce);Sleep(5000);return 0;}。

贪吃蛇源代码(需要easy x,vc6.0可以成功编译运行)

贪吃蛇源代码(需要easy x,vc6.0可以成功编译运行)

#include <graphics.h>#include <stdlib.h>#include <time.h>//#include <dos.h>#include <conio.h>#include <stdio.h>//#include <winnt.h>#define MAX_JOINTS 200#define LEFT 0x4b00#define RIGHT 0x4d00#define DOWN 0x5000#define UP 0x4800#define ESC 0x011b#define MV_RIGHT 1#define MV_LEFT 2#define MV_UP 3#define MV_DOWN 4void InitGraph(void); /*图形驱动初始化函数*/void DrawFence(void); /*绘制游戏场景*/void GameOver(int score); /*结束游戏*/void GamePlay(void); /*玩游戏具体过程*/void PrScore(int score); /*输出成绩*/struct Food /*食物的结构体定义*/{int x; /*食物的横坐标*/int y; /*食物的纵坐标*/int addFood; /*判断是否要出现食物的变量*/};struct Snake /*蛇的结构体定义*/{int x[MAX_JOINTS]; /*保存蛇身每一节位于屏幕上的列坐标*/ int y[MAX_JOINTS]; /*保存蛇身每一节位于屏幕上的行坐标*/ int joint; /*蛇的节数*/int direction; /*蛇移动方向*/int life; /*蛇的生命,0活着,1死亡*/};/*主函数*/void main(void){InitGraph(); /*图形驱动*/DrawFence(); /*游戏场景*/GamePlay(); /*玩游戏具体过程*/closegraph(); /*图形结束*/}/*图形驱动初始化函数*/void InitGraph(void){int gd = DETECT, gm;initgraph(&gd, &gm, "");cleardevice();setbkcolor(BLUE);cleardevice();setcolor(WHITE);//settextstyle(DEFAULT_FONT, HORIZ_DIR, 3);setfont(32, 0, "宋体");outtextxy(170, 150, "Greedy Snake");outtextxy(219, 254, "Ready?");setcolor(BLUE);cleardevice();}/*游戏开始画面,左上角坐标为(50,40),右下角坐标为(610,460)的围墙*/ void DrawFence(void){int i;setbkcolor(LIGHTGREEN);setcolor(11);//setlinestyle(SOLID_LINE, 0, THICK_WIDTH);setlinestyle(PS_SOLID, 0, 3);/*画围墙*/for (i=50; i<=600; i+=10){rectangle(i, 40, i+10, 49); /*上边*/rectangle(i, 451, i+10, 460); /*下边*/}for (i=40; i<=450; i+=10){rectangle(50, i, 59, i+10); /*左边*/rectangle(601, i, 610, i+10); /*右边*/}}/*控制贪吃蛇吃食物*/void GamePlay(void){int i, key;//int gamespeed = 22000; /*控制游戏速度*/int gamespeed = 200;int score = 0; /*记录游戏得分*/struct Food food; /*食物结构体变量*/struct Snake snake; /*蛇结构体变量*/food.addFood = 1; /*1表示需要出现新食物,0表示已经存在食物*/ snake.life = 0; /*置蛇的生命状态为活着*/snake.direction = MV_RIGHT; /*置蛇头方向往右*/snake.x[0] = 100; snake.y[0] = 100; /*置蛇头初始位置*/snake.x[1] = 110; snake.y[1] = 100;snake.joint = 2; /*置蛇的初始节数为2*/PrScore(score); /*显示游戏得分*//*重复玩游戏,直到按Esc键结束*/srand(time(NULL));while (1){while (!kbhit())/*在没有按键的情况下,蛇自己移动身体*/{if (food.addFood == 1) /*需要出现新食物*/{food.x = rand() % 400 + 60;food.y = rand() % 350 + 60;/*食物出现后必须在整格内才能让蛇吃到*/while (food.x%10 != 0){food.x++;}while (food.y%10 != 0){food.y++;}food.addFood = 0; /*画面上有食物*/}if (food.addFood == 0) /*画面上有食物,则显示*/{setcolor(GREEN);rectangle(food.x, food.y, food.x+10, food.y-10);}for (i=snake.joint-1; i>0; i--) /*蛇的每个节往前移动*/{snake.x[i] = snake.x[i-1];snake.y[i] = snake.y[i-1];}/*1,2,3,4 表示右,左,上,下四个方向,来决定蛇头的移动*/switch(snake.direction){case MV_RIGHT: snake.x[0] += 10; break;case MV_LEFT: snake.x[0] -= 10; break;case MV_UP: snake.y[0] -= 10; break;case MV_DOWN: snake.y[0] += 10; break;}/*从蛇的第四节开始判断是否撞到自己,因为蛇头为两节,第三节不可能拐过来*/for (i=3; i<snake.joint; i++){if (snake.x[i]==snake.x[0] && snake.y[i]==snake.y[0]){GameOver(score); /*显示失败*/snake.life = 1; /*蛇死*/break;}}/*判断蛇是否撞到墙壁*/if (snake.x[0]<55 || snake.x[0]>595|| snake.y[0]<55 || snake.y[0]>455){GameOver(score); /*本次游戏结束*/snake.life = 1; /*蛇死*/}/*以上两种判断以后,如果蛇死就跳出内循环,重新开始*/if (snake.life == 1) break;if (snake.x[0]==food.x && snake.y[0]==food.y) /*吃到食物后*/{/*把画面上的食物清除*/setcolor(0);rectangle(food.x, food.y, food.x+10, food.y-10);/*新的一节先放在看不见的位置,下次循环就取前一节的位置*/snake.x[snake.joint] =-20; snake.y[snake.joint] =-20;snake.joint++; /*蛇的身体长一节*/food.addFood = 1; /*画面上需要出现新食物*/score += 10;PrScore(score); /*输出新得分*/}/*画蛇*/setcolor(4);for (i=0; i<snake.joint; i++){rectangle(snake.x[i], snake.y[i],snake.x[i]+10, snake.y[i]-10);}//delay(gamespeed); /*延时控制蛇的速度*/Sleep(gamespeed);/*去除蛇的最后一节*/setcolor(BLUE);rectangle(snake.x[snake.joint-1], snake.y[snake.joint-1],snake.x[snake.joint-1]+10,snake.y[snake.joint-1]-10);} /*end of while(!kbhit)*/if (snake.life == 1) break; /*如果蛇死,则跳出循环*///key = bioskey(0); /*接收按键*/key = getch();/*if (kbhit()){key = getch();}*//*判断按键,是否往相反方向移动,按Esc键则退出*/ /* if (key == ESC) break;else if (key==UP && snake.direction!=4)snake.direction = MV_UP;else if (key==RIGHT && snake.direction!= MV_LEFT)snake.direction = MV_RIGHT;else if (key==LEFT && snake.direction!= MV_RIGHT)snake.direction = MV_LEFT;else if (key==DOWN && snake.direction!= MV_UP)snake.direction = MV_DOWN;*/if (key == ESC) break;else if (key=='W' && snake.direction!=4)snake.direction = MV_UP;else if (key=='D' && snake.direction!= MV_LEFT)snake.direction = MV_RIGHT;else if (key=='A' && snake.direction!= MV_RIGHT)snake.direction = MV_LEFT;else if (key=='S' && snake.direction!= MV_UP)snake.direction = MV_DOWN;} /*end of while(1)*/ }/*结束游戏*/void GameOver(int score){cleardevice();PrScore(score);setcolor(RED);//settextstyle(0, 0, 4);setfont(60, 0,"黑体");outtextxy(200, 200, "GAME OVER");getch();}/*输出成绩*/void PrScore(int score){char str[10];setfillstyle(SOLID_FILL, YELLOW);bar(50, 15, 220, 35);setcolor(6);//settextstyle(0, 0, 2);setfont(16, 0,"宋体");sprintf(str, "score:%d", score);outtextxy(55, 20, str);}。

贪吃蛇程序

贪吃蛇程序

贪吃蛇程序游戏说明:1、在英文状态下用w、a、s、d键操纵蛇头上下左右移动。

2、操控蛇头吃到食物时蛇长便增加1。

3、蛇头不能碰到四周墙壁和自己身体。

4、当蛇身长度达到45时(可自行调节),游戏成功。

源代码:(可直接复制到VC6.0里运行程序)#include <iostream.h> //标准输入输出流#include <windows.h> //win32下的函数#include <stdlib.h> //常用系统函数,此处产生随机数#include <conio.h> //控制台输入输出函数#include <time.h> //时间函数,使用当前时间做种子enum dir{up,down,left,right}; //枚举类型enum dir// 1、围墙的制作class Fence //定义出一个类:围墙{public:void InitFence(); //定义边界函数的组成void OutputF(); //输出边界函数public:char game[30][30]; //game定义为游戏框,注意类型为字符}f; //定义对象//画框框void Fence::InitFence(){for(int i=0;i<21;i++)for(int j=0;j<25;j++){if(i==0||i==20||j==0||j==24) game[i][j]= '*'; //画出边框else game[i][j]= ' '; //将内部点设置为空}}//显示框框void Fence::OutputF(){for(int i=0; i<21; i++){for(int j=0; j<25; j++){cout<<game[i][j]<<' ';}cout<<endl;}}// 2、蛇结点的构建class SnakeNode{private:int x,y;SnakeNode *prior,*next;public:void add_head(int x,int y);int get_x();int get_y();void delete_tail();}*head=NULL, *tail =NULL;void SnakeNode::add_head(int x,int y) //定义插入头结点函数{SnakeNode *q=new SnakeNode;q->x =x; q->y =y;q->next =head;q->prior =NULL;if(head) head->prior =q;head =q;if(!tail) tail =head;f.game[x][y]= '*'; //f对象可以在定义Fence类时定义; 且Fence类在SnakeNode 类前定义}int SnakeNode::get_x(){return x;}int SnakeNode::get_y(){return y;}void SnakeNode::delete_tail() //定义删除尾结点函数{SnakeNode *p =tail;f.game[tail->get_x()][tail->get_y()]= ' '; //把尾结点的坐标表示的'*'置为空格if(tail==head) tail= head= NULL;else{tail= tail->prior;tail->next= NULL;}delete p;}// 3、定义移动class move{public:dir point; //枚举变量point: 控制方向int food_x;int food_y;public:void moving();void change_point(char); //改变方向void get_food();};void move::moving() //对类中moving函数定义{int a,b;a= head->get_x(); //取得头结点横坐标b= head->get_y(); //头结点纵坐标switch(point){case up: --a; break;case down: ++a; break;case left: --b; break;case right: ++b; break;}if(a==20||b==24||a==0||b==0) //判断是否撞墙{cout<<"game over!!!"<<endl;exit(0);}if(a==food_x && b==food_y) //吃food{head->add_head(a,b);get_food();}else{if(f.game[a][b]=='*'){cout<<"game over!!!"<<endl;exit(0);}else{head->add_head(a,b); //插入头结点head->delete_tail(); //删除尾结点}}}void move::change_point(char keydown) //定义改变方向函数{switch(keydown){case 'w': point= up; break;case 's': point= down; break;case 'a': point= left; break;case 'd': point= right; break;}}void move::get_food() //定义得到食物函数{for(int v=0;;v++){srand((unsigned int) time(NULL)); //做种子(程序运行时间)food_x= rand()%19+1;food_y= rand()%23+1;if(f.game[food_x][food_y]!='*'){f.game[food_x][food_y]= '@';break;}else continue;}}//主函数int main(){cout<<"Using 'w,s,a,d'to control direction!!!\n";//画框框和小蛇move m;f.InitFence();head->add_head(4,3);head->add_head(4,4);head->add_head(4,5);m.get_food();f.OutputF();while (true){char keydown= getch(); //getch()返回键盘上读取的字符;包含头文件<conio.h>m.change_point(keydown);while(!kbhit()){ //判断有没有按键落下;system("cls"); //清屏函数;m.moving();f.OutputF();Sleep(200);}}return 0;}游戏截图:。

JAVA程序源代码(贪吃蛇)

JAVA程序源代码(贪吃蛇)

贪吃蛇源代码将Location、LocationRO、SnakeFrame、SnakeModel、SnakePanel放到命名为snake的文件夹里,主函数MainApp放到外面运行主函数即可实现。

主函数package snake;import javax.swing.*;import snake.*;public class MainApp {public static void main(String[] args) {JFrame.setDefaultLookAndFeelDecorated(true);SnakeFrame frame=new SnakeFrame();frame.setSize(350,350);frame.setResizable(false);frame.setLocation(330,220);frame.setTitle("贪吃蛇");frame.setVisible(true);}}package snake;public class Location {private int x;private int y;Location(int x,int y){this.x=x;this.y=y;}int getX(){return x;}int getY(){return y;}void setX(int x){this.x=x;}void setY(int y){this.y=y;}public boolean equalOrRev(Location e){return ((e.getX()==getX())&&(e.getY()==getY()))||((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}public boolean equals(Location e){return(e.getX()==getX())&&(e.getY()==getY());}public boolean reverse(Location e){return ((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}}package snake;public class LocationRO{private int x;private int y;LocationRO(int x,int y){this.x=x;this.y=y;}int getX(){return x;}int getY(){return y;}public boolean equalOrRev(LocationRO e){return ((e.getX()==getX())&&(e.getY()==getY()))||((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}public boolean equals(LocationRO e){return(e.getX()==getX())&&(e.getY()==getY());}public boolean reverse(LocationRO e){return ((e.getX()==getX())&&(e.getY()==-1*getY()))||((e.getX()==-1*getX())&&(e.getY()==getY()));}}package snake;import java.awt.*;import java.awt.event.*;import javax.swing.*;class SnakeFrame extends JFrame implements ActionListener{final SnakePanel p=new SnakePanel(this);JMenuBar menubar=new JMenuBar();JMenu fileMenu=new JMenu("文件");JMenuItem newgameitem=new JMenuItem("开始");JMenuItem stopitem=new JMenuItem("暂停");JMenuItem runitem=new JMenuItem("继续");JMenuItem exititem=new JMenuItem("退出");//"设置"菜单JMenu optionMenu=new JMenu("设置");//等级选项ButtonGroup groupDegree = new ButtonGroup();JRadioButtonMenuItem oneItem= new JRadioButtonMenuItem("初级");JRadioButtonMenuItem twoItem= new JRadioButtonMenuItem("中级");JRadioButtonMenuItem threeItem= new JRadioButtonMenuItem("高级");JMenu degreeMenu=new JMenu("等级");JMenu helpMenu=new JMenu("帮助");JMenuItem helpitem=new JMenuItem("操作指南");final JCheckBoxMenuItem showGridItem = new JCheckBoxMenuItem("显示网格");JLabel scorelabel;public JTextField scoreField;private long speedtime=200;private String helpstr = "游戏说明:\n1 :方向键控制蛇移动的方向."+"\n2 :单击菜单'文件->开始'开始游戏."+"\n3 :单击菜单'文件->暂停'或者单击键盘空格键暂停游戏."+"\n4 :单击菜单'文件->继续'继续游戏."+"\n5 :单击菜单'设置->等级'可以设置难度等级."+"\n6 :单击菜单'设置->显示网格'可以设置是否显示网格."+ "\n7 :红色为食物,吃一个得10分同时蛇身加长."+"\n8 :蛇不可以出界或自身相交,否则结束游戏.";SnakeFrame(){setJMenuBar(menubar);fileMenu.add(newgameitem);fileMenu.add(stopitem);fileMenu.add(runitem);fileMenu.add(exititem);menubar.add(fileMenu);oneItem.setSelected(true);groupDegree.add(oneItem);groupDegree.add(twoItem);groupDegree.add(threeItem);degreeMenu.add(oneItem);degreeMenu.add(twoItem);degreeMenu.add(threeItem);optionMenu.add(degreeMenu);// 风格选项showGridItem.setSelected(true);optionMenu.add(showGridItem);menubar.add(optionMenu);helpMenu.add(helpitem);menubar.add(helpMenu);Container contentpane=getContentPane();contentpane.setLayout(new FlowLayout());contentpane.add(p);scorelabel=new JLabel("得分: ");scoreField=new JTextField("0",15);scoreField.setEnabled(false);scoreField.setHorizontalAlignment(0);JPanel toolPanel=new JPanel();toolPanel.add(scorelabel);toolPanel.add(scoreField);contentpane.add(toolPanel);oneItem.addActionListener(this);twoItem.addActionListener(this);threeItem.addActionListener(this);newgameitem.addActionListener(this);stopitem.addActionListener(this);runitem.addActionListener(this);exititem.addActionListener(this);helpitem.addActionListener(this);showGridItem.addActionListener(this);}public void actionPerformed(ActionEvent e){try{if(e.getSource()==helpitem){JOptionPane.showConfirmDialog(p,helpstr,"操纵说明",JOptionPane.PLAIN_MESSAGE);}else if(e.getSource()==exititem)System.exit(0);else if(e.getSource()==newgameitem)p.newGame(speedtime);else if(e.getSource()==stopitem)p.stopGame();else if(e.getSource()==runitem)p.returnGame();else if(e.getSource()==showGridItem){if(!showGridItem.isSelected()){p.setBackground(Color.lightGray);}else{p.setBackground(Color.darkGray);}}else if(e.getSource()==oneItem) speedtime=200;else if(e.getSource()==twoItem) speedtime=100;else if(e.getSource()==threeItem) speedtime=50;}catch(Exception ee){ee.printStackTrace();}}}package snake;import java.util.*;import javax.swing.JOptionPane;public class SnakeModel {private int rows,cols;//行列数private Location snakeHead,runingDiriction;//运行方向private LocationRO[][] locRO;//LocationRO类数组private LinkedList snake,playBlocks;//蛇及其它区域块private LocationRO snakeFood;//目标食物private int gameScore=0; //分数private boolean AddScore=false;//加分// 获得蛇头public LocationRO getSnakeHead(){return (LocationRO)(snake.getLast());}//蛇尾public LocationRO getSnakeTail(){return (LocationRO)(snake.getFirst());}//运行路线public Location getRuningDiriction(){return runingDiriction;}//获得蛇实体区域public LinkedList getSnake(){return snake;}//其他区域public LinkedList getOthers(){return playBlocks;}//获得总分public int getScore(){return gameScore;}//获得增加分数public boolean getAddScore(){return AddScore;}//设置蛇头方向private void setSnakeHead(Location snakeHead){ this.snakeHead=snakeHead;}//获得目标食物public LocationRO getSnakeFood(){return snakeFood;}//随机设置目标食物private void setSnakeFood(){snakeFood=(LocationRO)(playBlocks.get((int)(Math.random()*playBlocks.size()))); }//移动private void moveTo(Object a,LinkedList fromlist,LinkedList tolist){fromlist.remove(a);tolist.add(a);}//初始设置public void init(){playBlocks.clear();snake.clear();gameScore=0;for(int i=0;i<rows;i++){for(int j=0;j<cols;j++){playBlocks.add(locRO[i][j]);}}//初始化蛇的形状for(int i=4;i<7;i++){moveTo(locRO[4][i],playBlocks,snake);}//蛇头位置snakeHead=new Location(4,6);//设置随机块snakeFood=new LocationRO(0,0);setSnakeFood();//初始化运动方向runingDiriction=new Location(0,1);}//Snake构造器public SnakeModel(int rows1,int cols1){rows=rows1;cols=cols1;locRO=new LocationRO[rows][cols];snake=new LinkedList();playBlocks=new LinkedList();for(int i=0;i<rows;i++){for(int j=0;j<cols;j++){locRO[i][j]=new LocationRO(i,j);}}init();}/**定义布尔型move方法,如果运行成功则返回true,否则返回false*参数direction是Location类型,*direction 的值:(-1,0)表示向上;(1,0)表示向下;*(0,-1)表示向左;(0,1)表示向右;**/public boolean move(Location direction){//判断设定的方向跟运行方向是不是相反if (direction.reverse(runingDiriction)){snakeHead.setX(snakeHead.getX()+runingDiriction.getX());snakeHead.setY(snakeHead.getY()+runingDiriction.getY());}else{snakeHead.setX(snakeHead.getX()+direction.getX());snakeHead.setY(snakeHead.getY()+direction.getY());}//如果蛇吃到了目标食物try{if ((snakeHead.getX()==snakeFood.getX())&&(snakeHead.getY()==snakeFood.getY())){moveTo(locRO[snakeHead.getX()][snakeHead.getY()],playBlocks,snake);setSnakeFood();gameScore+=10;AddScore=true;}else{AddScore=false;//是否出界if((snakeHead.getX()<rows)&&(snakeHead.getY()<cols)&&(snakeHead.getX()>=0&&(snak eHead.getY()>=0))){//如果不出界,判断是否与自身相交if(snake.contains(locRO[snakeHead.getX()][snakeHead.getY()])){//如果相交,结束游戏JOptionPane.showMessageDialog(null, "Game Over!", "游戏结束",RMA TION_MESSAGE);return false;}else{//如果不相交,就把snakeHead加到snake里面,并且把尾巴移出moveTo(locRO[snakeHead.getX()][snakeHead.getY()],playBlocks,snake);moveTo(snake.getFirst(),snake,playBlocks);}}else{//出界,游戏结束JOptionPane.showMessageDialog(null, "Game Over!", "游戏结束", RMA TION_MESSAGE);return false;}}}catch(ArrayIndexOutOfBoundsException e){return false;}//设置运行方向if (!(direction.reverse(runingDiriction)||direction.equals(runingDiriction))){runingDiriction.setX(direction.getX());runingDiriction.setY(direction.getY());}return true;}}package snake;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.util.*;public class SnakePanel extends JPanel implements Runnable,KeyListener{JFrame parent=new JFrame();private int row=20; //网格行数private int col=30; //列数private JPanel[][] gridsPanel; //面板网格private Location direction;//方向定位private SnakeModel snake; //贪吃蛇private LinkedList snakeBody; //蛇的身体private LinkedList otherBlocks; //其他区域private LocationRO snakeHead; //蛇的头部private LocationRO snakeFood; //目标食物private Color bodyColor=Color.orange;//蛇的身体颜色private Color headColor=Color.black; //蛇的头部颜色private Color foodColor=Color.red; //目标食物颜色private Color othersColor=Color.lightGray;//其他区域颜色private int gameScore=0; //总分private long speed; //速度(难度设置)private boolean AddScore; //加分private Thread t; //线程private boolean isEnd; //暂停private static boolean notExit;// 构造器,初始化操作public SnakePanel(SnakeFrame parent){this.parent=parent;gridsPanel=new JPanel[row][col];otherBlocks=new LinkedList();snakeBody=new LinkedList();snakeHead=new LocationRO(0,0);snakeFood=new LocationRO(0,0);direction=new Location(0,1);// 布局setLayout(new GridLayout(row,col,1,1));for(int i=0;i<row;i++){for(int j=0;j<col;j++){gridsPanel[i][j]=new JPanel();gridsPanel[i][j].setBackground(othersColor);add(gridsPanel[i][j]);}}addKeyListener(this);}// 开始游戏public void newGame(long speed){this.speed=speed;if (notExit) {snake.init();}else{snake=new SnakeModel(row,col);notExit=true;t=new Thread(this);t.start();}requestFocus();direction.setX(0);direction.setY(1);gameScore=0;updateTextFiled(""+gameScore);isEnd=false;}// 暂停游戏public void stopGame(){requestFocus();isEnd=true;}// 继续public void returnGame(){requestFocus();isEnd=false;}// 获得总分public int getGameScore(){return gameScore;}//更新总分private void updateTextFiled(String str){((SnakeFrame)parent).scoreField.setText(str); }//更新各相关单元颜色private void updateColors(){// 设定蛇身颜色snakeBody=snake.getSnake();Iterator i =snakeBody.iterator();while(i.hasNext()){LocationRO t=(LocationRO)(i.next());gridsPanel[t.getX()][t.getY()].setBackground(bodyColor);}//设定蛇头颜色snakeHead=snake.getSnakeHead();gridsPanel[snakeHead.getX()][snakeHead.getY()].setBackground(headColor);//设定背景颜色otherBlocks=snake.getOthers();i =otherBlocks.iterator();while(i.hasNext()){LocationRO t=(LocationRO)(i.next());gridsPanel[t.getX()][t.getY()].setBackground(othersColor);}//设定临时块的颜色snakeFood=snake.getSnakeFood();gridsPanel[snakeFood.getX()][snakeFood.getY()].setBackground(foodColor); }public boolean isFocusTraversable(){return true;}//实现Runnable接口public void run(){while(true){try{Thread.sleep(speed);}catch (InterruptedException e){}if(!isEnd){isEnd=!snake.move(direction);updateColors();if(snake.getAddScore()){gameScore+=10;updateTextFiled(""+gameScore);}}}}//实现KeyListener接口public void keyPressed(KeyEvent event){int keyCode = event.getKeyCode();if(notExit){if (keyCode == KeyEvent.VK_LEFT) { //向左direction.setX(0);direction.setY(-1);}else if (keyCode == KeyEvent.VK_RIGHT) { //向右direction.setX(0);direction.setY(1);}else if (keyCode == KeyEvent.VK_UP) { //向上direction.setX(-1);direction.setY(0);}else if (keyCode == KeyEvent.VK_DOWN) { //向下direction.setX(1);direction.setY(0);}else if (keyCode == KeyEvent.VK_SPACE){ //空格键isEnd=!isEnd;}}}public void keyReleased(KeyEvent event){}public void keyTyped(KeyEvent event){}。

JAVA小程序—贪吃蛇源代码

JAVA小程序—贪吃蛇源代码

JAVA贪吃蛇源代码SnakeGame.javapackage SnakeGame;import javax.swing.*;public class SnakeGame{public static void main( String[] args ){JDialog.setDefaultLookAndFeelDecorated( true ); GameFrame temp = new GameFrame();}}Snake.javapackage SnakeGame;import java.awt.*;import java.util.*;class Snake extends LinkedList{public int snakeDirection = 2;public int snakeReDirection = 4;public Snake(){this.add( new Point( 3, 3 ) );this.add( new Point( 4, 3 ) );this.add( new Point( 5, 3 ) );this.add( new Point( 6, 3 ) );this.add( new Point( 7, 3 ) );this.add( new Point( 8, 3 ) );this.add( new Point( 9, 3 ) );this.add( new Point( 10, 3 ) );}public void changeDirection( Point temp, int direction ) {this.snakeDirection = direction;switch( direction ){case 1://upthis.snakeReDirection = 3;this.add( new Point( temp.x, temp.y - 1 ) );break;case 2://rightthis.snakeReDirection = 4;this.add( new Point( temp.x + 1, temp.y ) );break;case 3://downthis.snakeReDirection = 1;this.add( new Point( temp.x, temp.y + 1 ) );break;case 4://leftthis.snakeReDirection = 2;this.add( new Point( temp.x - 1, temp.y ) );break;}}public boolean checkBeanIn( Point bean ){Point temp = (Point) this.getLast();if( temp.equals( bean ) ){return true;}return false;}public void removeTail(){this.remove( 0 );}public void drawSnake( Graphics g, int singleWidthX, int singleHeightY, int cooPos ) {g.setColor( ColorGroup.COLOR_SNAKE );Iterator snakeSq = this.iterator();while ( snakeSq.hasNext() ){Point tempPoint = (Point)snakeSq.next();this.drawSnakePiece( g, tempPoint.x, tempPoint.y,singleWidthX, singleHeightY, cooPos );}}public void drawSnakePiece( Graphics g, int temp1, int temp2,int singleWidthX, int singleHeightY, int cooPos ){g.fillRoundRect( singleWidthX * temp1 + 1,singleHeightY * temp2 + 1,singleWidthX - 2,singleHeightY - 2,cooPos,cooPos );}public void clearEndSnakePiece( Graphics g, int temp1, int temp2, int singleWidthX, int singleHeightY, int cooPos ){g.setColor( ColorGroup.COLOR_BACK );g.fillRoundRect( singleWidthX * temp1 + 1,singleHeightY * temp2 + 1,singleWidthX - 2,singleHeightY - 2,cooPos,cooPos );}}GameFrame.javapackage SnakeGame;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;import java.awt.geom.*;class GameFrame extends JFrame{private Toolkit tempKit;private int horizontalGrid, verticalGrid;private int singleWidthX, singleHeightY;private int cooPos;private Snake mainSnake;private LinkedList eatedBean;{eatedBean = new LinkedList();}private Iterator snakeSq;public javax.swing.Timer snakeTimer;private int direction = 2;private int score;private String info;private Point bean, eatBean;{bean = new Point();}private boolean flag;private JMenuBar infoMenu;private JMenu[] tempMenu;private JMenuItem[] tempMenuItem;private JRadioButtonMenuItem[] levelMenuItem, versionMenuItem;private JLabel scoreLabel;{scoreLabel = new JLabel();}private Graphics2D g;private ImageIcon snakeHead;{snakeHead = new ImageIcon( "LOGO.gif" );}private ConfigMenu configMenu;private boolean hasStoped = true;public GameFrame(){this.tempKit = this.getToolkit();this.setSize( tempKit.getScreenSize() );this.setGrid( 60, 40, 5 );this.getContentPane().setBackground( ColorGroup.COLOR_BACK );this.setUndecorated( true );this.setResizable( false );this.addKeyListener( new KeyHandler() );GameFrame.this.snakeTimer = new javax.swing.Timer( 80, new TimerHandler() ); this.getContentPane().add( scoreLabel, BorderLayout.SOUTH );this.scoreLabel.setFont( new Font( "Fixedsys", Font.BOLD, 15 ) );this.scoreLabel.setText( "Pause[SPACE] - Exit[ESC]" );this.configMenu = new ConfigMenu( this );this.setVisible( true );}public void setGrid( int temp1, int temp2, int temp3 ){this.horizontalGrid = temp1;this.verticalGrid = temp2;this.singleWidthX = this.getWidth() / temp1;this.singleHeightY = this.getHeight() / temp2;this.cooPos = temp3;}private class KeyHandler extends KeyAdapter{public void keyPressed( KeyEvent e ){if( e.getKeyCode() == 27 ){snakeTimer.stop();if( JOptionPane.showConfirmDialog( null, "Are you sure to exit?" ) == 0 ) {System.exit( 0 );}snakeTimer.start();}else if( e.getKeyCode() == 37 && mainSnake.snakeDirection != 2 )//left {direction = 4;}else if( e.getKeyCode() == 39 && mainSnake.snakeDirection != 4 )//right {direction = 2;}else if( e.getKeyCode() == 38 && mainSnake.snakeDirection != 3 )//up {direction = 1;}else if( e.getKeyCode() == 40 && mainSnake.snakeDirection != 1 )//down {direction = 3;}else if( e.getKeyCode() == 32 ){if( !hasStoped ){if( !flag ){snakeTimer.stop();configMenu.setVisible( true );configMenu.setMenuEnable( false );flag = true;}else{snakeTimer.start();configMenu.setVisible( false );configMenu.setMenuEnable( true );flag = false;}}}}}private class TimerHandler implements ActionListener{public synchronized void actionPerformed( ActionEvent e ){Point temp = (Point) mainSnake.getLast();snakeSq = mainSnake.iterator();while ( snakeSq.hasNext() ){Point tempPoint = (Point)snakeSq.next();if( temp.equals( tempPoint ) && snakeSq.hasNext() != false ){snakeTimer.stop();stopGame();JOptionPane.showMessageDialog( null,"Your Score is " + score + "&#92;n&#92;nYou Loss!" );}}System.out.println( temp.x + " " + temp.y );if( (temp.x == 0 && direction == 4) ||(temp.x == horizontalGrid-1 && direction == 2) ||(temp.y == 0 && direction == 1) ||(temp.y == verticalGrid-1 && direction == 3) ){snakeTimer.stop();stopGame();JOptionPane.showMessageDialog( null,"Your Score is " + score + "&#92;n&#92;nYou Loss!" );}if( direction != mainSnake.snakeReDirection ){moveSnake( direction );}mainSnake.drawSnake( getGraphics(), singleWidthX, singleHeightY, cooPos ); drawBeanAndEBean( getGraphics() );}}public void stopGame(){this.hasStoped = true;this.snakeTimer.stop();Graphics2D g = (Graphics2D) GameFrame.this.getGraphics();g.setColor( ColorGroup.COLOR_BACK );super.paint( g );configMenu.setVisible( true );}public void resetGame(){System.gc();this.hasStoped = false;Graphics2D g = (Graphics2D) GameFrame.this.getGraphics();g.setColor( ColorGroup.COLOR_BACK );super.paint( g );this.mainSnake = new Snake();this.createBean( bean );this.eatedBean.clear();mainSnake.drawSnake( getGraphics(), singleWidthX, singleHeightY, cooPos ); this.snakeTimer.start();this.direction = 2;this.score = 0;this.scoreLabel.setText( "Pause[SPACE] - Exit[ESC]" );}private void moveSnake( int direction ){if( mainSnake.checkBeanIn( this.bean ) ){this.score += 100;this.scoreLabel.setText( + " Current Score:" + this.score );this.eatedBean.add( new Point(this.bean) );this.createBean( this.bean );}mainSnake.changeDirection( (Point) mainSnake.getLast(), direction );Point temp = (Point) mainSnake.getFirst();if( eatedBean.size() != 0 ){if( eatedBean.getFirst().equals( temp ) ){eatedBean.remove( 0 );}else{mainSnake.clearEndSnakePiece( getGraphics(), temp.x, temp.y, singleWidthX, singleHeightY, cooPos );mainSnake.removeTail();}}else{mainSnake.clearEndSnakePiece( getGraphics(), temp.x, temp.y, singleWidthX, singleHeightY, cooPos );mainSnake.removeTail();}}private void drawBeanAndEBean( Graphics g ){g.setColor( ColorGroup.COLOR_BEAN );this.drawPiece( g, this.bean.x, this.bean.y );g.setColor( ColorGroup.COLOR_EATEDBEAN );snakeSq = eatedBean.iterator();while ( snakeSq.hasNext() ){Point tempPoint = (Point)snakeSq.next();this.drawPiece( g, tempPoint.x, tempPoint.y );}}private void drawPiece( Graphics g, int x, int y ){g.fillRoundRect( this.singleWidthX * x + 1,this.singleHeightY * y + 1,this.singleWidthX - 2,this.singleHeightY - 2,this.cooPos,this.cooPos );}private void createBean( Point temp ){LP:while( true ){temp.x = (int) (Math.random() * this.horizontalGrid);temp.y = (int) (Math.random() * this.verticalGrid);snakeSq = mainSnake.iterator();while ( snakeSq.hasNext() ){if( snakeSq.next().equals( new Point( temp.x, temp.y ) ) ){continue LP;}}break;}}}ConfigMenu.javapackage SnakeGame;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class ConfigMenu extends JMenuBar{GameFrame owner;JMenu[] menu;JMenuItem[] menuItem;JRadioButtonMenuItem[] speedItem, modelItem, standardItem; private UIManager.LookAndFeelInfo looks[];public ConfigMenu( GameFrame owner ){this.owner = owner;owner.setJMenuBar( this );String[] menu_name = {"Snake Game", "Game Configure", "Game Help"}; menu = new JMenu[menu_name.length];for( int i = 0; i < menu_name.length; i++ ){menu[i] = new JMenu( menu_name[i] );menu[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );this.add( menu[i] );}String[] menuItem_name = {"Start Game", "Stop Game", "Exit Game", "Game Color","About..."};menuItem = new JMenuItem[menuItem_name.length];for( int i = 0; i < menuItem_name.length; i++ ){menuItem[i] = new JMenuItem( menuItem_name[i] );menuItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) ); menuItem[i].addActionListener( new ActionHandler() );}menu[0].add( menuItem[0] );menu[0].add( menuItem[1] );menu[0].addSeparator();menu[0].add( menuItem[2] );menu[1].add( menuItem[3] );menu[2].add( menuItem[4] );String[] inner_menu_name = {"Game Speed", "Window Model", "Game Standard "}; JMenu[] inner_menu = new JMenu[inner_menu_name.length];for( int i = 0; i < inner_menu_name.length; i++ ){inner_menu[i] = new JMenu( inner_menu_name[i] );inner_menu[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );menu[1].add( inner_menu[i] );}ButtonGroup temp1 = new ButtonGroup();String[] speedItem_name = {"Speed-1", "Speed-2", "Speed-3", "Speed-4", "Speed-5"}; speedItem = new JRadioButtonMenuItem[speedItem_name.length];for( int i = 0; i < speedItem_name.length; i++ ){speedItem[i] = new JRadioButtonMenuItem( speedItem_name[i] );inner_menu[0].add( speedItem[i] );speedItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );speedItem[i].addItemListener( new ItemHandler() );temp1.add( speedItem[i] );}ButtonGroup temp2 = new ButtonGroup();String[] modelItem_name = { "Linux", "Mac", "Windows" };modelItem = new JRadioButtonMenuItem[modelItem_name.length];for( int i = 0; i < modelItem_name.length; i++ ){modelItem[i] = new JRadioButtonMenuItem( modelItem_name[i] );inner_menu[1].add( modelItem[i] );modelItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );modelItem[i].addItemListener( new ItemHandler() );temp2.add( modelItem[i] );}ButtonGroup temp3 = new ButtonGroup();String[] standardItem_name = { "60 * 40", "45 * 30", "30 * 20" };standardItem = new JRadioButtonMenuItem[standardItem_name.length];for( int i = 0; i < standardItem_name.length; i++ ){standardItem[i] = new JRadioButtonMenuItem( standardItem_name[i] );inner_menu[2].add( standardItem[i] );standardItem[i].setFont( new Font( "Courier", Font.PLAIN, 12 ) );standardItem[i].addItemListener( new ItemHandler() );temp3.add( standardItem[i] );}looks = UIManager.getInstalledLookAndFeels();}private class ActionHandler implements ActionListener{public void actionPerformed( ActionEvent e ){if( e.getSource() == menuItem[0] ){owner.resetGame();ConfigMenu.this.setVisible( false );}else if( e.getSource() == menuItem[1] ){owner.stopGame();ConfigMenu.this.setVisible( true );ConfigMenu.this.setMenuEnable( true );}else if( e.getSource() == menuItem[2] ){System.exit( 0 );}else if( e.getSource() == menuItem[3] ){ConfigDialog temp = new ConfigDialog( owner );temp.setVisible( true );}else if( e.getSource() == menuItem[4] ){JOptionPane.showMessageDialog( null, "Sanke Game 2.0 Version!&#92;n&#92;n" + "Author: FinalCore&#92;n&#92;n" );}}}private class ItemHandler implements ItemListener{public void itemStateChanged( ItemEvent e ){for( int i = 0; i < speedItem.length; i++ ){if( e.getSource() == speedItem[i] ){owner.snakeTimer.setDelay( 150 - 30 * i );}}if( e.getSource() == standardItem[0] ){owner.setGrid( 60, 40, 5 );}else if( e.getSource() == standardItem[1] ){owner.setGrid( 45, 30, 10 );}else if( e.getSource() == standardItem[2] ){owner.setGrid( 30, 20, 15 );}for( int i = 0; i < modelItem.length; i++ ){if( e.getSource() == modelItem[i] ){try{UIManager.setLookAndFeel( looks[i].getClassName() ); }catch(Exception ex){}}}}}public void setMenuEnable( boolean temp ){menu[1].setEnabled( temp );}}。

C语言贪吃蛇源代码

C语言贪吃蛇源代码

C语言贪吃蛇源代码 TTA standardization office【TTA 5AB- TTAK 08- TTA 2C】#include<stdio.h>#include<process.h>#include<windows.h>#include<conio.h>#include<time.h>#include<stdlib.h>#define WIDTH 40#define HEIGH 12enum direction{//方向LEFT,RIGHT,UP,DOWN};struct Food{//食物int x;int y;};struct Node{//画蛇身int x;int y;struct Node *next;};struct Snake{//蛇属性int lenth;//长度enum direction dir;//方向};struct Food *food; //食物struct Snake *snake;//蛇属性struct Node *snode,*tail;//蛇身int SPEECH=200;int score=0;//分数int smark=0;//吃食物标记int times=0;int STOP=0;void Initfood();//产生食物void Initsnake();//构造snakevoid Eatfood();//头部前进void Addnode(int x, int y);//增加蛇身void display(struct Node *shead);//显示蛇身坐标void move();//蛇移动void draw();//画蛇void Homepage();//主页void keybordhit();//监控键盘按键void Addtail();//吃到食物void gotoxy(int x, int y)//定位光标{COORD pos;pos.X = x - 1;pos.Y = y - 1;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos); }void Initsnake()//构造snake{int i;snake=(struct Snake*)malloc(sizeof(struct Snake));tail=(struct Node*)malloc(sizeof(struct Node));food = (struct Food*)malloc(sizeof(struct Food));snake->lenth=5;//初始长度 5snake->dir=RIGHT;//初始蛇头方向右for(i=2;i<=snake->lenth 2;i )//增加 5 个结点{Addnode(i,2);}}void Initfood()//产生食物{struct Node *p=snode;int mark=1;srand((unsigned)time(NULL));//以时间为种子产生随机数while(1){food->x=rand()%(WIDTH-2) 2;//食物X坐标food->y=rand()%(HEIGH-2) 2;//食物Y坐标while(p!=NULL){if((food->x==p->x)&&(food->y==p->y))//如果食物产生在蛇身上{//则重新生成食物mark=0;//食物生成无效break;}p=p->next;if(mark==1)//如果食物不在蛇身上,生成食物,否则重新生成食物{gotoxy(food->x,food->y);printf("%c",3);break;}mark=1;p=snode;}}void move()//移动{struct Node *q, *p=snode;if(snake->dir==RIGHT){Addnode(p->x 1,p->y);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}}if(snake->dir==LEFT){Addnode(p->x-1,p->y);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}if(snake->dir==UP){Addnode(p->x,p->y-1);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}}if(snake->dir==DOWN){Addnode(p->x,p->y 1);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}}}void Addnode(int x, int y)//增加蛇身{struct Node *newnode=(struct Node *)malloc(sizeof(struct Node)); struct Node *p=snode;newnode->next=snode;newnode->x=x;newnode->y=y;snode=newnode;//结点加到蛇头if(x<2||x>=WIDTH||y<2||y>=HEIGH)//碰到边界{STOP=1;gotoxy(10,19);printf("撞墙,游戏结束,任意键退出!\n");//失败_getch();free(snode);//释放内存free(snake);exit(0);}while(p!=NULL)//碰到自身{if(p->next!=NULL)if((p->x==x)&&(p->y==y)){STOP=1;gotoxy(10,19);printf("撞到自身,游戏结束,任意键退出!\n");//失败_getch();free(snode);//释放内存free(snake);exit(0);}p=p->next;}}void Eatfood()//吃到食物{Addtail();score ;}void Addtail()//增加蛇尾{struct Node *newnode=(struct Node *)malloc(sizeof(struct Node)); struct Node *p=snode;tail->next=newnode;newnode->x=50;newnode->y=20;newnode->next=NULL;//结点加到蛇头tail=newnode;//新的蛇尾}void draw()//画蛇{struct Node *p=snode;int i,j;while(p!=NULL){gotoxy(p->x,p->y);printf("%c",2);tail=p;p=p->next;}if(snode->x==food->x&&snode->y==food->y)//蛇头坐标等于食物坐标{smark=1;Eatfood();//增加结点Initfood();//产生食物}if(smark==0){gotoxy(tail->x,tail->y);//没吃到食物清除之前的尾结点printf("%c",' ');//如果吃到食物,不清楚尾结点}else{times=1;}if((smark==1)&&(times==1)){gotoxy(tail->x,tail->y);//没吃到食物清除之前的尾结点printf("%c",' ');//如果吃到食物,不清楚尾结点smark=0;}gotoxy(50,12);printf("食物: %d,%d",food->x,food->y);gotoxy(50,5);printf("分数: %d",score);gotoxy(50,7);printf("速度: %d",SPEECH);gotoxy(15,14);printf("按o键加速");gotoxy(15,15);printf("按p键减速");gotoxy(15,16);printf("按空格键暂停");}void HideCursor()//隐藏光标{CONSOLE_CURSOR_INFO cursor_info = {1, 0};SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info); }void Homepage()//绘主页{int x,y;HideCursor();//隐藏光标printf("----------------------------------------\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("----------------------------------------\n");gotoxy(5,13);printf("任意键开始游戏!按W.A.S.D控制方向");_getch();Initsnake();Initfood();gotoxy(5,13);printf(" ");}void keybordhit()//监控键盘{char ch;if(_kbhit()){ch=getch();switch(ch){case 'W':case 'w':if(snake->dir==DOWN)//如果本来方向是下,而按相反方向无效{break;}elsesnake->dir=UP;break;case 'A':case 'a':if(snake->dir==RIGHT)//如果本来方向是右,而按相反方向无效{break;}elsesnake->dir=LEFT;break;case 'S':case 's':if(snake->dir==UP)//如果本来方向是上,而按相反方向无效{break;}elsesnake->dir=DOWN;break;case 'D':case 'd':if(snake->dir==LEFT)//如果本来方向是左,而按相反方向无效{break;}elsesnake->dir=RIGHT;break;case 'O':case 'o':if(SPEECH>=150)//速度加快{SPEECH=SPEECH-50;}break;case 'P':case 'p':if(SPEECH<=400)//速度减慢{SPEECH=SPEECH 50;}break;case ' '://暂停gotoxy(15,18);printf("游戏已暂停,按任意键恢复游戏"); system("pause>nul");gotoxy(15,18);printf(" "); break;default:break;}}}int main(void)//程序入口{Homepage();while(!STOP){keybordhit();//监控键盘按键move();//蛇的坐标变化draw();//蛇的重绘Sleep(SPEECH);//暂时挂起线程}return 0;}。

android游戏开发入门:贪吃蛇源代码分析

android游戏开发入门:贪吃蛇源代码分析

android游戏开发入门: 贪吃蛇 源代码分析贪吃蛇是一款足够经典的游戏。

它的经典,在于用户操作的简单,在于技术实现的简介,在于他的经久不衰。

这里的贪吃蛇的android实现,是SDK Samples中的开源例程。

可能各位都有看过~界面如下图啦~作为一个刚入门或者还没入门的新手,着实花了我一些力气来理解这段代码。

对于各种不懂的地方,慢慢查询资料,对于新的方法,通过修改代码尝试效果。

到现在终于能算个一知半解。

在代码中,对于自己有所收获的地方,我都做了相应的注释。

回过头来,觉得从这段代码中,能学到不少东西~~包括android应用的基本架构,他的面向对象的思想,以及代码的简洁明了。

于是,我想到,何不将这些东西分享出来,如果碰巧对感兴趣的朋友们有搜帮助,那就更好了~好了,闲话不说~代码和注释如下(处于对源码的敬意,原本的英文注释部分都没有删去~大家可以配合理解):PS:最近我正在写自己的“贪吃蛇”,说事贪吃蛇,其实完全颠覆了这个经典版本的设计理念和操作方式。

具体细节先卖一个关子,作品准备参加这次第二届大学生android应用开发大赛。

应该一个月内能完成,到时候也会开源出代码来~欢迎大家讨论指正·~*************************************************************************************************************************** *****Snake工程中,总共有三个文件: *TileView是基于Android的View类实现的方块图类,用来支撑上层类的调用,绘制方块图的显示界面。

通过这些代码,能打之了解如何 扩展View,实现特色的界面效果。

*SnakeView调用了TileView,实现了游戏逻辑 和 具体的显示。

*Snake为主Activity类。

建议大家按照上面的顺序看三个文件,可能逻辑上更舒服一点~~下面贴上代码和注释。

简单贪吃蛇c语言代码,一个C语言写简单贪吃蛇源代码.doc

简单贪吃蛇c语言代码,一个C语言写简单贪吃蛇源代码.doc

简单贪吃蛇c语⾔代码,⼀个C语⾔写简单贪吃蛇源代码.doc ⼀个C语⾔写简单贪吃蛇源代码#include#include#include#include#include#includeint grade=5,point=0,life=3;voidset(),menu(),move_head(),move_body(),move(),init_insect(),left(),upon(),right(),down(),init_graph(),food_f(),ahead(),crate(); struct bug{int x;int y;struct bug *last;struct bug *next;};struct fd{int x;int y;int judge;}food={0,0,0};struct bug *head_f=NULL,*head_l,*p1=NULL,*p2=NULL;void main(){char ch;initgraph(800,600);set();init_insect();while(1){food_f();Sleep(grade*10);setcolor(BLACK);circle(head_l->x,head_l->y,2);setcolor(WHITE);move_body();if(kbhit()){ch=getch();if(ch==27){ahead();set();}else if(ch==-32){switch(getch()){case 72:upon();break;case 80:down();break;case 75:left();break;case 77:right();break;}}else ahead();}else{ahead();}if(head_f->x==food.x&&head_f->y==food.y) {Sleep(100);crate();food.judge=0;point=point+(6-grade)*10;if(food.x<30||food.y<30||food.x>570||food.y>570)life++;menu();}if(head_f->x<5||head_f->x>595||head_f->y<5||head_f->y>595) {Sleep(1000);life--;food.judge=0;init_graph();init_insect();menu();}for(p1=head_f->next;p1!=NULL;p1=p1->next){if(head_f->x==p1->x&&head_f->y==p1->y){Sleep(1000);life--;food.judge=0;init_graph();init_insect();menu();break;}}if(life==0){outtextxy(280,300,"游戏结束!");getch();return;}move();};}void init_graph(){clearviewport();setlinestyle(PS_SOLID,1,5);rectangle(2,2,600,598);setlinestyle(PS_SOLID,1,1);}void set(){init_graph();outtextxy(640,50,"1、开始 / 返回");outtextxy(640,70,"2、退出");outtextxy(640,90,"3、难度");outtextxy(640,110,"4、重新开始");switch(getch()){case '1': menu();setcolor(GREEN);circle(food.x,food.y,2);setcolor(WHITE);return; case '2': exit(0);break;。

《贪吃蛇》游戏程序代码

《贪吃蛇》游戏程序代码

《贪吃蛇》游戏程序代码1. 游戏初始化:设置游戏窗口、蛇的初始位置和长度、食物的初始位置等。

2. 蛇的移动:根据用户输入的方向键,更新蛇的位置。

确保蛇的移动不会超出游戏窗口的边界。

3. 食物的:在游戏窗口中随机食物的位置。

确保食物不会出现在蛇的身体上。

4. 碰撞检测:检测蛇头是否撞到食物或自己的身体。

如果撞到食物,蛇的长度增加;如果撞到自己的身体,游戏结束。

5. 游戏循环:不断更新游戏画面,直到游戏结束。

6. 游戏结束:显示游戏结束的提示,并询问用户是否重新开始游戏。

import random游戏窗口大小WIDTH, HEIGHT = 800, 600蛇的初始位置和长度snake = [(WIDTH // 2, HEIGHT // 2)]snake_length = 1食物的初始位置food = (random.randint(0, WIDTH // 10) 10,random.randint(0, HEIGHT // 10) 10)蛇的移动方向direction = 'RIGHT'游戏循环while True:更新蛇的位置if direction == 'UP':snake.insert(0, (snake[0][0], snake[0][1] 10)) elif direction == 'DOWN':snake.insert(0, (snake[0][0], snake[0][1] + 10)) elif direction == 'LEFT':snake.insert(0, (snake[0][0] 10, snake[0][1])) elif direction == 'RIGHT':snake.insert(0, (snake[0][0] + 10, snake[0][1]))检测碰撞if snake[0] == food:food = (random.randint(0, WIDTH // 10) 10, random.randint(0, HEIGHT // 10) 10)else:snake.pop()检测游戏结束条件if snake[0] in snake[1:] or snake[0][0] < 0 or snake[0][0] >= WIDTH or snake[0][1] < 0 or snake[0][1] >= HEIGHT:break游戏画面更新(这里使用print代替实际的游戏画面更新) print(snake)用户输入方向键direction = input("请输入方向键(WASD): ").upper() print("游戏结束!")。

贪吃蛇JAVA源代码完整版

贪吃蛇JAVA源代码完整版

游戏贪吃蛇的JAVA源代码一.文档说明a)本代码主要功能为实现贪吃蛇游戏,GUI界面做到尽量简洁和原游戏相仿。

目前版本包含计分,统计最高分,长度自动缩短计时功能。

b)本代码受计算机系大神指点,经许可后发布如下,向Java_online网致敬c)运行时请把.java文件放入default package 即可运行。

二.运行截图a)文件位置b)进入游戏c)游戏进行中三.JAVA代码import java.awt.*;import java.awt.event.*;import static ng.String.format;import java.util.*;import java.util.List;import javax.swing.*;public class Snake extends JPanel implements Runnable { enum Dir {up(0, -1), right(1, 0), down(0, 1), left(-1, 0);Dir(int x, int y) {this.x = x; this.y = y;}final int x, y;}static final Random rand = new Random();static final int WALL = -1;static final int MAX_ENERGY = 1500;volatile boolean gameOver = true;Thread gameThread;int score, hiScore;int nRows = 44;int nCols = 64;Dir dir;int energy;int[][] grid;List<Point> snake, treats;Font smallFont;public Snake() {setPreferredSize(new Dimension(640, 440));setBackground(Color.white);setFont(new Font("SansSerif", Font.BOLD, 48));setFocusable(true);smallFont = getFont().deriveFont(Font.BOLD, 18);initGrid();addMouseListener(new MouseAdapter() {@Overridepublic void mousePressed(MouseEvent e) {if (gameOver) {startNewGame();repaint();}}});addKeyListener(new KeyAdapter() {@Overridepublic void keyPressed(KeyEvent e) {switch (e.getKeyCode()) {case KeyEvent.VK_UP:if (dir != Dir.down)dir = Dir.up;break;case KeyEvent.VK_LEFT:if (dir != Dir.right)dir = Dir.left;break;case KeyEvent.VK_RIGHT:if (dir != Dir.left)dir = Dir.right;break;case KeyEvent.VK_DOWN:if (dir != Dir.up)dir = Dir.down;break;}repaint();}});}void startNewGame() {gameOver = false;stop();initGrid();treats = new LinkedList<>();dir = Dir.left;energy = MAX_ENERGY;if (score > hiScore)hiScore = score;score = 0;snake = new ArrayList<>();for (int x = 0; x < 7; x++)snake.add(new Point(nCols / 2 + x, nRows / 2));doaddTreat();while(treats.isEmpty());(gameThread = new Thread(this)).start();}void stop() {if (gameThread != null) {Thread tmp = gameThread;gameThread = null;tmp.interrupt();}}void initGrid() {grid = new int[nRows][nCols];for (int r = 0; r < nRows; r++) {for (int c = 0; c < nCols; c++) {if (c == 0 || c == nCols - 1 || r == 0 || r == nRows - 1)grid[r][c] = WALL;}}}@Overridepublic void run() {while (Thread.currentThread() == gameThread) {try {Thread.sleep(Math.max(75 - score, 25));} catch (InterruptedException e) {return;}if (energyUsed() || hitsWall() || hitsSnake()) {gameOver();} else {if (eatsTreat()) {score++;energy = MAX_ENERGY;growSnake();}moveSnake();addTreat();}repaint();}}boolean energyUsed() {energy -= 10;return energy <= 0;}boolean hitsWall() {Point head = snake.get(0);int nextCol = head.x + dir.x;int nextRow = head.y + dir.y;return grid[nextRow][nextCol] == WALL;}boolean hitsSnake() {Point head = snake.get(0);int nextCol = head.x + dir.x;int nextRow = head.y + dir.y;for (Point p : snake)if (p.x == nextCol && p.y == nextRow)return true;return false;}boolean eatsTreat() {Point head = snake.get(0);int nextCol = head.x + dir.x;int nextRow = head.y + dir.y;for (Point p : treats)if (p.x == nextCol && p.y == nextRow) {return treats.remove(p);}return false;}void gameOver() {gameOver = true;stop();}void moveSnake() {for (int i = snake.size() - 1; i > 0; i--) {Point p1 = snake.get(i - 1);Point p2 = snake.get(i);p2.x = p1.x;p2.y = p1.y;}Point head = snake.get(0);head.x += dir.x;head.y += dir.y;}void growSnake() {Point tail = snake.get(snake.size() - 1);int x = tail.x + dir.x;int y = tail.y + dir.y;snake.add(new Point(x, y));}void addTreat() {if (treats.size() < 3) {if (rand.nextInt(10) == 0) { // 1 in 10if (rand.nextInt(4) != 0) { // 3 in 4int x, y;while (true) {x = rand.nextInt(nCols);y = rand.nextInt(nRows);if (grid[y][x] != 0)continue;Point p = new Point(x, y);if (snake.contains(p) || treats.contains(p))continue;treats.add(p);break;}} else if (treats.size() > 1)treats.remove(0);}}}void drawGrid(Graphics2D g) {g.setColor(Color.lightGray);for (int r = 0; r < nRows; r++) {for (int c = 0; c < nCols; c++) {if (grid[r][c] == WALL)g.fillRect(c * 10, r * 10, 10, 10);}}}void drawSnake(Graphics2D g) {g.setColor(Color.blue);for (Point p : snake)g.fillRect(p.x * 10, p.y * 10, 10, 10);g.setColor(energy < 500 ? Color.red : Color.orange);Point head = snake.get(0);g.fillRect(head.x * 10, head.y * 10, 10, 10);}void drawTreats(Graphics2D g) {g.setColor(Color.green);for (Point p : treats)g.fillRect(p.x * 10, p.y * 10, 10, 10);}void drawStartScreen(Graphics2D g) {g.setColor(Color.blue);g.setFont(getFont());g.drawString("Snake", 240, 190);g.setColor(Color.orange);g.setFont(smallFont);g.drawString("(click to start)", 250, 240);}void drawScore(Graphics2D g) {int h = getHeight();g.setFont(smallFont);g.setColor(getForeground());String s = format("hiscore %d score %d", hiScore, score);g.drawString(s, 30, h - 30);g.drawString(format("energy %d", energy), getWidth() - 150, h - 30); }@Overridepublic void paintComponent(Graphics gg) {super.paintComponent(gg);Graphics2D g = (Graphics2D) gg;g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);drawGrid(g);if (gameOver) {drawStartScreen(g);} else {drawSnake(g);drawTreats(g);drawScore(g);}}public static void main(String[] args) {SwingUtilities.invokeLater(() -> {JFrame f = new JFrame();f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setTitle("Snake");f.setResizable(false);f.add(new Snake(), BorderLayout.CENTER);f.pack();f.setLocationRelativeTo(null);f.setVisible(true);});}}。

贪吃蛇c++语言程序,C++语言贪吃蛇游戏源代码.doc

贪吃蛇c++语言程序,C++语言贪吃蛇游戏源代码.doc

贪吃蛇c++语⾔程序,C++语⾔贪吃蛇游戏源代码.docC语⾔贪吃蛇游戏源代码/*Author : 柳印奇email : liuyinqi2012@Description : 蛇年来临创作⼀个与蛇有关的经典游戏《贪吃蛇》,与同学们分享蛇年美好的时光。

欢迎交流与探讨,直接将代码粘贴到VC6.0的环境下即可运⾏。

← 左转→ 右转↓ 向下↑ 向上积分达到⼀定程度,会有换命的活动,命最多6条。

难度会随积分的上升逐渐上升,最多到6的难度。

*/#include#include#include#include#pragma comment(lib, "winmm.lib")using namespace std;#define GameW 20#define GameH 11const int CtrlLeft = GameW*2+4 + 3;struct Point {Point(){}Point& operator=(const Point& rhs) {_x = rhs._x;_y = rhs._y;return *this;}Point(int x, int y) {_x = x, _y = y;}int _x, _y;};HANDLE g_hOutput = GetStdHandle(STD_OUTPUT_HANDLE);HANDLE g_hInput = GetStdHandle(STD_INPUT_HANDLE); Point g_ptCursor(0,0);BOOL isChecking = FALSE;BOOL g_bGameOver = FALSE;BOOL bCreateEgg = FALSE;int g_nGameBack[GameH][GameW];int nowKeyInfo = -1;int g_nDiff = 1;int g_nLife = 3;int g_nScore = 0;void SetCursor(COORD cd) {SetConsoleCursorPosition(g_hOutput, cd);}void SetCursor(int x, int y){COORD cd = {x, y};SetCursor(cd);}void SetBlockCursor(int x, int y){COORD cd = {2*x + 2, y + 1};SetCursor(cd);}void SetBack(int x, int y, BOOL bk) {SetBlockCursor(x, y);if (bk)printf("%s", "■");elseprintf(" ");}bool Out(int x, int y) {return x < 0 || y < 0 || x >= GameW || y >= GameH;}struct Egg {int x;int y;Point fangxiang;Egg() {}Egg(int px, int py) {x = px;y = py;fangxiang._x = 1;fangxiang._y = 0;}Egg(const Egg& rhs) {x = rhs.x;y = rhs.y;fangxiang = rhs.fangxiang;}Egg& operator=(const Egg& rhs) { x = rhs.x;y = rhs.y;fangxiang = rhs.fangxiang;return *this;}void DrawMe() {if (!Out(x,y)) {SetBack(x, y, TRUE);}}void eraseMe() {if (!Out(x,y)) {SetBack(x, y, FALSE);}}};Egg egg;class Snake {public:vector List;Snake(){}Snake(Egg& eg) { List.push_back(eg); }void move() {。

贪吃蛇的源程序

贪吃蛇的源程序

贪吃蛇main(int argc,char *argv[]){if (argc!=1){if (argv[1]!="") Heng=atoi(argv[1]);if (argv[2]!="") Shu=atoi(argv[2]);}Init(); /*初始化界面*/PreAct=random(8); /*取得当前的方块*/for(;;) /*以下是游戏流程*/{NextAct=random(8); /*取得下一个方块*/DrawNext(1); /*画出下一个方块*/Act=PreAct;if (Heng%2==0) ActH=Heng/2; else ActH=(Heng-1)/2;ActS=0; /*方块开始从游戏空间的中间下落*/Staus=0; /*取开始的状态*/NoPass=CAN; /*物体可以下落*/Give(); /*取得当前的方块*/Display(Act+1); /*显示当前的方块,每种方块的颜色不同*/GoOn(); /*游戏的算法精髓所在*/PreAct=NextAct; /*方块下落完毕,取得下一个方块*/DrawNext(0);}}c2.0中怎么样设置图形显示?Tc2.0中有两种显示模式,一种是我们所熟知的字符模式,另一种是图形模式。

在字符模式下只能显式字符,如ASCII字符。

一般是显示25行,每行80个字符。

程序缺省的是字符模式。

在字符模式下不能显式图形和进行绘图操作。

要想进行图形显示和绘图操作,必须切换到图形模式下。

Tc2.0中用initgraph()函数可以切换到图形模式,用closegraph()可以从图形模式切换回字符模式。

initgraph()和closegraph()都是图形函数,使用图形函数必须包括头文件"graphics.h"。

void far initgraph(int far *graph driver,int far *graphmode,char far *pathtodriver);graphdriver是上涨指向图形驱动序号变量的指针;graphmo de是在graphdriver选定后指向图形显示模式序号变量的指针。

贪吃蛇源程序

贪吃蛇源程序

gotoxy(hOut,FrameX+2*Frame_width+3,FrameY+19);
printf("空格:暂停游戏");
gotoxy(hOut,FrameX+2*Frame_width+3,FrameY+15);
printf("Esc :退出游戏");
gotoxy(hOut,FrameX,FrameY);
随机产生方块类型的序号voidgetflagstructtetris制作俄罗斯方块voidmaketetrisstructtetris打印俄罗斯方块voidprinttetrishandlehoutstructtetris清除俄罗斯方块的痕迹voidcleartetrishandlehoutstructtetris判断是否能移动返回值为1能移动否则不动intifmoveablestructtetris判断是否满行并删除满行的俄罗斯方块voiddelfullhandlehoutstructtetris开始游戏voidstartgame
void gotoxy(HANDLE hOut, int x, int y)
{
COORD pos;
pos.X = x; //横坐标
pos.Y = y; //纵坐标
SetConsoleCursorPosition(hOut, pos);
}
/******






******************************************************************/
a[tetris->x+2][tetris->y]=b[3];

C语言课程设计报告——贪吃蛇源程序

C语言课程设计报告——贪吃蛇源程序

C 语止课程安排之阳早格格创做(小游戏贪吃蛇的步调安排报告)安排人:班级:201年月号目录一:概括1:钻研背景及意思2:安排的任务与需要知识面3:简曲完毕安排真量二:需要领会1:功能需要2:支配要领三:总体安排1:模块区分2:数据结构安排四:仔细安排1:主空摸块安排2:画造游戏界里3:游戏的简曲历程4:游戏的中断处理5:隐现排止榜疑息模块五:步调的调试与尝试1:动画与音乐共步2:蛇的运止3:末止步调六:论断七::中断语八:步调浑单九:参照文献一.概括本课程安排以硬件工程要领为指挥,采与了结构化,模块化的步调安排要领,以C谈话技能为前提,使用TurboC++3.0为主要启垦工具,对付贪吃蛇游戏举止了需要领会,总体安排,仔细安排,最后完毕系统的真止与尝试.1.1 钻研的背景及意思随着社会的死少,人们死计的节奏日益加快,越去越多的人加进了寰球化的天下.人们不再拘泥与一小块天天,加班,出好成了新颖人不可预防的公务.而此时一款不妨随时随天娱乐的游戏成为了人们的需要.此次课程安排完毕的贪吃蛇小游戏,正是为了谦脚上述需要而安排出去的.贪吃蛇游戏虽小,却安排诸多的知识面.通过启垦贪吃蛇游戏系统,可使读者收端相识使用硬件工程的战那个收,技能战工具启垦硬件的历程,进一步掌握结构化,模块化的步调安排要领战步调,进一步掌握总体数据结构安排,模块区分要领,掌握局部变量,齐部变量,结构体,共用体,数组,指针,文献等数据结构的使用要领,掌握图形,声音,随机数等多种库函数的使用要领,教习动画,音乐,窗心,菜单,键盘等多项编程技能,进一步教会硬件调试,尝试,组拆等硬件尝试要领,为后绝课程的教习战将去本量硬件启垦挨下脆真的前提.1.2 安排的任务战需要的知识面1.2.1 课程安排主要完毕的任务1).通过编写“贪吃蛇游戏”步调,掌握结构化,模块块化步调安排的思维,培植办理本量问题的本领.2) 有共步播搁动画,声音效验.3) 安排佳数组元素与蛇,食物的对付应关系.4) 随机爆收食物.5) 有分数统计,排止榜,分数保存等功能.通过此次课程安排,期视使读者能更深进的明黑战掌握课程教教中的基础观念,培植读者应用基础技能办理本量问题的本领,进而进一步普及领会问题妥协决问题的本领.1.2.3本次课程安排需要掌握战使用如下的知识面:1) 数组的应用.2) 齐部变量的使用.3) 按键处理.4)结构体的应用.5)图形,音乐战动画的有关知识.6)随即函数的使用.7)文献的基础出支配.8) 结构化,模块化的安排要领.正在本次课程安排中需要完毕的任务有:包罗下令,齐部变量的定义战宏定义,函数声明等(50止),主控模块(MAIN函数,14止),动画,音乐播搁模块(DRAWSNOW函数,33止),画出游戏启初界里模块,简曲游戏历程模块,游戏中断处理模块.启垦中处事量约为215止源代码.二 .需要领会贪吃蛇游戏是个简朴的小游戏,能让游戏者的身心得到娱乐,进而不妨更佳天加进到教习或者处事核心.虽然目前市里上出去那百般百般的游戏版本,但是贪吃蛇那类的小游戏其商场仍旧相称大的,果为它玩法简朴易止,不管是脚机,仍旧小游戏机,皆能很成功的运止.对付于正在中闲碌的人,不可能耗费洪量时间正在娱乐上,庞大游戏是止短亨的,那样的小游戏刚刚佳迎合了他们的需要.要启垦贪吃蛇游戏步调,最先要领会改步调应真止哪些功能.对付贪吃蛇游戏步调的功能需要可形貌如下:步调运止后隐现动画,音乐,按ESC 键退出游戏界里后,左边有一个矩形区,中游戏天区,正在矩形区中有食物战贪食蛇,上圆有统计分数及关数隐现天区.蛇正在启关围墙利用绿色矩形表示,围墙里随机的出现一个食物,通过按键盘四个光标键统造蛇进与,下,安排四个目标移动,蛇头碰到食物,则食物被吃掉,蛇身体少一节,接着又出现食物,等待蛇去吃.食物用一个面表示,而且屡屡食物的位子皆是随机出现的.游戏中要使贪吃蛇尽大概的少,然而是不克不迭使贪吃蛇碰到四里的墙壁,而且蛇的身体不克不迭碰到所有,可则游戏中断.游戏中每吃掉一个食物要有积分,随着分数的减少可加进下一关,纵然速度会加快.游戏中断时,如果分数加进前5名则沉新排榜并保存.隐现排止榜.由于有关贪吃蛇战食物的数据较多,而且关系稀切,贪吃蛇及食物皆是定义结构体数据典型,那样定义便于支配与处理.2.2 支配要领三 总体安排决定贪吃蛇游戏体捆绑构,给出总体模块结构图,决定步调的主要函数及之间的调用关系,共时安排蛇与游戏者等的数据结构.3.1 模块区分本步调采与结构化步调安排的要领,依照自顶背下,逐步细化的要领对付要办理的问题举止逐层领会.最先画出顶层模块,即主控模块,之完毕对付下层模块的调用功能,即调用其余的功能模块;接着,按需要领会中的功能需要安排第一层模块,有音乐动画,图形启动,画主界里,游戏历程,中断处理,退出品级6个主要功能;接着,画出第二层模块.总体模块结构如图6-1所示.3.1.1. 主控模块. 3.1.2. 动画音乐模块 3.1.3. 画主界里模块 3.1.4. 游戏历程模块 3.1.5. 游戏中断处理模块 3.1.6. 读与记录模块 3.1.7. 结果排序模块 3.1.8. 写进文献模块 3.1.9. 排止榜模块 3.1.10. 退出3.2 总体数据结构安排安排思路:测序的关键正在于表示蛇的图形及蛇的移动.用一个小限造性圆块表示蛇的一节主 控 模 板 读与记录结果排序写进文献排止榜动画音乐图形启动退出中断处理 游戏历程画主界里身体,身体每少一节,减少一个矩形块,蛇头业用共样的一节小矩形圆块表示移动时必须从蛇不妨上背前爬止,档案下灵验目标键后,应先决定蛇头的位子,而后蛇的身体虽蛇头移动,图形的真止是从身体新位子启初画出蛇.那时,由于已浑屏的本果,本去的蛇的位子战新蛇的位子好一节蛇身,即瞅起去蛇多一节身体,所以将蛇的末尾一节用背景致覆盖.食物的出现与消得意识画矩形块战覆盖矩形块.为了便于明黑,定义二个结构体:食物与蛇.底下介绍贪吃蛇游戏步调的主要数据结构.3.2.1 食物与蛇的数据结构表示食物与蛇的矩形块安排为10*10个像素单位,食物的基础数据域为它所出现的位子,用X战Y坐标表示,则矩形块用函数RECTANGLE(X,Y,X+10,Y+10)或者RECTANGLE(X,Y,X+10,Y-10)不妨画出.由于屡屡只出现一个食物,所以设定YES表示是可需要出现食物.YES=1表示不食物或者食物已经被蛇吃掉,需要画出食物.搁置食物后,置YES=0.蛇的一节身体为一个矩形块,表示矩形块只需左上角面坐标(X,Y).由于正在游戏历程中蛇的身体不竭删少,需用数组存搁每节坐标,最大设定为N=200,NODE表示目前节数.DIRECTION是保存蛇的移动目标的变量,其值可为1、2、3、4之一,分别表示左、左、上、下的目标.LIFE是表示死命的变量,LIFE=0表示蛇活着,一朝LIFE=1,一朝LIFE=1,表示蛇死,中断游戏.#define N 200Struct Food{ int x;int y;Int yes;}food;Struct Snake{ int x[N];Int y[N];Int node;Int derection;Int life;}snake;3.2.2 排止榜中劣胜者的数据结构排止榜主要记录劣胜者的姓名战结果.为了存搁排止榜疑息,可定义如下的结构体典型,其中字符数组name成员存搁劣胜者的姓名,整型变量score成员存搁劣胜者的结果.Struct person{ char name[20];Int score;};3.2.3 其余齐部变量的定义Struct person per[5];Int score=0;Int gamespeed=400;3.2.4 标记常量的宏定义#define LEFT 0x4b00;#define RIGHT 0x4d00;#define DOWN 0x5000;#define UP 0x4800#define ESC 0x011b#define FILENAME四. 仔细安排根据总体安排的模块功能战结构,完毕所负担的步调模块的算法安排.给出每个模块的仔细的算法,算法分别用保守过程图战笔墨证明去形貌.4.1 主控模块main函数主函数是步调的主控模块.最先初初化图形系统,而后使用drawsnow函数播搁动画战声音,接着调用init函数初初化图形系统,之后调用drawk函数画出游戏启初画里,正在调用g ameplay函数,即启初了游戏的简曲历程,游戏中断后调用endplay函数举止游戏中断处理;从文献中读与记录疑息,排序,隐现排止榜疑息,末尾关关图形系统,中断步调.主控模块的过程图如图6-2所示.其中戴有二个横线的矩形框表示对付自定义函数的调用.4.2函数主界里便是一个启关的围墙,用二个循环语句分别正在火仄目标战笔曲目标输出连绝的宽度战下的均为10个像素单位的距止小圆块,围成启关图形表示围墙,为了醉目,树坐为浓青色,用函数setlinestyle设曲线型宽度为3个像素,树坐3个像素的围墙线,.末尾,正在界里的左上部输出游戏步调的版本疑息,正在左上部输出游戏结果(score)战关(level)的表头.4.3 游戏简曲历程gameplay函数该函数是游戏的核心部分.游戏简曲历程gameplay函数的大概算法过程图如图6-4所示.余下过程图正在下页4.3.1那24.3.21 0个4.3.3那里的易面是表示蛇的新位子并与消前一次的图形.采与的要领是屡屡移动的时间从末尾一节启初到第二节,将前一节的坐标值赋给后一节的坐标,移动后只消把末尾一节用背景致揩出即可,果为新位子0到n-1节仍旧要出目前画里上的.那里用一个for循环去决定蛇身的新坐标.4.3.4 吃到食物后的处理蛇吃到食物后,最先将食物揩除,即用背景致画出该食物,而后给蛇的节数加1,树坐需要食物标记,是游戏结果加10分,如果结果达到50分的倍数,则给关数加1,并加快游戏速度.4.3.5 有按键推断蛇的目标那是一个内嵌的嵌套的条件采用结构,根据安东上下安排键去设定蛇的移动目标.其中1=背左,2=背左,3=进与,4=背下.推断是还思量好异的目标键无效,比圆蛇正正在进与爬止,按下一键目标是无效的.4.4 游戏的中断处理木块ENDPLAY函数游戏中断时,该当用ENDPLAY函数举止游戏中断处理,其算法过程图如图6-5所示I 其次,推断游戏者的结果是可不妨上排止榜.如果不妨上榜,则画出浓蓝色矩形界里,正在界里中输进游戏者姓名,对付结果举止赋值,而后调用CompareScore 函数对付记录排序,并调用Writefiles 函数将记录写进排止榜助文献;如果不克不迭上榜,则间接正在游戏界里输出不克不迭上榜疑息.末尾,调用 pain_board 函数隐现排止榜疑息.函数void pain_board完毕排止榜的画造.五. 步调的调试与尝试调试与尝试硬件的目标便是创造并改正潜伏的过得.一个步调,必须通过认果然调试战尝试,才搞尽管缩小过得、包管步调谦脚功能、本能需要,达到最初的安排、使用央供,进而包管步调的启垦品量.仔细安排完毕后,便不妨用C谈话根据各个模块的算法去安排步调,每个模块皆要安排成一个自定义函数.几个模块不妨搁正在所有形成一个本函数步调文献,也不妨一个模块形成一个源步调文献.本步调安排佳后,输进到估计机中,并保存到磁盘上;而后对付每个源步调文献皆举止了独力编译战调试(简曲代码不妨参瞅步调浑单);并针对付分歧的模块步调安排尝试用例举止单元尝试;末尾,将几个分别启垦的模块组拆正在所有,产死一个完备的步调,举止集成尝试,进而创造并改正了步调步调中存留的一些潜躲的过得,并使步调的容错本领大大巩固.5.1 动画与音乐的共步播搁预期截止:①片头正在隐现动画得共时播搁音乐;②按任性键后加进游戏主界里;③加进游戏主界里后动画音乐共时停止.本量运止效验:谦脚①战②,不谦脚③,即加进游戏后仍旧播搁片头音乐.过得领会:步调中使用循环播搁动画,并正在其循环体中拔出收声函数以达到音乐战动画的共步.由于正在中断动画时不关关扬声器,所以加进游戏界里后仍旧收声.建改:正在动画播搁完后加一条“nosound();”语句将扬声器关关,问题得到办理. 建改后步调运止的本量效验与预期效验普遍.5.2 蛇的运止5.2.1 蛇碰到墙预期截止:蛇运止时如果碰到墙壁,则游戏中断.本量运效验:超出安排墙壁后步调中断,然而超出上头墙壁后仍旧运止,如图6-9所示.过得领会:过得步调段正在蛇运止中的条件推断语句中,其推断条件是:if(snake.x[0]<55|| snake.x[0]>595),即少了上、下二个目标的推断.建改:正在蛇的运止历程中增加二个逻辑表黑式,推断蛇是可闯到上下的围墙.代码:If( snake.x[0]<55|| snake.x[0]>595|| snake.y[0]<55|| snake.y[0]>455)建改后的步调运止截止与预期的截止普遍.5.2.2 蛇头闯到蛇身预期的截止:当蛇得头部与蛇身相碰时,游戏应核心断. 本量运止效验:蛇头碰到蛇身时,步调本去不末止.过得领会:正在蛇的运止推断的步调堕落,其代码如下Fori=3;i<snake.node;i++){ if(snake.x[i]=snake.x[0]&&snake.y[i]=snake.y[0]){snake.life=0;break;}}建改:将循环体中的snake.life=0改为snake.life=1;建改后的截止与预期截止普遍.5.3 末止循环通过对付各个模块的调试战单元尝试并建改了过得后,将各个模块组拆成一个系统,并举止集成尝试.正在集成的历程中创造了一些过得,比圆齐部变量沉复定义、函数沉复声明等,分别举止了改正.末尾连绝运止了5次,以便尝试该游戏步调的功能、本能是可达到了预期的目标,并根据所使用的简曲呆板对付蛇的爬止速度举止适合的安排.尝试真量包罗蛇的运止、分数、关数、排止榜及排序、文献保存、音乐动画等功能,情况均仄常.六. 论断通过2周的课程安排,正在启垦小组共共的齐力下,毕竟完毕了贪吃蛇游戏步调的启垦任务.该游戏步调真止了用目标键统造蛇正在围墙内爬止、随机爆收食物、统造蛇吃掉食物并加分、统造游戏中闯关的数目战蛇的运止速度、真时隐现得分战关数、中断时处理战隐现排止榜等功能.该游戏步调具备界里友佳、支配便当、统造准确战容错本领强等特性.那个贪吃蛇游戏还存留一些缺陷,还该当正在如下几个圆里加以矫正.1)加进游戏后,到蛇牺牲,只可玩一次便会退出步调.应加进多次游戏的统造本领.2)蛇的格式不好瞅,应将蛇头、蛇尾战蛇身进一步好化,使其更像真正在的蛇.3)当分数达到400分时,蛇的速度变得非常快,一下子便碰到围墙上了,应适合统造蛇的速度战关数,以便使游戏更具备吸引力.贪吃蛇游戏的编程训练思索数据结构:定义食物的坐标去统造它出现的位子,用一系列的函数时举止表示,比圆用函数rectangle去画出矩形,用life变量的值表示蛇的死命,用direction变量的值表示蛇移动的目标等,另有用数组去存搁蛇身各节的坐标,那些皆让咱们认识了对付数组的支配,别的还认识了百般函数的应用.贪吃蛇的安排有很多助闲,教习编写贪吃蛇的游戏对付掌握C谈话的知识有很大的助闲.通过编程试验,还能拓展思路,让咱们去觅找需要调用那些函数,何如普及步调的品量等. 要写出佳的步调,需要咱们有扎真的前提,那样逢到一些基础算法的时间便会游刃有余了.正在编程时咱们要有歉富的设念力,不要拘泥与牢固的思维办法,逢到问题的时侯要多念几种办理问题的规划.歉富的设念力是建坐正在歉富的知识前提上,所以咱们要通过多个道路去助闲自己建坐较歉富的知识结构.正在编程是咱们碰倒了很多的艰易,那便需要咱们多与他人接流.正在编程的历程中,咱们也创造有良佳的编程风格是格中要害的,起码正在时间效用上便体现了那一面.养成良佳的习惯,代码的缩进编排,变量的命名准则要末究脆持普遍,那些皆是普及咱们编程本领的重心.正在举止课程安排的历程中咱们也教到了许多别的物品.最先,咱们教会了合做,要以他人的视线瞅瞅问题,也许那样得到的会比各得意到的皆要多;其次,咱们教会了单干,单干是为了更佳天合做,单干才搞普及合做的效用;末尾,咱们教会了搏斗,咱们疑赖,通过四年的教习,咱们一定能写出更粗彩的步调,将去会描画出更粗彩的人死.正在那里,咱们要感动指挥课程安排的弛凤君教授,赋予咱们粗心的指挥.教授多次询问编写进程,并为咱们指面迷津,助闲咱们启拓钻研思路,粗心面拨、关切饱励.教授敷衍了事的处事做风,宽紧供真的做风,踩踩真真的粗神,不然而受尔以文,而且教尔搞人,给以末死受益无贫之讲.尔还要感动咱们启垦小组的其余共教,正在安排中他们给尔很大的助闲.正是由于咱们团结协做,才成功的完毕了课程安排任务.八.程序浑单/*贪吃蛇游戏步调浑单*/#include<stdio.h>#include<string.h>#include<time.h>#include<bios.h>#include<graphics.h>#include<conio.h>#include<stdlib.h>#include<dos.h>#define filename "c:\\person.dat" /*排止榜文献的文献齐名*/#define esc 0x011b /*esc键*/#define n 200 /*蛇的最大节数*/#define left 0x4b00 /*左移目标键*/#define right 0x4d00 /*左移搁背键*/#define down 0x5000 /*下移目标键*/#define up 0x4800 /*上移目标键*//*排止榜结构体*/struct person{int score; /*游戏者分数*/char name[20]; /*游戏者姓名*/}per[5];/*小蘑菇结构体*//*自定义的函数声明*/void drawmogu(); /*动画音乐函数*/void readfiles(); /*从文献中读与记录疑息*/void writefiles(struct person *) ; /*将记录写进文献中*/void initscorefiles(); /*初初化记录文献*/void comparescore(struct person); /*排止榜按分数举止排序*/void endplay(); /*游戏中断处理函数*/void paihb(); /*画造排止榜函数*//*输出欢迎词汇并播搁声音函数*/void pr(){ int s[15]={0,100,150,200,250,300,250,150,100,250,350};setcolor(change/10);/*改变欢迎词汇颜色*/settextstyle(0,0,4);outtextxy(20,200,"WELCOME TO OUR GAME");/*输出欢迎词汇*/sound(s[change/10]);/*使扬声器以括号内的频次收声*/}/*下雪的动画并共步播搁音乐函数*/void DrawSnow(){ int i;int sx[62];selinestyle(SOLID_LINE,0,THICK_WIDTH);line(1,1,9,9);/*一次3止画出红色雪花的3条线*/line(0,5,10,5);line(9,1,1,9);save=malloc(200);/*正在堆中申请200字节空间*/getimage(0,0,10,10,save);/*将雪花位图保存到save中*/cleardevice();/*浑屏*/randomize();/*树坐随机种子数*/for(i=0;i<62;i++)sx[i]=(i+2)*10/*估计雪花位子的横坐标数组*//*以下的键控while循环统造播搁音乐战下雪动画*/while(!kbhit())/*如果已按键,真止循环体*/{ Pr();/*调用Pr函数输出欢迎词汇并播搁声音*/if(snownum!=100){snow[snownum].speed=2+random(5);i=random(62);snow[snownum].x=sx[i];/*与横坐标*/snow[snownum].y=10-random(100);/*与纵坐标*/}/*循环搁置snownum个雪花*/for(i=0;i<snownum;i++)putimage(snow[i].x,snow[i].y,save,COPY_PUT);delay(100);/*延缓100ms以便瞅到雪花*/cleardevice();/*浑屏*/Pr(); /*调用Pr函数输出欢迎词汇并播搁声音*/if(snownum !=100) snownum++;setfillstyle(SOLID_FILL,15);for(i=0;i<snownum;i++) /*循环画出snownum个雪花*/{ snow[i].y+=snow[i].speed;putimage(snow[i].x,snow[i].y,save,COPY_PUT);if(snow[i].y>500)snow[i].y=10-random(200);}change++;if(change==140) change=10;}nosound(); /*关关扬声器*/cleardevice();/*浑屏*/}/*图像系统初初化函数*/void init(void){ int gd=DETECT,gm;initgraph(&gd,&gm,"c:\\tc3\\BGI");cleardevice(); /*浑屏*/}/*游戏启初界里,左上角坐标为(50,40),左下角坐标(610,460)的围墙*/ void drawk(void){int i;setcolor(BLUE);setlinestyle(SOLID_LINE,0,THICK_WIDTH); /*树坐线性*/for(i=50;i<=600;i+=10) /*用循环画围墙*/{setcolor(2*i+1);circle(i,40,5); /*画上边*/circle(i,451,5);circle(i,460,5); /*画下边*/}for(i=40;i<=450;i+=10){setcolor(2*i+1);circle(50,i,5); /*画左边*/circle(601,i,5);}for(i=40;i<=460;i+=10){setcolor(2*i+1);circle(41,i,5); /*画左边*/circle(610,i,5);}setcolor(LIGHTCYAN);setlinestyle(SOLID_LINE,0,THICK_WIDTH);outtextxy(20,5," GREEDY SNAKE GAMES ji 11_1"); /*输出版本*/ outtextxy(480,10,"score level "); /*输出此文本*/}/*玩游戏简曲历程*/void gameplay(void){food.yes=1; /*0表示苹果已经存留,1表示需要出现新苹果*/snake.life=0; /*蛇活着*/int level=1; /*记录游戏品级*/char buffer[10]; /*字符数组用于变换整形数据*/randomize(); /*树坐随机数的种子数*/snake.direction=1; /*目标背左*/snake.x[0]=110;snake.y[0]=100; /*蛇头坐标初值*/snake.x[1]=100;snake.y[1]=100; /*蛇身1节坐标初值*/snake.x[2]=90;snake.y[2]=100; /*蛇身2节坐标初值*/snake.node=3; /*蛇节数初值*/while(1) /*玩游戏死循环,按esc键或者蛇死时中断*/{ while(!kbhit()) /*正在不按键的情况下,蛇自己移动身体*/{if(food.yes==1) /*需要出现新苹果*/{food.x=rand()%400+60; /*正在墙内随机爆收苹果横坐标*/food.y=rand()%350+60; /*正在墙内随机爆收苹果纵坐标*//*真物随机爆收后必须让苹果不妨正在整格上,那样才搞吃到*/ while(food.x%10!=0) food.x++;while(food.y%10!=0) food.y++;food.yes=0; /*画里上有苹果了*/}if(food.yes==0) /*画里上有苹果便要画出去*/{setcolor(GREEN);setfillstyle(SOLID_FILL,GREEN);circle(food.x,food.y,5);fillellipse(food.x,food.y,5,5);}setfillstyle(1,BLUE);bar(475,18,590,35); /*画出隐现分数及关数蓝色矩形条*/setcolor(WHITE);itoa(score,buffer,10); /*将整形数据分数变换成字符串*/outtextxy(480,20,buffer); /*输出分数*/itoa(level,buffer,10); /*将整形数据关数变换成字符串*/outtextxy(560,20,buffer); /*输出关数*//*循环使蛇的每一节往前移动,那是贪吃蛇的“关键算法”*/for(i=snake.node-1;i>0;i--){snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1];}/*1、2、3、4表示左、左、上、下四个目标,通过那个推断去移动蛇头*/ switch(snake.direction){case 1:snake.x[0]+=10;break;case 2:snake.x[0]-=10;break;case 3:snake.y[0]-=10;break;case 4:snake.y[0]+=10;break;}/*推断蛇是可碰到墙*/if(snake.x[0]<55||snake.x[0]>595||snake.y[0]<45||snake.y[0]>445){snake.life=1; /*置蛇死标记*/break;}/*从蛇的第四节启初推断是可碰到自己,*/for(i=3;i<snake.node;i++){ if(snake.x[i]==snake.x[0]&&snake.y[i]==snake.y[0]){snake.life=1; /*置蛇死标记*/break;}}if(snake.life==1) /*以上二种推断以去,如果蛇死便跳出内循环*/break; /*跳出while(!kbhit)*/if(snake.x[0]==food.x&&snake.y[0]==food.y) /*吃到苹果以去*/{setcolor(BLACK); /*把画里上的苹果揩除*/circle(food.x,food.y,5);snake.node++; /*蛇的身体少一节*/food.yes=1; /*画里上需要出现新的苹果*/score+=10; /*出吃一个苹果减少10分*/if(score%50==0) /*吃够5个苹果加进下一关*/{level+=1; /*关数加1*/gamespeed-=60; /*统造速度的值缩小60,以便加赶快度*/}}setcolor(RED); /*画出红色蛇的循环*/setfillstyle(SOLID_FILL,RED); /*用圆画出红色蛇头*/fillellipse(snake.x[0],snake.y[0],5,5);setcolor(GREEN);setfillstyle(SOLID_LINE,GREEN);circle(snake.x[0],snake.y[0],1); /*对付蛇头弥补绿色小圆动做眼睛*/setcolor(RED);setfillstyle(SOLID_FILL,BLUE);for(i=1;i<snake.node;i++) /*用圆画出红色蛇身*/{setcolor(RED);setfillstyle(SOLID_FILL,BLUE);fillellipse(snake.x[i],snake.y[i],5,5); /*对付每节蛇身用蓝色弥补*/setcolor(CYAN);circle(snake.x[i],snake.y[i],1); /*用青色小圆画正在每节蛇身上*/}delay(gamespeed); /*延缓gamespeed毫秒,以便统造蛇的爬止速度*/setcolor(BLACK); /*用背景致乌色去除蛇的末尾一节*/circle(snake.x[snake.node-1],snake.y[snake.node-1],5) ;setfillstyle(SOLID_FILL,BLACK);fillellipse(snake.x[snake.node-1],snake.y[snake.node-1],5,5);}if(snake.life==1) break; /*如果蛇死便跳出循环*/key=bioskey(0); /*接支按键*/if(key==esc) break; /*按esc键退出*//*推断是可往好异的目标疏通*/else if(key==up&&snake.direction!=4)snake.direction=3;else if(key==right&&snake.direction!=2)snake.direction=1;else if(key==left&&snake.direction!=1)snake.direction=2;else if(key==down&&snake.direction!=3)snake.direction=4;} /*endwhile(1)*/} /*中断游戏*//*读与文献支配函数*/void readfiles(){FILE * fpread;/*如果文献不存留,则创造1个空文献,可则挨启该文献*/if((fpread=fopen(filename,"ab+"))==NULL){printf("cant't open the file person.dat! ");exit(0);}if(fgetc(fpread)==EOF) /*如果文献真量为空*/initscorefiles(); /*调用函数举止记录初初化处事*/rewind(fpread); /*沉新复位文献位子指针*/fread(per,sizeof(struct person),5,fpread);fclose(fpread); /*关关排止榜文献*/}/*写进文献支配函数*/void writefiles(struct person *tmp){FILE * fpwrite;/*以读写办法挨启文献,文献内本有的数据将被浑空*/if((fpwrite=fopen(filename,"wb+"))==NULL){printf("cant't open the file person.dat! ");exit(0);}fwrite(tmp,sizeof(struct person),5,fpwrite);fclose(fpwrite);}/*初初化记录函数*/void initscorefiles(){int i;struct person a[5];for(i=0;i<5;i++){a[i].score=0; /*5人的分数为0*/strcpy(a[i].name,"nobody"); /*5人的名为nobody*/}writefiles(a); /*调用记录写进函数*/}/*排序函数,如果玩家分数超出最矮记录,则将玩家分数拔出到符合的位子,共时简略本先的最矮记录 */void comparescore(struct person des)。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
case left:
SnakeBody[SnakeHead]=i-1;
break;
case right:
SnakeBody[SnakeHead]=i+1;
break;
}
if (!BITTEST(Ground.bitarray,SnakeBody[SnakeHead]))
while (BITTEST(Ground.bitarray, SnakeFoodPosition))
{
SnakeFoodPosition+=SnakeLong;
SnakeFoodPosition=SnakeFoodPosition%(64*128-1);
}
SnakeDirection=left;
break;
case SCANCODE_6:
SnakeDirection=right;
break;
}
}
BITSET(Ground.bitarray,332);
SnakeBody[0]=330;
SnakeBody[1]=331;
SnakeBody[2]=332;
SnakeHead=2;
SnakeTail=0;
SnakeLong=3;
food();
SnakeDirection=up;
if (row<64)
{
LCDCMD(row+LCDCMDVERADDRESS); // 起始列
LCDWriteLeft(Ground.LCDarray[index]);
}
else
{
LCDCMD(row-64+LCDCMDVERADDRESS); // 起始列
IMH=0x0; // 指定xint5中断
IML=0x0a0;
ICR=0xff; // 清除等待的中断
IER=0x23; // 使能xint5中断
CSR=CSR|1; // 开中断
}
void interrupt XINT5() //中断响应函数
LCDWriteRight(Ground.LCDarray[index]);
}
}
void InitInterrupt(void)
{
// 设置中断控制寄存器
CSR&=0xfffffffe; // 关中断 GIE=0
ISTP=0x00000c00; // 重置中断向量表到0C00h
#define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b))
#define BITCLEAR(a, b) ((a)[BITSLOT(b)] &= ~BITMASK(b))
#define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b))
#define BITNSLOTS(nb) ((nb + CHAR_BIT - 1) / CHAR_BIT)
#define win 2
#define fail 1
#define running 0
#define up 1
#define down 2
#define left 3
#define right 4
{
Ground.bitarray[i]=0;
}
//memset(Ground.LCDarray, 0, 4*16);
for(i=0;i<64;i++)
{
BITSET(Ground.bitarray,i);
BITSET(Ground.bitarray,127*64+i);
SnakeHead=SnakeHead%20;
switch (SnakeDirection)
{
case up:
SnakeBody[SnakeHead]=i-64;
break;
case down:
SnakeBody[SnakeHead]=i+64;
break;
#include "ICETEK-C6713-A.h"
#include <limits.h> /* for CHAR_BIT */
#define BITMASK(b) (128>>((b) % CHAR_BIT))
#define BITSLOT(b) ((b) / CHAR_BIT)
Selse if (SnakeBody[SnakeHead]==SnakeFoodPosition)
{
BITSET(Ground.bitarray,SnakeBody[SnakeHead]);
SnakeLong++;
food();
move();
draw(BITSLOT(SnakeBody[SnakeHead]));
draw(BITSLOT(SnakeTailIndex));
Delay(500);
}
}
}
void Init()
{
int i;
for (i=0;i<64*128/8;i++)
{
BITSET(Ground.bitarray,SnakeBody[SnakeHead]);
BITCLEAR(Ground.bitarray,SnakeBody[SnakeTail]);
SnakeTailIndex=SnakeBody[SnakeTail];
SnakeTail++;
main()
{
init_emif(); // 初始化emif
InitCTR(); // 初始化ICETEK-CTR
TurnOnLCD(); // 打开显示
LCDCLS(); // 清除显示内存
LCDCMD(LCDCMDSTARTLINE); // 设置显示起始行=0
GameStatus=running;
for (i=0;i<64*128/8;i++)
{
draw(i);
}
}
void food()
{
srand((unsigned) time(0));
SnakeFoodPosition=rand()%(64*128-1);
void food();
void Init();
void move();
void draw(int index);
void InitInterrupt(void);
int SnakeFoodPosition,SnakeLong;
int SnakeBody[20],SnakeHead,SnakeTail,GameStatus,SnakeDirection,SnakeTailIndex;
{
int key;
key=Getkey();
switch(key)
{
case SCANCODE_2:
SnakeDirection=down;
break;
case SCANCODE_8:
SnakeDirection=up;
break;
case SCANCODE_4:
BITSET(Ground.bitarray,SnakeFoodPosition);
draw(BITSLOT(SnakeFoodPosition));
}
void move()
{
int i;
i=SnakeBody[SnakeHead]; //暂存蛇头上一位置
SnakeHead++;
}
for(i=1;i<127;i++)
{
BITSET(Ground.bitarray,i*64);
BITSET(Ground.bitarray,i*63+63);
}
BITSET(Ground.bitarray,330);
BITSET(Ground.bitarray,331);
if (SnakeLong==20) GameStatus=win;
}
else
GameStatus=fail;
}
void draw(int index)
{
int page;
int row;
page=index%8;
row=index/8;
LCDCMD(7-page+0x0b8); // 设置操作页
Init();
InitInterrupt();
while(1)
{
switch (GameStatus)
{
case win:
Init();
break;
case fail:
Init();
break;
case running:
union
{
char bitarray[BITNSLOTS(64*128 )];
unsigned char LCDarray[64*128/8];
}Ground;
int SnakeFoodPosition,SnakeLong;
相关文档
最新文档