贪吃蛇游戏源代码

合集下载

贪吃蛇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);});}}。

贪吃蛇小游戏源代码

贪吃蛇小游戏源代码
return 1;
}
tail=(tail+1)%80;
qipan[zuobiao[0][head]][zuobiao[1][head]]='*';
head=(head+1)%80;
zuobiao[0][head]=x;
zuobiao[1][head]=y;
qipan[zuobiao[0][head]][zuobiao[1][head]]='#';
/*处理棋盘*/
char qipan[20][80];//定义棋盘
for(i=0;i<20;i++)
for(j=0;j<80;j++)
qipan[i][j]=' ';//初始化棋盘
for(i=0;i<80;i++)
qipan[0][i]='_';
for(i=0;i<20;i++)
qipan[i][0]='|';
printf("Input your game speed,please.(e.g.300)\n");
scanf("%d",&gamespeed);
while(direction!='q')
{
system("cls");
for(i=0;i<20;i++)//打印出棋盘
for(j=0;j<80;j++)
direction='q';
system("cls");
printf("GAME OVER!\n");

贪吃蛇游戏源代码(C++)

贪吃蛇游戏源代码(C++)

贪吃蛇游戏源代码(C++)#include <windows.h>#include <stdlib.h>#include <conio.h>#include <time.h>#include <cstring>#include <cstdio>#include <iostream>#define N 22using namespace std;int gameover;int x1, y1; // 随机出米int x,y;long start;//===================================== ==//类的实现与应用initialize//===================================== ==//下面定义贪吃蛇的坐标类class snake_position{public:int x,y; //x表示行,y表示列snake_position(){};void initialize(int &);//坐标初始化};snake_position position[(N-2)*(N-2)+1]; //定义贪吃蛇坐标类数组,有(N-2)*(N-2)个坐标void snake_position::initialize(int &j){x = 1;y = j;}//下面定义贪吃蛇的棋盘图class snake_map{private:char s[N][N];//定义贪吃蛇棋盘,包括墙壁。

int grade, length;int gamespeed; //前进时间间隔char direction; // 初始情况下,向右运动int head,tail;int score;bool gameauto;public:snake_map(int h=4,int t=1,int l=4,char d=77,int s=0):length(l),direction(d),head(h),tail(t),score(s){}void initialize(); //初始化函数void show_game();int updata_game();void setpoint();void getgrade();void display();};//定义初始化函数,将贪吃蛇的棋盘图进行初始化void snake_map::initialize(){int i,j;for(i=1;i<=3;i++)s[1][i] = '*';s[1][4] = '#';for(i=1;i<=N-2;i++)for(j=1;j<=N-2;j++)s[i][j]=' '; // 初始化贪吃蛇棋盘中间空白部分for(i=0;i<=N-1;i++)s[0][i] = s[N-1][i] = '-'; //初始化贪吃蛇棋盘上下墙壁for(i=1;i<=N-2;i++)s[i][0] = s[i][N-1] = '|'; //初始化贪吃蛇棋盘左右墙壁}//===================================== =======//输出贪吃蛇棋盘信息void snake_map::show_game(){system("cls"); // 清屏int i,j;cout << endl;for(i=0;i<N;i++){cout << '\t';for(j=0;j<N;j++)cout<<s[i][j]<<' '; // 输出贪吃蛇棋盘if(i==2) cout << "\t等级:" << grade;if(i==6) cout << "\t速度:" << gamespeed;if(i==10) cout << "\t得分:" << score << "分" ;if(i==14) cout << "\t暂停:按一下空格键" ;if(i==18) cout << "\t继续:按两下空格键" ;cout<<endl;}}//输入选择等级void snake_map::getgrade(){cin>>grade;while( grade>7 || grade<1 ){cout << "请输入数字1-7选择等级,输入其他数字无效" << endl;cin >> grade;}switch(grade){case 1: gamespeed = 1000;gameauto = 0;break;case 2: gamespeed = 800;gameauto = 0;break;case 3: gamespeed = 600;gameauto = 0;break;case 4: gamespeed = 400;gameauto = 0;break;case 5: gamespeed = 200;gameauto = 0;break;case 6: gamespeed = 100;gameauto = 0;break;case 7: grade = 1;gamespeed = 1000;gameauto = 1;break; }}//输出等级,得分情况以及称号void snake_map::display(){cout << "\n\t\t\t\t等级:" << grade;cout << "\n\n\n\t\t\t\t速度:" << gamespeed;cout << "\n\n\n\t\t\t\t得分:" << score << "分" ;}//随机产生米void snake_map::setpoint(){srand(time(0));do{x1 = rand() % (N-2) + 1;y1 = rand() % (N-2) + 1;}while(s[x1][y1]!=' ');s[x1][y1]='*';}char key;int snake_map::updata_game(){gameover = 1;key = direction;start = clock();while((gameover=(clock()-start<=gamespeed))&&!kbhit()); //如果有键按下或时间超过自动前进时间间隔则终止循环if(gameover){getch();key = getch();}if(key == ' '){while(getch()!=' '){};//这里实现的是按空格键暂停,按空格键继续的功能,但不知为何原因,需要按两下空格才能继续。

贪吃蛇游戏安卓源代码

贪吃蛇游戏安卓源代码

附录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语言小游戏源代码《贪吃蛇》
void main(void){/*主函数体,调用以下四个函数*/ init(); setbkcolor(7); drawk(); gameplay(); close(); }
void init(void){/*构建图形驱动函数*/ int gd=DETECT,gm; initgraph(&gd,&gm,""); cleardevice(); }
欢迎您阅读该资料希望该资料能给您的学习和生活带来帮助如果您还了解更多的相关知识也欢迎您分享出来让我们大家能共同进步共同成长
C 语言小游戏源代码《贪吃பைடு நூலகம்》
#define N 200/*定义全局常量*/ #define m 25 #include <graphics.h> #include <math.h> #include <stdlib.h> #include <dos.h> #define LEFT 0x4b00 #define RIGHT 0x4d00 #define DOWN 0x5000 #define UP 0x4800 #define Esc 0x011b int i,j,key,k; struct Food/*构造食物结构体*/ { int x; int y; int yes; }food; struct Goods/*构造宝贝结构体*/ { int x; int y; int yes; }goods; struct Block/*构造障碍物结构体*/ { int x[m]; int y[m]; int yes; }block; struct Snake{/*构造蛇结构体*/ int x[N]; int y[N]; int node; int direction; int life; }snake; struct Game/*构建游戏级别参数体*/ { int score; int level; int speed;

贪吃蛇 源代码

贪吃蛇 源代码

#include"stdafx.h"#include<iostream>#include<conio.h>#include<time.h>#include<windows.h>using namespace std;const int X=30,Y=15; //初始边界大小int level=1; //初始等级int length=3; //初始长度int food_bool=0; //食物是否存在int food_x,food_y; //食物存在的座标char direction='d'; //初始方向int success=1; //成功条件void SetPoint(int x,int y) //构造gotoxy函数{COORD s={x,y};SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),s);}struct body{ //构造蛇和墙体的身体int x,y;body *next;};body *head=new(struct body); //声明蛇头body *wall; //声明墙体的头节点class snake{ //构造蛇类public:void gaming(); //声明游戏的主函数void map(); //声明边界构造函数void paint_body(); //声明蛇体构造函数void food(); //声明创建食物函数void str_wall(); //声明墙体构造函数void add_wall(); //声明墙体添加函数};void snake::str_wall() //墙体构造函数{struct body *p=new(struct body); //声明并初始化操作节点wall=p; //让墙体头节点等于pp->x=(rand()+time(NULL))%(X-3)+2; //随机创建节点坐标p->y=(rand()+time(NULL))%(Y-3)+2;int k=0;while(k==0) //判断墙体是否出现在蛇身{k=1;struct body *q;q=head;while(q!=NULL){if(p->x==q->x&&p->y==q->y){k=0;p->x=(rand()+time(NULL))%(X-3)+2;p->y=(rand()+time(NULL))%(Y-3)+2;break;}q=q->next;}}SetPoint(p->x,p->y);cout<<"■";for(int i=0;i<10;i++){p->next=new(struct body); //构建10个初始墙体p=p->next;p->x=(rand()+time(NULL))%(X-3)+2;p->y=(rand()+time(NULL))%(Y-3)+2;while(k==0) //判断墙体是否出现在蛇身{k=1;struct body *q;q=head;while(q!=NULL){if(p->x==q->x&&p->y==q->y){k=0;p->x=(rand()+time(NULL))%(X-3)+2;p->y=(rand()+time(NULL))%(Y-3)+2;break;}q=q->next;}}k=0;SetPoint(p->x,p->y); //墙体出现位置正确时画出墙体cout<<"■";}p->next=NULL; //设置末节点为NULL}void snake::add_wall() //墙体添加函数{struct body *p;for(int i=0;i<3;i++) //判断墙体是否成立{p=new(struct body);int k=0;p->x=(rand()+time(NULL))%(X-3)+2;p->y=(rand()+time(NULL))%(Y-3)+2;while(k==0){k=1;struct body *q;q=head;while(q!=NULL){if(p->x==q->x&&p->y==q->y){k=0;p->x=(rand()+time(NULL))%(X-3)+2;p->y=(rand()+time(NULL))%(Y-3)+2;break;}q=q->next;}}p->next=wall;wall=p; //将新得到的墙体插入到头节点SetPoint(p->x,p->y);cout<<"■";}}void snake::food() //创建食物函数{int k;k=0;food_x=(rand()+time(NULL))%(X-3)+2;food_y=(rand()+time(NULL))%(Y-3)+2;body *p;while(k==0){k=1;p=wall;while(p!=NULL) //判断食物是否出现在墙体上{if(p->x==food_x&&p->y==food_y){k=0;food_x=(rand()+time(NULL))%(X-3)+2;food_y=(rand()+time(NULL))%(Y-3)+2;break;}p=p->next;}p=head;while(p!=NULL) //判断食物是否出现在蛇身上{if(p->x==food_x&&p->y==food_y){k=0;food_x=(rand()+time(NULL))%(X-3)+2;food_y=(rand()+time(NULL))%(Y-3)+2;break;}p=p->next;}}SetPoint(food_x,food_y); //画出食物cout<<"*";food_bool=1;}void snake::map() //边界构造函数{system("cls"); //清屏for(int i=0;i<=X;i+=2) //画出墙体{SetPoint(i,0);cout<<"■";}for(int i=1;i<Y;i++){SetPoint(0,i);cout<<"■";}for(int i=1;i<Y;i++){SetPoint(X,i);cout<<"■";}for(int i=0;i<=X+1;i+=2){SetPoint(i,Y);cout<<"■";}SetPoint(X+5,3); //画出信息cout<<"长度:"<<length;SetPoint(X+5,5);cout<<"等级:"<<level;}void snake::paint_body() //蛇体构造函数{body *body; //构建身体,比较丑,但是不想改了head->x=X/2; //游戏开始时,蛇出现在地图中心,此时长度为三 head->y=Y/2;body=new(struct body);head->next=body;body->x=head->x-1;body->y=head->y;body->next=new(struct body);body->next->x=head->x-2;body->next->y=head->y;body->next->next=NULL;SetPoint(head->x,head->y);cout<<"*";SetPoint(head->next->x,head->next->y);cout<<"*";SetPoint(head->next->next->x,head->next->next->y);cout<<"*";}void snake::gaming() //这里是gaming!!!!!!!!!!{int time_begin=clock();char x;char x1;struct body *newb;newb=new(body);map(); //构造边界paint_body(); //构造蛇身体str_wall(); //构造墙体food(); //构造一个食物x=direction; //读取方向while(1){if(_kbhit()) //如果读入缓存中有输入{x=_getch();while(_kbhit()) //读掉剩下的输入缓存中的数_getch();}if(x==' '){_getch();x=direction;}elseif((x=='w'||x=='W')&&direction!='s'){newb->x=head->x;newb->y=head->y-1;x1='w';}else if((x=='a'||x=='A')&&direction!='d'){newb->x=head->x-1;newb->y=head->y;x1='a';}else if((x=='s'||x=='S')&&direction!='w'){newb->x=head->x;newb->y=head->y+1;x1='s';}else if((x=='d'||x=='D')&&direction!='a'){newb->x=head->x+1;newb->y=head->y;x1='d';}else{if(x1=='w'){newb->x=head->x;newb->y=head->y-1;}else if(x1=='a'){newb->x=head->x-1;newb->y=head->y;}else if(x1=='s'){newb->x=head->x;newb->y=head->y+1;}else if(x1=='d'){newb->x=head->x+1;newb->y=head->y;}}if(clock()-time_begin>(500-level*45))//移动蛇身,随时间加快{time_begin=clock();{direction=x1;newb->next=head;head=newb;}if(head->x==food_x&&head->y==food_y)//遇见食物吃掉,食物小时{food_bool=0;}if(head->x==X||head->y==Y||head->x==0||head->y==0)//遇到墙体死亡{success=0;}else{body *p=head->next;if(food_bool==1){while(p->next!=NULL){if(p->x==head->x&&p->y==head->y)success=0;p=p->next;}}else{while(p!=NULL){if(p->x==head->x&&p->y==head->y)success=0;p=p->next;}}}{body *p=wall;while(p!=NULL){if(p->x==head->x&&p->y==head->y)//遇到墙体死亡success=0;p=p->next;}}if(success==0){system("cls");cout<<"你失败了"<<endl;cout<<"死的时候你的长度为"<<length<<endl;break;}if(food_bool==1){body *p=head;while(p->next->next!=NULL)//将指针移到末尾{p=p->next;}SetPoint(p->next->x,p->next->y);//蛇身移动后最后一部分消失cout<<" ";delete(p->next);p->next=NULL;}else{food();length++;if(length%5==0){level++;add_wall();}if(level==10)success=2;SetPoint(X+5,3);cout<<"长度:"<<length;SetPoint(X+5,5);cout<<"等级:"<<level;}{SetPoint(head->x,head->y);//吃到食物后蛇身增加cout<<"*";}if(success==2){system("cls");cout<<"你通关了"<<endl;break;}newb=new(body);}SetPoint(X+30,Y);}}void prompt(){cout<<"****************************************************"<<endl;cout<<"* 欢迎进入贪吃蛇世界 *"<<endl;cout<<"* *代表蛇身或食物 *"<<endl;cout<<"* ■代表墙 *"<<endl;cout<<"* *"<<endl;cout<<"* *"<<endl;cout<<"* 初试身体长度为3,每到5的倍数升一级 *"<<endl;cout<<"* *"<<endl;cout<<"* wasd操控,注意切换输入法哦 *"<<endl;cout<<"* *"<<endl;cout<<"* 每升一级速度加快,同时增加三个墙体 *"<<endl;cout<<"* *"<<endl;cout<<"* 按任意键开始游戏 *"<<endl;cout<<"* ps:按空格键暂停 *"<<endl;cout<<"****************************************************"<<endl;_getch();}int main(int argc,char argv[]){snake H;prompt();system("cls");H.gaming();system("pause");return 0;}。

贪吃蛇游戏源代码

贪吃蛇游戏源代码

贪吃蛇游戏源代码#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <graphics.h>#include <bios.h>#include <dos.h>#include<string.h>#define LEFT_MARGIN 140#define FRAME_UNIT_WIDTH 25#define FRAME_UNIT_HEIGHT 15#define BOX_SIZE 15#define WINDOW_WIDTH 640#define WINDOW_HEIGHT 480#define SNAK_DEFAULT_POS_X 10#define SNAK_DEFAULT_POS_Y 5#define SMD_UP 1#define SMD_DOWN 2#define SMD_RIGHT 3#define SMD_LEFT 4#define UP_MOVE 72#define DOWN_MOVE 80#define LEFT_MOVE 75#define RIGHT_MOVE 77#define STEP_MOVE 7#define GAME_STOP 57#define ESC_OUT 1#define GENERAT_EGG 8#define NO_EVENT 0#define Boolean int#define TRUTH 1#define FALS 0#define Type_GAMESTATUS int#define ON_PAL YING 2#define WINNER 1#define GAMEOVER 0#define TIMEINTERV AL 6typedef struct{int p_X;int p_Y;}POS_in_Fram;typedef struct SNode{POS_in_Fram cur_pos;int color;struct SNode *next;}SNode, *LSNode;typedef struct{int direction;int len;POS_in_Fram Head_pre_pos; POS_in_Fram Head_cur_pos;int Head_color;LSNode next;Boolean Dead;}SNAK;typedef struct{POS_in_Fram egg_pos;int egg_color;}EggType;SNAK obj_snake;EggType obj_egg;int Message_Event;int ScoreTotal;int SpeedLevel;Type_GAMESTATUS GameStat;void set_Message_Event(int T){Message_Event = T;}int get_Message_Event(){return(Message_Event);}void clear_ScoreTotal(){ScoreTotal = 0;}int get_ScoreTotal(){return(ScoreTotal);}void draw_ScoreTotal(){char text_buffer[20];int ul_X, ul_Y;ul_X = LEFT_MARGIN;ul_Y = WINDOW_HEIGHT - BOX_SIZE * (FRAME_UNIT_HEIGHT - 4); setcolor(BLUE);sprintf(text_buffer, "Score Total: %d", get_ScoreTotal());moveto(ul_X, ul_Y);outtext(text_buffer);setcolor(YELLOW);ScoreTotal++;sprintf(text_buffer, "Score Total: %d", get_ScoreTotal());moveto(ul_X, ul_Y);outtext(text_buffer);}void init_SpeedLevel(){SpeedLevel = 1;}int get_SpeedLevel(){return(SpeedLevel);}void draw_SpeedLevel(int old_l, int new_l){char text_buffer[20];int ul_X, ul_Y;ul_X = LEFT_MARGIN;ul_Y = WINDOW_HEIGHT - BOX_SIZE * (FRAME_UNIT_HEIGHT - 4); setcolor(BLUE);sprintf(text_buffer, "Speed Level: %d", old_l);moveto(ul_X, ul_Y + textheight("H") * 2);outtext(text_buffer);setcolor(YELLOW);sprintf(text_buffer, "Speed Level: %d", new_l);moveto(ul_X, ul_Y + textheight("H") * 2);outtext(text_buffer);}void setSpeedLevel(int score){if(score >= 0 && score < 20){draw_SpeedLevel(get_SpeedLevel(), 1);SpeedLevel = 1;}else if(score >= 20 && score < 50){draw_SpeedLevel(get_SpeedLevel(), 2);SpeedLevel = 2;}else if(score >= 50 && score < 100){draw_SpeedLevel(get_SpeedLevel(), 3);SpeedLevel = 3;}else{draw_SpeedLevel(get_SpeedLevel(), 4);SpeedLevel = 4;}}void set_GameStat(Type_GAMESTATUS state){GameStat = state;}Type_GAMESTATUS get_GameStat() {return(GameStat);}void set_SnakeDead(Boolean T){obj_snake.Dead = T;}Boolean Is_SnakeDead(){return(obj_snake.Dead);}int get_SHOD(int T){switch(T){case SMD_UP:return(SMD_DOWN);case SMD_DOWN:return(SMD_UP);case SMD_RIGHT:return(SMD_LEFT);case SMD_LEFT:return(SMD_RIGHT);}}int get_SHD(){return(obj_snake.direction);}Boolean findPointInSnake(int pX, int pY) {LSNode p;if((obj_snake.Head_cur_pos.p_X == pX) && (obj_snake.Head_cur_pos.p_Y == pY))return(TRUTH);for(p = obj_snake.next;p != NULL;p = p->next){if((p->cur_pos.p_X == pX) && (p->cur_pos.p_Y == pY))return(TRUTH);}return(FALS);}Boolean Is_SnakEating(){if((obj_snake.Head_pre_pos.p_X == obj_egg.egg_pos.p_X) && (obj_snake.Head_pre_pos.p_Y == obj_egg.egg_pos.p_Y))return(TRUTH);elsereturn(FALS);}void Init_obj_snake(){obj_snake.direction = SMD_RIGHT;obj_snake.len = 1;obj_snake.Head_cur_pos.p_X = SNAK_DEFAULT_POS_X;obj_snake.Head_cur_pos.p_Y = SNAK_DEFAULT_POS_Y;obj_snake.Head_pre_pos = obj_snake.Head_cur_pos;obj_snake.Head_color = RED;obj_snake.next = NULL;obj_snake.Dead = FALS;}void Init_obj_egg(){obj_egg.egg_pos.p_X = 0;obj_egg.egg_pos.p_Y = 0;obj_egg.egg_color = BLACK;}void RegistryGraphicMode(){int Driver, Mode;detectgraph(&Driver, &Mode);initgraph(&Driver, &Mode,"");}void Draw_FrameInWindow(int f_ul_X, int f_ul_Y, int f_dr_X, int f_dr_Y, int W, int H) {int i, x, y;rectangle(f_ul_X - 1, f_ul_Y - 1, f_dr_X + 1, f_dr_Y + 1);setfillstyle(SOLID_FILL, BLACK);bar(f_ul_X, f_ul_Y, f_dr_X, f_dr_Y);setcolor(DARKGRAY);for(i = 1;i < W;i++){x = f_ul_X + i * BOX_SIZE;line(x, f_ul_Y, x, f_dr_Y);}for(i = 1;i < H;i++){y = f_ul_Y + i * BOX_SIZE;line(f_ul_X, y, f_dr_X, y);}}void Draw_mainGraphWindow(){int ul_X, ul_Y, dr_X, dr_Y;setfillstyle(SOLID_FILL, BLUE);bar(0, 0, WINDOW_WIDTH - 1, WINDOW_HEIGHT - 1);ul_X = LEFT_MARGIN;ul_Y = WINDOW_HEIGHT - BOX_SIZE * (FRAME_UNIT_HEIGHT * 2 - 3);dr_X = LEFT_MARGIN + BOX_SIZE * FRAME_UNIT_WIDTH;dr_Y = WINDOW_HEIGHT - BOX_SIZE * (FRAME_UNIT_HEIGHT - 3);Draw_FrameInWindow(ul_X, ul_Y, dr_X, dr_Y, FRAME_UNIT_WIDTH, FRAME_UNIT_HEIGHT);ul_X = LEFT_MARGIN;ul_Y = WINDOW_HEIGHT - BOX_SIZE * (FRAME_UNIT_HEIGHT - 4);settextjustify(LEFT_TEXT, TOP_TEXT);settextstyle(DEFAULT_FONT, HORIZ_DIR, 1);setcolor(YELLOW);sprintf(text_buffer, "Score Total: %d", get_ScoreTotal());moveto(ul_X, ul_Y);outtext(text_buffer);sprintf(text_buffer, "Speed Level: %d", get_SpeedLevel());moveto(ul_X, gety() + textheight("H") * 2);outtext(text_buffer);strcpy(text_buffer, "EXIT: ESC Button");moveto(ul_X, gety() + textheight("H") * 2);outtext(text_buffer);strcpy(text_buffer, "Created By: qiuyongfei");moveto(ul_X, gety() + textheight("H") * 2);outtext(text_buffer);strcpy(text_buffer, "Class: 04hulianwang29hao");moveto(ul_X, gety() + textheight("H") * 2);outtext(text_buffer);strcpy(text_buffer, "UP: Up Arrow");moveto(ul_X + textwidth("H") * 30, ul_Y);strcpy(text_buffer, "DOWN: Down Arrow");moveto(ul_X + textwidth("H") * 30, gety() + textheight("H") * 2);outtext(text_buffer);strcpy(text_buffer, "LEFT: Left Arrow");moveto(ul_X + textwidth("H") * 30, gety() + textheight("H") * 2);outtext(text_buffer);strcpy(text_buffer, "RIGHT: Right Arrow");moveto(ul_X + textwidth("H") * 30, gety() + textheight("H") * 2);outtext(text_buffer);strcpy(text_buffer, "STOP: Space Button");moveto(ul_X + textwidth("H") * 30, gety() + textheight("H") * 2);outtext(text_buffer);}void draw_egg(Boolean T){int ul_X, ul_Y;int color;ul_X = LEFT_MARGIN;ul_Y = WINDOW_HEIGHT - BOX_SIZE * (FRAME_UNIT_HEIGHT * 2 - 3);if(T == FALS)color = BLACK;elsecolor = obj_egg.egg_color;setfillstyle(SOLID_FILL, color);bar(ul_X + BOX_SIZE * obj_egg.egg_pos.p_Y + 1, ul_Y + BOX_SIZE * obj_egg.egg_pos.p_X + 1, ul_X + BOX_SIZE * (obj_egg.egg_pos.p_Y + 1) - 1, ul_Y + BOX_SIZE * (obj_egg.egg_pos.p_X + 1) - 1);}void Mapped_Draw(Boolean T){int ul_X, ul_Y;int Ax, Ay, Bx, By;int color;LSNode p;ul_X = LEFT_MARGIN;ul_Y = WINDOW_HEIGHT - BOX_SIZE * (FRAME_UNIT_HEIGHT * 2 - 3);if(T == FALS)color = BLACK;elsecolor = obj_snake.Head_color;setfillstyle(SOLID_FILL, color);Ax = ul_X + BOX_SIZE * obj_snake.Head_cur_pos.p_Y + 1;Ay = ul_Y + BOX_SIZE * obj_snake.Head_cur_pos.p_X + 1;Bx = ul_X + BOX_SIZE * (obj_snake.Head_cur_pos.p_Y + 1) - 1;By = ul_Y + BOX_SIZE * (obj_snake.Head_cur_pos.p_X + 1) - 1;bar(Ax, Ay, Bx, By);if(T == TRUTH){setfillstyle(SOLID_FILL, YELLOW);bar(Ax + 4, Ay + 4, Ax + 4 + 5, Ay + 4 + 5);}for(p = obj_snake.next;p != NULL;p = p->next){if(T == FALS)color = BLACK;elsecolor = p->color;setfillstyle(SOLID_FILL, color);Ax = ul_X + BOX_SIZE * p->cur_pos.p_Y + 1;Ay = ul_Y + BOX_SIZE * p->cur_pos.p_X + 1;Bx = ul_X + BOX_SIZE * (p->cur_pos.p_Y + 1) - 1;By = ul_Y + BOX_SIZE * (p->cur_pos.p_X + 1) - 1;bar(Ax, Ay, Bx, By);}}void draw_GS_GO_Surface(Type_GAMESTA TUS T){char text_buffer[40];settextjustify(LEFT_TEXT, TOP_TEXT);switch(T){case ON_PAL YING:settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 4);setcolor(LIGHTCY AN);strcpy(text_buffer, "ITEM - 2: Game.Greed Snake");moveto(100, 100);outtext(text_buffer);settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 1);setcolor(YELLOW);strcpy(text_buffer, "Please press any key to continue ...");moveto(150, 300);outtext(text_buffer);break;case GAMEOVER:settextstyle(GOTHIC_FONT, HORIZ_DIR, 8);setcolor(RED);strcpy(text_buffer, "GAME OVER");moveto(70, 80);outtext(text_buffer);settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 2);setcolor(YELLOW);strcpy(text_buffer, "Sorry!");moveto(160, 320);outtext(text_buffer);sprintf(text_buffer, "Total Score: %d", get_ScoreTotal());moveto(240, 320);outtext(text_buffer);sprintf(text_buffer, "Speed Level: %d", get_SpeedLevel());moveto(240, 350);outtext(text_buffer);break;case WINNER:settextstyle(GOTHIC_FONT, HORIZ_DIR, 8);setcolor(RED);strcpy(text_buffer, "YOU WIN !");moveto(80, 80);outtext(text_buffer);settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 2);setcolor(YELLOW);strcpy(text_buffer, "Congratulation!");moveto(120, 320);outtext(text_buffer);sprintf(text_buffer, "Total Score: %d", get_ScoreTotal());moveto(280, 320);outtext(text_buffer);sprintf(text_buffer, "Speed Level: %d", get_SpeedLevel());moveto(280, 350);outtext(text_buffer);break;default:break;}}void set_SH_Pre_Pos(int T){int H_pX, H_pY;H_pX = obj_snake.Head_cur_pos.p_X;H_pY = obj_snake.Head_cur_pos.p_Y;switch(T){case SMD_UP:if((H_pX - 1) < 0 || findPointInSnake(H_pX - 1, H_pY) == TRUTH){set_SnakeDead(TRUTH);return;}obj_snake.Head_pre_pos.p_X = H_pX - 1;obj_snake.Head_pre_pos.p_Y = H_pY;break;case SMD_DOWN:if((H_pX + 1) >= FRAME_UNIT_HEIGHT || findPointInSnake(H_pX + 1, H_pY) == TRUTH){set_SnakeDead(TRUTH);return;}obj_snake.Head_pre_pos.p_X = H_pX + 1;obj_snake.Head_pre_pos.p_Y = H_pY;break;case SMD_RIGHT:if((H_pY + 1) >= FRAME_UNIT_WIDTH || findPointInSnake(H_pX, H_pY + 1) == TRUTH){set_SnakeDead(TRUTH);return;}obj_snake.Head_pre_pos.p_X = H_pX;obj_snake.Head_pre_pos.p_Y = H_pY + 1;break;case SMD_LEFT:if((H_pY - 1) < 0 || findPointInSnake(H_pX, H_pY - 1) == TRUTH){set_SnakeDead(TRUTH);return;}obj_snake.Head_pre_pos.p_X = H_pX;obj_snake.Head_pre_pos.p_Y = H_pY - 1;break;}}Boolean set_SHD(int T){if(get_SHD() == T || get_SHOD(get_SHD()) == T) return(FALS);obj_snake.direction = T;return(TRUTH);}void process_SnakeNode(Boolean eated){int i;POS_in_Fram temp1_cur_pos, temp2_cur_pos; LSNode p, q;temp1_cur_pos = obj_snake.Head_cur_pos;obj_snake.Head_cur_pos = obj_snake.Head_pre_pos;p = obj_snake.next;for(i = 1;i < obj_snake.len;i++){temp2_cur_pos = p->cur_pos;p->cur_pos = temp1_cur_pos;temp1_cur_pos = temp2_cur_pos;p = p->next;}if(eated == TRUTH){q = (LSNode)malloc(sizeof(SNode));q->color = obj_egg.egg_color;q->cur_pos = temp1_cur_pos;if(obj_snake.len == 1){q->next = obj_snake.next;obj_snake.next = q;obj_snake.len++;return;}for(p = obj_snake.next;p->next != NULL;p = p->next);q->next = p->next;p->next = q;obj_snake.len++;}}void generate_Egg(){int temp_pX, temp_pY, temp_color;draw_egg(FALS);temp_pX = random(FRAME_UNIT_HEIGHT);temp_pY = random(FRAME_UNIT_WIDTH);while(findPointInSnake(temp_pX, temp_pY) == TRUTH){temp_pX = random(FRAME_UNIT_HEIGHT);temp_pY = random(FRAME_UNIT_WIDTH);}obj_egg.egg_pos.p_X = temp_pX;obj_egg.egg_pos.p_Y = temp_pY;for(temp_color = random(16);temp_color == BLACK;temp_color = random(16)); obj_egg.egg_color = temp_color;draw_egg(TRUTH);set_Message_Event(NO_EVENT);}void move_To(int T, Boolean step) {if(step == FALS){if(set_SHD(T) == FALS)goto Skip_1;}set_SH_Pre_Pos(T);if(Is_SnakeDead() == TRUTH) goto Skip_2;if(Is_SnakEating() == TRUTH) {Mapped_Draw(FALS);process_SnakeNode(TRUTH);Mapped_Draw(TRUTH);draw_ScoreTotal();setSpeedLevel(get_ScoreTotal());goto Skip_3;}else{Mapped_Draw(FALS);process_SnakeNode(FALS);Mapped_Draw(TRUTH);goto Skip_1;}Skip_1:set_Message_Event(NO_EVENT); return;Skip_2:set_Message_Event(ESC_OUT); return;Skip_3:set_Message_Event(GENERAT_EGG); return;}void pause_game(){while((bioskey(0) >> 8) != GAME_STOP);set_Message_Event(NO_EVENT);}void process_GameStat(Type_GAMESTATUS T) {LSNode p, q;switch(T){case ON_PAL YING:draw_GS_GO_Surface(ON_PAL YING);break;case WINNER:cleardevice();draw_GS_GO_Surface(WINNER);getch();break;case GAMEOVER:cleardevice();draw_GS_GO_Surface(GAMEOVER);getch();break;default:break;}p = obj_snake.next;while(p != NULL){q = p->next;free(p);}}Boolean IsWinner(){if(get_SpeedLevel() == 4)return(TRUTH);elsereturn(FALS);}Boolean IsGameOver(){if(get_Message_Event() == ESC_OUT)return(TRUTH);elsereturn(FALS);}Boolean IsTimeOut(){static long temp, sourc;temp = biostime(0, sourc);if((temp - sourc) < (TIMEINTERVAL - SpeedLevel))return FALS;else{sourc = temp;return TRUTH;}}void getMessageEvent(){if(get_Message_Event() == GENERAT_EGG || get_Message_Event() == ESC_OUT || get_Message_Event() == GAME_STOP)return;if(IsTimeOut() == TRUTH){set_Message_Event(STEP_MOVE);}if(bioskey(1)){set_Message_Event(bioskey(0) >> 8); return;}}void dispatchMessage_Event(){switch(get_Message_Event()){case UP_MOVE:move_To(SMD_UP, FALS);break;case DOWN_MOVE:move_To(SMD_DOWN, FALS);break;case LEFT_MOVE:move_To(SMD_LEFT, FALS);break;case RIGHT_MOVE:move_To(SMD_RIGHT, FALS);break;case STEP_MOVE:move_To(get_SHD(), TRUTH);break;case GENERA T_EGG:generate_Egg();break;case GAME_STOP:pause_game();break;case ESC_OUT:break;default:set_Message_Event(NO_EVENT); }}void main(){RegistryGraphicMode();set_GameStat(ON_PAL YING);process_GameStat(get_GameStat());clear_ScoreTotal();Init_obj_snake();Init_obj_egg();init_SpeedLevel();randomize();set_Message_Event(GENERAT_EGG);getch();cleardevice();Draw_mainGraphWindow();do{getMessageEvent(); dispatchMessage_Event();if(IsWinner() == TRUTH){set_GameStat(WINNER);break;}if(IsGameOver() == TRUTH){set_GameStat(GAMEOVER); break;}}while(1);process_GameStat(get_GameStat());closegraph(); }。

贪吃蛇源代码

贪吃蛇源代码

import java.awt.*;import java.awt.event.*;public class GreedSnake //主类{public static void main(String[] args) {// TODO Auto-generated method stubnew MyWindow();}}class MyPanel extends Panel implements KeyListener,Runnable//自定义面板类,继承了键盘和线程接口{Button snake[]; //定义蛇按钮int shu=0; //蛇的节数int food[]; //食物数组boolean result=true; //判定结果是输还是赢Thread thread; //定义线程static int weix,weiy; //食物位置boolean t=true; //判定游戏是否结束int fangxiang=0; //蛇移动方向int x=0,y=0; //蛇头位置MyPanel(){setLayout(null);snake=new Button[20];food=new int [20];thread=new Thread(this);for(int j=0;j<20;j++){food[j]=(int)(Math.random()*99);//定义20个随机食物}weix=(int)(food[0]*0.1)*60; //十位*60为横坐标weiy=(int)(food[0]%10)*40; //个位*40为纵坐标for(int i=0;i<20;i++){snake[i]=new Button();}add(snake[0]);snake[0].setBackground(Color.black);snake[0].addKeyListener(this); //为蛇头添加键盘监视器snake[0].setBounds(0,0,10,10);setBackground(Color.cyan);}public void run() //接收线程{while(t){if(fangxiang==0)//向右{try{x+=10;snake[0].setLocation(x, y);//设置蛇头位置if(x==weix&&y==weiy) //吃到食物{shu++;weix=(int)(food[shu]*0.1)*60;weiy=(int)(food[shu]%10)*40;repaint(); //重绘下一个食物add(snake[shu]); //增加蛇节数和位置snake[shu].setBounds(snake[shu-1].getBounds()); }thread.sleep(100); //睡眠100ms}catch(Exception e){}}else if(fangxiang==1)//向左{try{x-=10;snake[0].setLocation(x, y);if(x==weix&&y==weiy){shu++;weix=(int)(food[shu]*0.1)*60;weiy=(int)(food[shu]%10)*40;repaint();add(snake[shu]);snake[shu].setBounds(snake[shu-1].getBounds()); }thread.sleep(100);}catch(Exception e){}}else if(fangxiang==2)//向上{try{y-=10;snake[0].setLocation(x, y);if(x==weix&&y==weiy){shu++;weix=(int)(food[shu]*0.1)*60;weiy=(int)(food[shu]%10)*40;repaint();add(snake[shu]);snake[shu].setBounds(snake[shu-1].getBounds());}thread.sleep(100);}catch(Exception e){}}else if(fangxiang==3)//向下{try{y+=10;snake[0].setLocation(x, y);if(x==weix&&y==weiy){shu++;weix=(int)(food[shu]*0.1)*60;weiy=(int)(food[shu]%10)*40;repaint();add(snake[shu]);snake[shu].setBounds(snake[shu-1].getBounds());}thread.sleep(100);}catch(Exception e){}}int num1=shu;while(num1>1)//判断是否咬自己的尾巴{if(snake[num1].getBounds().x==snake[0].getBounds().x&&snake[num1].getBounds().y==snake[0]. getBounds().y){t=false;result=false;repaint();}num1--;}/*if(x<0||x>=this.getWidth()||y<0||y>=this.getHeight())//判断是否撞墙{t=false;result=false;repaint();}*/int num=shu;while(num>0) //设置蛇节位置{snake[num].setBounds(snake[num-1].getBounds());num--;}if(shu==5) //如果蛇节数等于15则胜利{t=false;result=true;repaint();}}}public void keyPressed(KeyEvent e) //按下键盘方向键{if(e.getKeyCode()==KeyEvent.VK_RIGHT)//右键{if(fangxiang!=1)//如果先前方向不为左fangxiang=0;}else if(e.getKeyCode()==KeyEvent.VK_LEFT){ if(fangxiang!=0)fangxiang=1;}else if(e.getKeyCode()==KeyEvent.VK_UP){ if(fangxiang!=3)fangxiang=2;}else if(e.getKeyCode()==KeyEvent.VK_DOWN){ if(fangxiang!=2)fangxiang=3;}}public void keyTyped(KeyEvent e){}public void keyReleased(KeyEvent e){}public void paint(Graphics g) //在面板上绘图{int x1=this.getWidth()-1;int y1=this.getHeight()-1;g.setColor(Color.red);g.fillOval(weix, weiy, 10, 10);//食物g.drawRect(0, 0, x1, y1); //墙if(t==false&&result==false)g.drawString("游戏结束", 250, 200);//输出游戏失败else if(t==false&&result==true)g.drawString("你赢了", 250, 200);//输出游戏成功}}class MyWindow extends Frame implements ActionListener//自定义窗口类{MyPanel my;Button btn;Panel panel;MyWindow(){super("GreedSnake");my=new MyPanel();btn=new Button("begin");panel=new Panel();btn.addActionListener(this);panel.add(new Label("begin后请按Tab键选定蛇"));panel.add(btn);panel.add(new Label("按上下左右键控制蛇行动"));add(panel,BorderLayout.NORTH);add(my,BorderLayout.CENTER);setBounds(100,100,610,500);setVisible(true);validate();addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}public void actionPerformed(ActionEvent e)//按下begin按钮{if(e.getSource()==btn){try{my.thread.start(); //开始线程my.validate();}catch(Exception ee){}}}}。

贪吃蛇源代码

贪吃蛇源代码

// proj_test.cpp : Defines the entry point for the console application./*设计思路:1、首先开辟单链表,内有3个节点表示蛇身2、蛇每移动一次,开辟新节点,加入链表头结点作为蛇头,释放尾部节点,形成移动效果3、随机产生食物,若在移动中吃到食物,则本次周期无需释放尾部节点,蛇身加长按键指示:上:W下:S左:A右:D加速: 1减速:2*///头文件定义#include "stdafx.h"#include<stdio.h>#include <graphics.h>#include <malloc.h>#include <conio.h>#include <stdlib.h>#include <time.h>#include <math.h>#include <windows.h>#define Hori_Len 30 //水平格数struct node *FindSecTailNode(struct node *Pnode); //函数功能:找到尾部前一节点,以便清除尾节点struct node *MoveNextStep(struct node *headnode,int direction); //函数功能:开辟新节点,清除尾节点,形成移动效果struct node *InitNode(); //函数功能:初始化蛇身,开辟单链表,内含3个节点;void DrawSnake(struct node *headnod); //函数功能:绘制蛇身int CheckSnake(struct node *p); //函数功能:错误检测,如果到达边界,返回错误标志void delay(); //函数功能:延时-决定蛇移动速度int keydown(int *z); //函数功能:获取键盘输入void drawDot(int x,int y); //函数功能:绘图--绘点void ReMoveDot(int x,int y); //函数功能:黑色填充目标点void mkfood(struct node *p); //函数功能:产生食物void SpeedCtrl(struct node *TempNode,struct node *HeadNode);//速度控制函数void RecordDisp(); //打印游戏纪录void InitFill() ;//初始化填充struct node{int x;int y;struct node *next;};int cnt_X=100;int food[2]={2,15};int check_result=1;int timelenX=5000;int Dire=2;int speed=450;int fen=0;//积分int jilu;//最高分记录char jiluzhe[20];char ch1[10];char ch2[10];char ch3[10];int main(){FILE *fp;//从文件载入最高记录if((fp=fopen("Record.txt","r"))==NULL)jilu=0;else {fgets(jiluzhe,20,fp);fscanf(fp,"%d",&jilu);}// fclose (fp);struct node *MoveNode;MoveNode=InitNode();initgraph(600, 600); // 初始化图形空间mkfood(MoveNode);//产生食物InitFill();//初始化填充RecordDisp();for(;;){//delay();Sleep(600-speed);int temp_dir=Dire;Dire=keydown(&Dire);if(Dire==5) //新增暂停功能{outtextxy(300,300,"暂停");getch();Dire=temp_dir;outtextxy(300,300," ");}if(MoveNode!=NULL){MoveNode=MoveNextStep(MoveNode,Dire);if(check_result==0){//closegraph();break;//return 0;}DrawSnake(MoveNode);}//Sleep(timelenX/55);}setfont(50,0,"宋体");setcolor(YELLOW);outtextxy(175,250,"GAMEOVER!"); /*setcolor(WHITE);Sleep(1000);jilu=0;if (fen>=jilu){strcpy(jiluzhe,"daqing");fp=fopen("Record.txt","w");fprintf(fp,"%s\n%d",jiluzhe,fen);fclose (fp);Sleep(1000);}*/if (fen>=jilu){strcpy(jiluzhe,"Daqing56");fp=fopen("Record.txt","w");fprintf(fp,"%s\n%d",jiluzhe,fen);fclose (fp);}Sleep(1000);closegraph();return 0;}void DrawSnake(struct node *headnod){struct node *TempNode=headnod;while(TempNode&&(TempNode->next!=NULL)){drawDot(TempNode->x,TempNode->y);TempNode=TempNode->next;}drawDot(TempNode->x,TempNode->y);}struct node *MoveNextStep(struct node *headnode,int direction){struct node *TempNode=(struct node *) malloc(sizeof(struct node));if(TempNode!=NULL)TempNode->next=headnode;switch(direction){case 1: //TempNode->x=headnode->x-1;TempNode->y=headnode->y;break;case 2:TempNode->x=headnode->x+1;TempNode->y=headnode->y;break;case 3:TempNode->x=headnode->x;TempNode->y=headnode->y-1;break;case 4:TempNode->x=headnode->x;TempNode->y=headnode->y+1;break;default:break;}check_result=CheckSnake(TempNode);if(check_result==0)//一旦游戏失败,函数返回{return TempNode;}if(!(TempNode->x==food[0]&&TempNode->y==food[1])) //检测没有吃掉食物,则去尾巴{struct node *tailnode, *Sectailnode=FindSecTailNode(TempNode);tailnode=Sectailnode->next;ReMoveDot(tailnode->x,tailnode->y);//填充黑色以便清除尾巴free(tailnode);Sectailnode->next=NULL;}else{fen++;mkfood(TempNode);}SpeedCtrl(TempNode,headnode);return TempNode;}void SpeedCtrl(struct node *TempNode,struct node *HeadNode){//添加自动调速代码int DistToFood_X=abs(TempNode->x-food[0]);int DistToFood_Y=abs(TempNode->y-food[1]);int DistToEdge_X=abs(TempNode->x-1)<abs(TempNode->x-(Hori_Len-1))?abs(TempNode->x-1):abs(TempNode->x-(Hori_Len-1));int DistToEdge_Y=abs(TempNode->y-3)<abs(TempNode->y-(Hori_Len-1))?abs(TempNode ->y-3):abs(TempNode->y-(Hori_Len-1));int HoriSign=(Dire==1)||(Dire==2);/*if((DistToFood_X<7&&DistToFood_Y==0) || (DistToFood_Y<7&&DistToFood_X==0)) //与目标点距离过小timelenX=5000+(7-DistToFood_X-DistToFood_Y)*1000;else// if((DistToEdge_X<7&&HoriSign==1)||(DistToEdge_Y<7&&HoriSign==0)) //与边缘距离过小if((Dire==1&&TempNode->x<6)||(Dire==2&&TempNode->x>23)||(Dire==3&&TempNode->y<8)| |(Dire==4&&TempNode->y>23)){if(Dire==1&&TempNode->x<6) //水平移动// timelenX=5000+(6-TempNode->x)*2000;speed=speed-(6-TempNode->x)*20;if(Dire==2&&TempNode->x>23) //水平移动// timelenX=5000+(TempNode->x+8-Hori_Len)*2000;speed=speed-(TempNode->x+7-Hori_Len)*20;if(Dire==3&&TempNode->y<8) //水平移动// timelenX=5000+(9-TempNode->y)*2000;speed=speed-(8-TempNode->y)*20;if(Dire==4&&TempNode->y>23) //水平移动// timelenX=5000+(TempNode->y+8-Hori_Len)*2000;speed=speed-(TempNode->y+7-Hori_Len)*20;}else{speed=speed<500?(speed=450+5*fen):500; //正常情况}if(speed>500) speed=500;*/speed=speed<500?(speed=450+5*fen):500; //正常情况if(speed>500) speed=500;sprintf(ch1, "%d ", fen);sprintf(ch2, "%d ", speed);settextcolor(WHITE);outtextxy(55,20,ch1);outtextxy(185,20,ch2);/*struct node *p=HeadNode;if(p!=NULL)do{int diffX=abs(TempNode->x-p->x);int diffY=abs(TempNode->y-p->y);if(Dire==1&&TempNode->x>p->x&&diffX<4)timelenX=5000+(4-diffX)*2000;if(Dire==2&&TempNode->x<p->x&&diffX<4)timelenX=5000+(4-diffX)*2000;if(Dire==3&&TempNode->y>p->y&&diffY<4)timelenX=5000+(4-diffY)*2000;if(Dire==4&&TempNode->y<p->y&&diffY<4)timelenX=5000+(4-diffY)*1500;p=p->next;} while(p!=NULL);*/}struct node *FindSecTailNode(struct node *Pnode){struct node * TempNode=Pnode;while(TempNode&&(TempNode->next!=NULL)&&(TempNode->next->next!=NULL)) {TempNode=TempNode->next;}return TempNode;}struct node *InitNode(){struct node *head=(struct node *) malloc(sizeof(struct node));struct node *head_1=(struct node *) malloc(sizeof(struct node));struct node *head_2=(struct node *) malloc(sizeof(struct node));head->x=3;head->y=5;head_1->x=2;head_1->y=5;head_2->x=1;head_2->y=5;if(head!=NULL)head->next=head_1;if(head_1!=NULL)head_1->next=head_2;if(head_2!=NULL)head_2->next=NULL;return head;}int keydown(int *z)//获取输入{char ch;if(kbhit()){ch=getch();switch(ch){case 'A':case 'a':if((*z)!=2) *z=1;break; case 'D':case 'd':if((*z)!=1)*z=2;break; case 'W':case 'w':if((*z)!=4)*z=3;break; case 'S':case 's':if((*z)!=3)*z=4;break; case 'E':case 'e':(*z)=5;break; //暂停default :break;}if(ch==27) *z=27;}return *z;}void delay(){for(int i=0;i<timelenX;i++)for(int j=0;j<timelenX;j++){}}void drawDot(int x,int y){x=x*20;y=y*20;setfillcolor(GREEN);bar(x+1,y+1,x+19,y+19);}void ReMoveDot(int x,int y){x=x*20;y=y*20;setfillcolor(BLACK);bar(x+1,y+1,x+19,y+19);}void mkfood(struct node *p2){//MoveTo(20,20);// gotoxy(20,20);////goto_pos(20,20);// cleardevice();struct node *p1;struct node *p;p=p1=p2;srand((unsigned)clock());//设定随机数种子food[1]=rand()%26+3;//随机产生食物坐标food[0]=rand()%28+1;//检测食物的坐标是否与蛇身体重复,如果是,则重新生成食物if(p!=NULL){do{if (food[0]==p->x&&food[1]==p->y){mkfood(p1);}p=p->next;}while(p!=NULL);}drawDot(food[0],food[1]);}void InitFill() //初始化填充{int x=0,y=0;for(int i=0;i<30;i++){setfillcolor(GREEN);x=i*20;y=0;bar(x+1,y+1,x+19,y+19);y=40;bar(x+1,y+1,x+19,y+19);y=580;bar(x+1,y+1,x+19,y+19);}for(int j=0;j<30;j++){setfillcolor(GREEN);y=j*20;x=0;bar(x+1,y+1,x+19,y+19);x=580;bar(x+1,y+1,x+19,y+19);}}void RecordDisp(){ch1[10];ch2[10];ch3[10];sprintf(ch1, "%d ", fen);sprintf(ch2, "%d ", speed);sprintf(ch3, "%d ", jilu);settextcolor(YELLOW);outtextxy(20,20,"分数:");outtextxy(150,20,"速度:");outtextxy(280,20,"最高纪录:");outtextxy(410,20,"保持者:");settextcolor(WHITE);outtextxy(55,20,ch1);outtextxy(185,20,ch2);outtextxy(350,20,ch3);outtextxy(465,20,jiluzhe);}int CheckSnake(struct node *p){struct node *p2;p2=p;int pointX=p2->x;int pointY=p2->y;if(pointX==29||pointY==29||pointX==0||pointY==2) return 0;while(p2!=NULL){p2=p2->next;if(p2!=NULL){if(pointX==p2->x&&pointY==p2->y)return 0;}}return 1;}。

贪吃蛇游戏源代码

贪吃蛇游戏源代码

//主函数# include <windows.h># include <time.h># include "resource.h"#include "snake.h"#include "table.h"#define GAME_STATE_W AIT 0//游戏等待状态#define GAME_STATE_RUN 1//游戏运行状态#define GAME_STATE_END 2//游戏结束状态//界面相关物件尺寸的定义#define WALL_WIDTH 80//外墙左部到游戏区的宽度#define WALL_HEIGHT 80//外墙顶部到游戏区的高度#define BMP_W ALL_WIDTH 16//墙位图的宽度#define BMP_W ALL_HEIGHT 16//墙位图的高度LRESULT CALLBACK WndProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam);void DrawGame(void);void ShellDraw( HDC hdc );void GameAreaDraw(HDC hdc);void OnTimer(UINT uTIMER_ID);void StartGame( void );void EndGame( void );//创建一个桌子CTable table;int tableBlockWidth = 0; //桌子的格子的宽度int tableBlockHeight = 0; //桌子的格子的高度int iScores = 0; //游戏的得分UINT uGameState = GAME_STATE_W AIT; //当前游戏状态HDC windowDC = NULL; //windows屏幕设备HDC bufferDC = NULL; //缓冲设备环境HDC picDC = NULL; //snake图像内存设备HDC endDC = NULL; //游戏终结图像内存设备HDC scoreDC = NULL; //分数板内存设备HWND hAppWnd = NULL; //本application窗口句柄HBITMAP picBMP = NULL; //snake图像位图句柄HBITMAP bufferBMP = NULL; //缓冲位图句柄HBITMAP endBMP = NULL; //游戏终结hAppWnd图像内存句柄HBITMAP hbmpWall = NULL; //墙位图句柄HBITMAP hbmpScore = NULL; //分数板位图句柄HBRUSH hbrushWall = NULL; //墙画刷//定时器标识UINT uSnakeMoveTimer; //蛇的移动UINT uFoodAddTimer; //水果的产生//框架的位置数据定义//GDI RECT 而不是MFC CRectRECT g_ClientRect;int g_iClientWidth;int g_iClientHeight;int WINAPI WinMain(HINSTANCE hInstance, // handle to current instanceHINSTANCE hPrevInstance, // handle to previous instanceLPSTR lpCmdLine, // command lineint nCmdShow // show state){WNDCLASS wndClass;UINT width,height;//定义窗口wndClass.cbClsExtra = 0;wndClass.cbWndExtra = 0;wndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);wndClass.hIcon = LoadIcon(NULL,MAKEINTRESOURCE(IDI_MAIN));wndClass.hCursor = LoadCursor(NULL,IDC_ARROW);wndClass.hInstance = hInstance;wndClass.lpfnWndProc = WndProc;wndClass.lpszClassName = "Snake";wndClass.lpszMenuName = NULL;wndClass.style = CS_HREDRAW | CS_VREDRAW;//注册窗口RegisterClass(&wndClass);width = GetSystemMetrics(SM_CXSCREEN);height = GetSystemMetrics(SM_CYSCREEN);HWND hWnd;hWnd = CreateWindow("Snake","贪吃蛇游戏",WS_POPUP,0,0,width,height,NULL,NULL,hInstance,NULL);hAppWnd = hWnd;//显示窗口ShowWindow(hWnd,SW_SHOWNORMAL);UpdateWindow(hWnd);GetClientRect(hWnd,&g_ClientRect);g_iClientWidth = g_ClientRect.right - g_ClientRect.left;g_iClientHeight = g_ClientRect.bottom - g_ClientRect.top;//将游戏区域分成横纵均匀的20小块tableBlockWidth = (g_ClientRect.right - 2 * WALL_WIDTH) / 20;tableBlockHeight = (g_ClientRect.bottom - 2 * WALL_HEIGHT) / 20;//获取当前主设备与windowDC相连windowDC = GetDC(NULL);//创建与windowDC兼容的内存设备环境bufferDC = CreateCompatibleDC(windowDC);picDC = CreateCompatibleDC(windowDC);endDC = CreateCompatibleDC(windowDC);scoreDC =CreateCompatibleDC(windowDC);//位图的初始化与载入位图bufferBMP = CreateCompatibleBitmap(windowDC,g_iClientWidth,g_iClientHeight);picBMP = (HBITMAP)LoadImage(NULL,"snake.bmp",IMAGE_BITMAP,160,80,LR_LOADFROMFILE);hbmpWall = (HBITMAP)LoadImage(NULL,"brick.bmp",IMAGE_BITMAP,16,16,LR_LOADFROMFILE);endBMP = (HBITMAP)LoadImage(NULL,"end.bmp",IMAGE_BITMAP,369,300,LR_LOADFROMFILE);hbmpScore = (HBITMAP)LoadImage(NULL,"scoreboard.bmp",IMAGE_BITMAP,265,55,LR_LOADFROMFILE);//生声明位图与设备环境的关联SelectObject(bufferDC,bufferBMP);SelectObject(picDC,picBMP);SelectObject(endDC,endBMP);SelectObject(scoreDC,hbmpScore);hbrushWall = CreatePatternBrush(hbmpWall);StartGame();MSG Msg;while (GetMessage(&Msg,NULL,0,0)){TranslateMessage(&Msg);DispatchMessage(&Msg);}return Msg.wParam;}LRESULT CALLBACK WndProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam){switch (message){case WM_TIMER:OnTimer((UINT)wParam);break;case WM_KEYDOWN:switch (wParam){case VK_ESCAPE:KillTimer(hAppWnd,uSnakeMoveTimer);KillTimer(hAppWnd,uFoodAddTimer);uGameState = GAME_STATE_W AIT;if (IDYES == MessageBox(hWnd,"真的要退出吗?","贪吃蛇",MB_YESNO | MB_ICONQUESTION)){exit(0);}uSnakeMoveTimer = SetTimer(hAppWnd,500,100,NULL);uFoodAddTimer = SetTimer(hAppWnd,600,7000,NULL);uGameState = GAME_STATE_RUN;break;case VK_UP:table.ChangeSnakeDirect(S_UP);break;case VK_DOWN:table.ChangeSnakeDirect(S_DOWN);break;case VK_LEFT:table.ChangeSnakeDirect(S_LEFT);break;case VK_RIGHT:table.ChangeSnakeDirect(S_RIGHT);break;case VK_SPACE:if (GAME_STATE_END == uGameState){StartGame();}else if (GAME_STATE_RUN == uGameState){KillTimer(hAppWnd,uSnakeMoveTimer);KillTimer(hAppWnd,uFoodAddTimer);uGameState = GAME_STATE_W AIT;}else{uSnakeMoveTimer = SetTimer(hAppWnd,500,100,NULL);uFoodAddTimer = SetTimer(hAppWnd,600,7000,NULL);uGameState = GAME_STATE_RUN;}break;}break;case WM_SETCURSOR:SetCursor(NULL);break;case WM_DESTROY:ReleaseDC(hWnd,picDC);ReleaseDC(hWnd,bufferDC);ReleaseDC(hWnd,windowDC);PostQuitMessage(0);break;}return DefWindowProc(hWnd,message,wParam,lParam);}void DrawGame(){ShellDraw(bufferDC);GameAreaDraw(bufferDC);BitBlt(windowDC,0,0,g_iClientWidth,g_iClientHeight,bufferDC,0,0,SRCCOPY);}void OnTimer(UINT uTIMER_ID){if (uTIMER_ID == uSnakeMoveTimer){//移动蛇table.SnakeMove();//检测蛇是否碰到自己的身体if (table.GetSnake() ->IsHeadTouchBody(table.GetSnake() ->GetPos()[0].x,table.GetSnake() ->GetPos()[0].y)){EndGame();}//根据蛇头所在区域做相应的处理switch (table.GetData(table.GetSnake() ->GetPos()[0].x,table.GetSnake() ->GetPos()[0].y)){case TB_STATE_FOOD:table.ClearFood(table.GetSnake() ->GetPos()[0].x,table.GetSnake() ->GetPos()[0].y);table.AddBlock((rand())%tableBlockWidth,rand()%tableBlockHeight);table.GetSnake() ->AddBody();iScores++;break;case TB_STATE_BLOCK:case TB_STATE_SBLOCK:EndGame();break;}//xianshiDrawGame();}else if (uTIMER_ID == uFoodAddTimer){//定时加食物table.AddFood((rand())%tableBlockWidth,rand()%tableBlockHeight);}}//开始游戏void StartGame(){iScores = 0;int iFoodNumber;//桌面初始化table.InitialTable(tableBlockWidth,tableBlockHeight);table.GetSnake() ->ChangeDirect(S_RIGHT);table.GetSnake() ->SetHeadPos(tableBlockWidth / 2,tableBlockHeight / 2);//预先随机产生一些食物srand( (unsigned)time(NULL));for (iFoodNumber = 0; iFoodNumber < 400; iFoodNumber++){table.AddFood((rand())%tableBlockWidth,(rand())%tableBlockHeight);}//打开定时器DrawGame();uSnakeMoveTimer = SetTimer(hAppWnd,500,100,NULL);uFoodAddTimer = SetTimer(hAppWnd,600,7000,NULL);uGameState = GAME_STATE_RUN;}void EndGame(){//关计时器KillTimer(hAppWnd,uSnakeMoveTimer);KillTimer(hAppWnd,uFoodAddTimer);uGameState = GAME_STATE_END;}void ShellDraw(HDC hdc){char szText[30] = "Score: ";char szNum[20];int iNowScores = iScores * 100;itoa(iNowScores,szNum,10);strcat(szText,szNum);RECT rt,rect;GetClientRect(hAppWnd,&rt);//墙的绘制SelectObject(hdc,hbrushWall);PatBlt(hdc,rt.left,rt.top,rt.right,rt.bottom,PATCOPY);//内部游戏区为白色底平面rect.left = rt.left + WALL_WIDTH;rect.top = rt.top + WALL_HEIGHT;rect.right = rt.right - WALL_WIDTH;rect.bottom = rt.bottom - WALL_HEIGHT;FillRect(hdc,&rect,(HBRUSH)(COLOR_WINDOW + 1));BitBlt(hdc,GetSystemMetrics(SM_CXSCREEN) / 3 ,10,256,55,scoreDC,0,0,SRCCOPY);SetBkMode(hdc,TRANSPARENT);TextOut(hdc,GetSystemMetrics(SM_CXSCREEN) / 3 + 50,30,szText,strlen(szText));}void GameAreaDraw(HDC hdc){int i,j;int x, y, x_pos, y_pos;BitmapState state;//绘制水果与毒果for (i = 0; i < tableBlockHeight; i++){for (j = 0; j < tableBlockWidth; j++){x_pos = j * 20 + WALL_WIDTH;y_pos = i * 20 + WALL_HEIGHT;switch (table.GetData(j,i)){case TB_STATE_FOOD:BitBlt(hdc,x_pos,y_pos,20,20,picDC,100,0,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,20,0,SRCAND);break;case TB_STATE_BLOCK:BitBlt(hdc,x_pos,y_pos,20,20,picDC,80,0,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,0,0,SRCAND);break;}}}//根据当前的形状绘制蛇头x = table.GetSnake()->GetPos()[0].x;y = table.GetSnake()->GetPos()[0].y;x_pos = x * 20 + WALL_WIDTH;y_pos = y * 20 + WALL_HEIGHT;state = table.GetSnake()->GetStateArray()[0];switch (state){case M_UP_UP:BitBlt(hdc,x_pos,y_pos,20,20,picDC,80,20,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,0,20,SRCAND);break;case M_DOWN_DOWN:BitBlt(hdc,x_pos,y_pos,20,20,picDC,140,20,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,60,20,SRCAND);break;case M_LEFT_LEFT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,100,20,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,20,20,SRCAND);break;case M_RIGHT_RIGHT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,120,20,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,40,20,SRCAND);break;}//根据蛇身各节点的状态绘制蛇身for (i = 1; i < table.GetSnake()->GetLength() - 1; i++){x = table.GetSnake()->GetPos()[i].x;y = table.GetSnake()->GetPos()[i].y;x_pos = x * 20 + WALL_WIDTH;y_pos = y * 20 + WALL_HEIGHT;state = table.GetSnake()->GetStateArray()[i];switch (state){case M_UP_UP:case M_DOWN_DOWN:BitBlt(hdc,x_pos,y_pos,20,20,picDC,80,40,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,0,40,SRCAND);break;case M_LEFT_LEFT:case M_RIGHT_RIGHT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,100,40,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,20,40,SRCAND);break;case M_RIGHT_DOWN:case M_UP_LEFT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,100,60,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,20,60,SRCAND);break;case M_RIGHT_UP:case M_DOWN_LEFT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,140,40,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,60,40,SRCAND);break;case M_LEFT_DOWN:case M_UP_RIGHT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,80,60,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,0,60,SRCAND);break;case M_LEFT_UP:case M_DOWN_RIGHT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,120,40,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,40,40,SRCAND);break;}}//绘制蛇尾巴x = table.GetSnake()->GetPos()[table.GetSnake()->GetLength()-1].x;y = table.GetSnake()->GetPos()[table.GetSnake()->GetLength()-1].y;x_pos = x * 20 + WALL_WIDTH;y_pos = y * 20 + WALL_HEIGHT;state = table.GetSnake()->GetStateArray()[table.GetSnake()->GetLength()-1];switch (state){case M_UP_UP:BitBlt(hdc,x_pos,y_pos,20,20,picDC,120,60,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,40,60,SRCAND);break;case M_DOWN_DOWN:BitBlt(hdc,x_pos,y_pos,20,20,picDC,120,0,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,40,0,SRCAND);break;case M_LEFT_LEFT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,140,60,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,60,60,SRCAND);break;case M_RIGHT_RIGHT:BitBlt(hdc,x_pos,y_pos,20,20,picDC,140,0,SRCPAINT);BitBlt(hdc,x_pos,y_pos,20,20,picDC,60,0,SRCAND);break;}//绘制游戏结束图案if (uGameState == GAME_STA TE_END){x_pos = g_iClientWidth / 3;y_pos = g_iClientHeight / 4;BitBlt(hdc,x_pos,y_pos,369,300,endDC,0,0,SRCCOPY);}}# include "snake.h"CSnake::CSnake(int x_pos,int y_pos,int len){if (len < 1){len = 1;}int i;m_length = len;//蛇的身体体长//初始化蛇的坐标位置m_pPos = new SPoint[m_length+2];m_pPos[0].x = x_pos;m_pPos[0].y = y_pos;for (i = 1; i < m_length +2; i++){m_pPos[i].x = 0;m_pPos[i].y = 0;}//初始化蛇的运动状态m_newSnake.head = S_NONE;m_oldSnake.head = S_NONE;m_newSnake.body = new MoveState[m_length];m_oldSnake.body = new MoveState[m_length];for(i = 0; i < m_length; i++){m_oldSnake.body[i] = S_NONE;m_newSnake.body[i] = S_NONE;}m_newSnake.tail = S_NONE;m_oldSnake.tail = S_NONE;//初始化蛇的位图显示状态;m_pStateArray = new BitmapState[m_length+2];for (i = 0; i < m_length + 2; i++){m_pStateArray[i] = M_NONE;}}CSnake::~CSnake(){SAFE_DELETE_ARRAY(m_pPos);SAFE_DELETE_ARRAY(m_pStateArray);}//根据新旧两蛇的运动状态,确定当前显示的运动状态BitmapState CSnake::GetRightState(MoveState oldDirect,MoveState newDirect) {BitmapState re;switch(oldDirect){case S_NONE:switch(newDirect){case S_NONE:re = M_NONE;break;case S_UP:re = M_UP_UP;break;case S_DOWN:re = M_DOWN_DOWN;break;case S_LEFT:re = M_LEFT_LEFT;break;case S_RIGHT:re = M_RIGHT_RIGHT;break;}break;case S_UP:switch(newDirect){case S_UP:re = M_UP_UP;break;case S_LEFT:re = M_UP_LEFT;break;case S_RIGHT:re = M_UP_RIGHT;break;}break;case S_DOWN:switch(newDirect){case S_DOWN:re = M_DOWN_DOWN;break;case S_LEFT:re = M_DOWN_LEFT;break;case S_RIGHT:re = M_DOWN_RIGHT;break;}break;case S_LEFT:switch(newDirect){case S_UP:re = M_LEFT_UP;break;case S_LEFT:re = M_LEFT_LEFT;break;case S_DOWN:re = M_LEFT_DOWN;break;}break;case S_RIGHT:switch(newDirect){case S_UP:re = M_RIGHT_UP;break;case S_DOWN:re = M_RIGHT_DOWN;break;case S_RIGHT:re = M_RIGHT_RIGHT;break;}break;}return re;}//改变方向void CSnake::ChangeDirect(MoveState d) {//方向不能为其对立方switch(d){case S_NONE:m_newSnake.head = S_NONE;break;case S_UP:if(m_newSnake.head != S_DOWN)m_newSnake.head = S_UP;break;case S_DOWN:if(m_newSnake.head != S_UP)m_newSnake.head = S_DOWN;break;case S_LEFT:if(m_newSnake.head != S_RIGHT)m_newSnake.head = S_LEFT;break;case S_RIGHT:if(m_newSnake.head != S_LEFT)m_newSnake.head = S_RIGHT;break;}}//蛇移动void CSnake::Move(){int i;//1.计算各节点的新状态//保存蛇身体各部位的形状for (i = 0; i < m_length; i++){m_oldSnake.body[i] = m_newSnake.body[i];}m_newSnake.tail = m_newSnake.body[m_length-1];for(i = m_length - 1; i > 0; i--){m_newSnake.body[i] = m_newSnake.body[i-1];}m_newSnake.body[0] = m_newSnake.head;//根据新旧状态获取新的状态m_pStateArray[0] = GetRightState(m_oldSnake.head,m_newSnake.head);for(i = 0; i < m_length; i++){m_pStateArray[i+1] = GetRightState(m_oldSnake.body[i],m_newSnake.body[i]);}m_pStateArray[m_length+1] = GetRightState(m_oldSnake.tail,m_newSnake.tail);//2、整个蛇坐标移动,除蛇头外其他为原状态的前一位置for(i = m_length + 1; i > 0; i--){m_pPos[i] = m_pPos[i-1];}//蛇头根据新位置进行偏移switch(m_newSnake.head){case S_UP:m_pPos[0].y -= SNAKE_MOVE;break;case S_DOWN:m_pPos[0].y += SNAKE_MOVE;break;case S_LEFT:m_pPos[0].x -= SNAKE_MOVE;break;case S_RIGHT:m_pPos[0].x += SNAKE_MOVE;break;}}//蛇身体的增长void CSnake::AddBody(int n){//分配变量作为保存各种数据状态int i;Snake_Struct saveOldSnake,saveNewSnake;BitmapState *saveStateArray;SPoint *savePos;//保存蛇的位置信息savePos = new SPoint[m_length+2];for(i = 0; i < m_length + 2; i++){savePos[i] = m_pPos[i];}//保存蛇的状态信息saveOldSnake.head = m_oldSnake.head;saveOldSnake.body = new MoveState[m_length];for(i = 0; i < m_length; i++){saveOldSnake.body[i] = m_oldSnake.body[i];}saveOldSnake.tail = m_oldSnake.tail;saveNewSnake.head = m_newSnake.head;saveNewSnake.body = new MoveState[m_length];for(i = 0; i < m_length; i++){saveNewSnake.body[i] = m_newSnake.body[i];}saveNewSnake.tail = m_newSnake.tail;saveStateArray = new BitmapState[m_length+2];for (i = 0; i < m_length + 2; i++){saveStateArray[i] = m_pStateArray[i];}//将长度增长m_length += n;//释放所有存储蛇状态数据的存储空间SAFE_DELETE_ARRAY(m_newSnake.body); SAFE_DELETE_ARRAY(m_oldSnake.body); SAFE_DELETE_ARRAY(m_pPos);SAFE_DELETE_ARRAY(m_pStateArray);//创建并初始化蛇增长后的存储空间m_pPos = new SPoint[m_length+2];for (i = 0; i < m_length +2; i++){m_pPos[i].x = 0;m_pPos[i].y = 0;}//初始化蛇的运动状态m_newSnake.head = S_NONE;m_oldSnake.head = S_NONE;m_newSnake.body = new MoveState[m_length]; m_oldSnake.body = new MoveState[m_length];for(i = 0; i < m_length; i++){m_oldSnake.body[i] = S_NONE;m_newSnake.body[i] = S_NONE;}m_newSnake.tail = S_NONE;m_oldSnake.tail = S_NONE;//初始化蛇的位图显示状态;m_pStateArray = new BitmapState[m_length+2]; for (i = 0; i < m_length + 2; i++){m_pStateArray[i] = M_NONE;}//恢复原来的长度数据m_newSnake.head = saveNewSnake.head;m_oldSnake.head = saveOldSnake.head;for(i = 0; i < m_length - n; i++){m_newSnake.body[i] = saveNewSnake.body[i];m_oldSnake.body[i] = saveOldSnake.body[i];}m_newSnake.tail = saveNewSnake.tail;m_oldSnake.tail = saveOldSnake.tail;m_pStateArray = new BitmapState[m_length+2];for (i = 0; i < m_length + 2 - n; i++)m_pStateArray[i] = saveStateArray[i];m_pPos = new SPoint[m_length+2];for(i = 0; i < m_length + 2 - n; i++)m_pPos[i] = savePos[i];}//设置蛇头坐标void CSnake::SetHeadPos(int x, int y){m_pPos[0].x = x;m_pPos[0].y = y;}//取蛇状态的标志数组BitmapState* CSnake::GetStateArray(){return m_pStateArray;}//取蛇的位置信息SPoint* CSnake::GetPos(){return m_pPos;}//取蛇长度int CSnake::GetLength()return m_length + 2;}//检测蛇头是否碰到身体bool CSnake::IsHeadTouchBody(int x, int y){int i;for(i = 1; i < m_length + 2; i++){if (m_pPos[i].x == x && m_pPos[i].y == y)return true;}return false;}//初始化,用作游戏结束后重新开始void CSnake::Initial(){//释放以前的存储空间SAFE_DELETE_ARRAY(m_pPos);SAFE_DELETE_ARRAY(m_pStateArray);SAFE_DELETE_ARRAY(m_newSnake.body);SAFE_DELETE_ARRAY(m_oldSnake.body);int i;int x_pos = 0;int y_pos = 0;m_length = 1;//蛇的身体体长//初始化蛇的坐标位置m_pPos = new SPoint[m_length+2];m_pPos[0].x = x_pos;m_pPos[0].y = y_pos;for (i = 1; i < m_length +2; i++){m_pPos[i].x = 0;m_pPos[i].y = 0;}//初始化蛇的运动状态m_newSnake.head = S_NONE;m_oldSnake.head = S_NONE;m_newSnake.body = new MoveState[m_length];m_oldSnake.body = new MoveState[m_length];for(i = 0; i < m_length; i++){m_oldSnake.body[i] = S_NONE;m_newSnake.body[i] = S_NONE;}m_newSnake.tail = S_NONE;m_oldSnake.tail = S_NONE;//初始化蛇的位图显示状态;m_pStateArray = new BitmapState[m_length+2];for (i = 0; i < m_length + 2; i++){m_pStateArray[i] = M_NONE;}}#ifndef __SNAKE_H_H#define __SNAKE_H_H#define SNAKE_MOVE 1#define SAFE_DELETE_ARRAY(p) {delete [](p);(p)=NULL;}#include <stdio.h>//节点图像显示位图状态enumBitmapState{M_NONE,M_UP_UP,M_DOWN_DOWN,M_LEFT_LEFT,M_RIGHT_RIGHT, M_UP_LEFT,M_UP_RIGHT,M_DOWN_LEFT,M_DOWN_RIGHT,M_LEFT_UP,M_LEFT_DOWN,M_RIGHT_UP,M_RIGHT_DOWN};//节点运动状态enum MoveState{S_NONE,S_UP,S_DOWN,S_LEFT,S_RIGHT};//节点位置坐标struct SPointint x;int y;};//定义蛇体状态struct Snake_Struct{MoveState head;//头部MoveState *body;//身体MoveState tail;//尾部};class CSnake{private:int m_length; //蛇的长度Snake_Struct m_newSnake; //蛇的新态的所有节点的运动状态Snake_Struct m_oldSnake; //蛇的原态的所有节点的坐标的运动状态BitmapState *m_pStateArray; //蛇的所有节点显示位图的状态SPoint *m_pPos; //蛇体坐标BitmapState GetRightState(MoveState oldDirect,MoveState newDirect);public:void Move(void);void ChangeDirect(MoveState d);void AddBody(int n=1);void SetHeadPos(int x, int y);BitmapState * GetStateArray(void);SPoint * GetPos(void);bool IsHeadTouchBody(int x, int y);int GetLength(void);void Initial(void);CSnake(int x_pos = 0, int y_pos = 0, int len = 1);~CSnake();};#endif#include "table.h"CTable::CTable()m_width = 0;m_height = 0;m_foodNumber = 0;m_blockNumber = 0;m_board = NULL;}CTable::~CTable(){if (m_board != NULL){SAFE_DELETE_ARRAY(m_board);}}//初始化面板void CTable::InitialTable(int w,int h){int i, j;m_width = w;m_height = h;m_snake.Initial();if (m_board != NULL){SAFE_DELETE_ARRAY(m_board);}//根据高度和宽度设置新的桌子m_board = new int * [m_height];for (i = 0; i < m_height; i++){m_board[i] = new int[m_width];for (j = 0; j < m_width; j++){m_board[i][j] = 0;}}//将桌子四周设置为墙for (i = 0; i < m_height; i++){m_board[i][0] = TB_STATE_SBLOCK;m_board[i][m_width-1] = TB_STA TE_SBLOCK;}for (i = 0; i < m_width; i++){m_board[0][i] = TB_STATE_SBLOCK;m_board[m_height-1][i] = TB_STA TE_SBLOCK;}}//食物的操作bool CTable::AddBlock(int x, int y){if( (x > 0) && (x < m_width) && (y > 0) && (y < m_height) && (m_board[y][x] == TB_STATE_OK)){m_board[y][x] = TB_STA TE_BLOCK;m_blockNumber++;return true;}return false;}bool CTable::AddFood(int x, int y){if( (x > 0) && (x < m_width) && (y > 0) && (y < m_height) && (m_board[y][x] == TB_STATE_OK)){m_board[y][x] = TB_STA TE_FOOD;m_foodNumber++;return true;}return false;}bool CTable::ClearFood(int x, int y){m_board[y][x] = TB_STA TE_OK;return true;}//取蛇对象CSnake * CTable::GetSnake(void){return &m_snake;}//取桌子对象int ** CTable::GetBoard(void){return m_board;}//获取数据信息int CTable::GetData(int x, int y){return m_board[y][x];}//蛇的操作void CTable::SnakeMove(void){m_snake.Move();}bool CTable::ChangeSnakeDirect(MoveState d){m_snake.ChangeDirect(d);return true;}#ifndef __TABLE_H_H#define __TABLE_H_H#define TB_STATE_OK 0 //正常#define TB_STATE_FOOD 1 //食物#define TB_STATE_BLOCK 2 //障碍-毒果#define TB_STATE_SBLOCK 3 //障碍-墙#include "snake.h"class CTable{private:int m_width;//桌子的宽度int m_height;//桌子的宽度int m_foodNumber;//桌子上食物的数量int m_blockNumber;//毒果的数量CSnake m_snake;//桌上的蛇int ** m_board;//桌的面板public:CTable();~CTable();//初始化面板void InitialTable(int w,int h);//食物的操作bool AddBlock(int x, int y);bool AddFood(int x, int y);bool ClearFood(int x, int y);//物件获取CSnake * GetSnake(void);int ** GetBoard(void);int GetData(int x, int y);//蛇的操作void SnakeMove(void);bool ChangeSnakeDirect(MoveState d); };#endif。

贪吃蛇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);}。

汇编语言写的贪吃蛇小游戏源代码

汇编语言写的贪吃蛇小游戏源代码

DATA SEGMENTdw 0,0snk db 1blk db 32food db 3tal1 db 4tal2 db 2adrs db 5len db ?pst db ?addrs dw ?frow db ?fcol db ?hwrt db ?gmov db 'game over press r to restart press q to quit $'score1 db 'score :$'score2 db ?score0 db 1zero db 48writer db 'Developer: Geniusdot $'email db ': geniusdotgmail.$'msg1 db 'The way to play the game:$'way db ' press w to up ,press s to down,press a to left,press d to right$' msg db 'Press any key(except a,s,d,w) to start$'DATA ENDSSTACK SEGMENT stackdb 200 dup(0)STACK ENDSCODE SEGMENTASSUME CS:CODE,DS:DATA,SS:STACKstart:mov ax,datamov ds,axmov ax,0mov es,axmov frow,10mov fcol,6mov dh,10mov dl,26mov ah,2int 10hmov ah,9lea dx,msg1 int 21hmov dh,11 mov dl,7mov ah,2mov bh,0int 10hmov ah,9lea dx,wayint 21hmov dh,12 mov dl,20 mov ah,2mov bh,0int 10hmov ah,9lea dx,msgint 21hmov ah,0int 16hmov ah,6mov al,0mov ch,0mov cl,0mov dh,24 mov dl,79 mov bh,10int 10hmov dh,0mov dl,0mov ah,2mov bh,0int 10hmov ah,9lea dx,score1 int 21hmov dl,15 mov ah,2mov bh,0int 10hlea dx,writerint 21hmov ah,9lea dx,emailint 21hmov score2,48push es:[9*4] ;将原int9入口地址保存pop ds:[0]push es:[9*4+2]pop ds:[2]mov word ptr es:[9*4],offset int9 ;更改中断向量表mov es:[9*4+2],csjmp aawrite macro row,col,cnt ;宏定义用于向当前光标处输出字符push bxpush cxpush dxmov dh,rowmov dl,colmov ah,2mov bh,0int 10hmov ah,9mov bl,11mov cx,1lea di,cnt ;50mov al,[di]int 10hpop dxpop cxpop bxendmreadh macro row,col ;宏定义用于读出当前光标处字符push dxpush bxmov dh,rowmov dl,colmov ah,2mov bh,0int 10hmov ah,08hint 10hmov pst,alpop bxpop axpop dxendmwnear macro ;宏定义只用在readcg宏中当readcg的所有判断都不成立调用此宏local wnext1local wnext2local wnext3local wnext4push dxdec dhreadh dh,dlcmp pst,1jne wnext1write dh,dl,tal2jmp wnext4wnext1:inc dhdec dlreadh dh,dlcmp pst,1jne wnext2write dh,dl,tal2jmp wnext4wnext2:inc dhinc dlreadh dh,dlcmp pst,1jne wnext3write dh,dl,tal2jmp wnext4dec dhinc dlreadh dh,dlcmp pst,1jne wnext4write dh,dl,tal2wnext4:pop dxendmreadcg macro row,col ;宏定义用于改变判断出来的字符local tnup,tnup1,tnup2,tnlf,tnlf1,tnlf2,tndn,tndn1,tndn2,tnrt,tnrt1,tnrt2,goout push bxpush axpush dxwrite dh,dl,tal1dec rowreadh dh,dlcmp pst,4jne tnup1jmp tnup2tnup1:jmp near ptr tnuptnup2:write dh,dl,blkinc dhinc dhreadh dh,dlcmp pst,1jne tnupwrite dh,dl,tal2jmp near ptr goouttnup:pop dxpush dxdec colreadh dh,dlcmp pst,4jne tnlf1jmp tnlf2tnlf1:jmp near ptr tnlf tnlf2:write dh,dl,blk inc dlinc dlreadh dh,dlcmp pst,1jne tnlfwrite dh,dl,tal2 jmp near ptr goout tnlf:pop dxpush dxinc rowreadh dh,dlcmp pst,4jne tndn1jmp tndn2tndn1:jmp near ptr tndn tndn2:write dh,dl,blk dec dhdec dhreadh dh,dlcmp pst,1jne tndnwrite dh,dl,tal2 jmp near ptr goout tndn:pop dxpush dxinc colreadh dh,dlcmp pst,4jne tnrt1jmp tnrt2tnrt1:jmp near ptr tnrt tnrt2:write dh,dl,blk dec dldec dlreadh dh,dlcmp pst,1jne tnrtwrite dh,dl,tal2jmp near ptr goouttnrt:pop dxpush dxwneargoout:pop dxpop axpop bxendmaddone: ;此标号功能是将蛇身增加一push dxinc score2mov dh,1mov dl,0mov cx,23cmpad1:push cxmov cx,79cmpad2:readh dh,dlcmp pst,2jne nextad3jmp nextad4nextad3:jmp near ptr nextadnextad4:write dh,dl,snkdec dhreadh dh,dlcmp pst,4jne natupwrite dh,dl,tal2dec dhwrite dh,dl,tal1jmp outonatup:inc dhreadh dh,dlcmp pst,4jne natlfwrite dh,dl,tal2 dec dlwrite dh,dl,tal1 jmp outonatlf:inc dhinc dlreadh dh,dlcmp pst,4jne natdnwrite dh,dl,tal2 inc dhwrite dh,dl,tal1 jmp outonatdn:dec dhinc dlreadh dh,dlcmp pst,4jne natrtwrite dh,dl,tal2 inc dlwrite dh,dl,tal1 natrt:outo:pop cxjmp near ptr endad nextad:inc dljmp nextad2chgad2:jmp near ptr cmpad2 nextad2:loop chgad2sub dl,79inc dhpop cxjmp nextad1chgad1:jmp near ptr cmpad1loop chgad1endad:pop dxjmp near ptr crtfaa: ;从这开始产生最原始的蛇mov addrs,offset turnrightmov dh,10mov dl,1mov cx,3write dh,dl,tal1inc dlwrite dh,dl,tal2wrt:inc dlwrite dh,dl,snkloop wrtmov len,6mov ax,0jmp wrt1ovflw: ;当蛇碰壁或自身转到此游戏结束mov ah,6mov al,0mov ch,0mov cl,0mov dh,24mov dl,79mov bh,7int 10hmov dh,17mov dl,17mov ah,2mov bh,0int 10hmov ah,9lea dx,gmovint 21hmov ax,0 ;恢复int9中断mov es,axpush ds:[0]pop es:[9*4]push ds:[2]pop es:[9*4+2]stop:mov ah,0int 16hcmp al,'r'je aa1jmp aa2aa1:jmp near ptr startaa2:cmp al,'q'jne stopjmp near ptr exitwrt1: ;此处蛇行走过程的无限循环call dlypush dxinc dhcmp dh,25je ovflwinc dlcmp dl,80je ovflwpop dxpush dxdec dhcmp dh,0je ovflwdec dlcmp dl,-1je ovflwpop dxpush dxlea ax,turnrightcmp addrs,axjne tonxt2inc dlreadh dh,dlcmp pst,1je tonxt1cmp pst,2je tonxt1cmp pst,4je tonxt1jmp tonxt2 tonxt1:jmp ovflwtonxt2:pop dxpush dxlea ax,turnup cmp addrs,ax jne tonxt4dec dhreadh dh,dl cmp pst,1je tonxt3cmp pst,2je tonxt3cmp pst,4je tonxt3jmp tonxt4 tonxt3:jmp ovflwtonxt4:pop dxpush dxlea ax,turndown cmp addrs,ax jne tonxt6inc dhreadh dh,dl cmp pst,1je tonxt5cmp pst,2je tonxt5cmp pst,4je tonxt5jmp tonxt6 tonxt5:jmp ovflwtonxt6:pop dxpush dxlea ax,turnback cmp addrs,axjne tonxt8dec dlreadh dh,dlcmp pst,1je tonxt7cmp pst,2je tonxt7cmp pst,4je tonxt7jmp tonxt8tonxt7:jmp ovflwtonxt8:pop dxjmp nextacrtf1:jmp near ptr addone crtf:call rand1call rand2inc frowmov ah,frowmov al,fcolpush dxmov dh,1mov dl,0push cxmov cx,23check1:push cxmov cx,79check2:readh dh,dlcmp pst,1je nextncmp pst,2je nextncmp pst,4je nextnjmp nextnnnextn:cmp ax,dxje crtfnextnn:inc dlloop check2inc dhsub dl,79pop cxloop check1pop cxpop dxwrite frow,fcol,food nexta:mov ah,frowmov al,fcolcmp ax,dxje crtf12jmp crtf13crtf12:jmp near ptr crtf1 crtf13:push dxcmp score2,58jl normalmov score2,49inc score0normal:mov dh,0mov dl,8write dh,dl,score2 add dl,score0write dh,dl,zeropop dxcmp adrs,17je jmp1cmp adrs,145je jmp1cmp adrs,31je jmp2cmp adrs,159je jmp2cmp adrs,32je jmp3cmp adrs,160je jmp3cmp adrs,30je jmp4cmp adrs,158je jmp4jmp addrsjmp1:lea ax, turndowncmp ax,addrsje jmp2mov addrs,offset turnupjmp near ptr turnupjmp2:lea ax,turnupcmp ax,addrsje jmp1mov addrs,offset turndownjmp near ptr turndownjmp3:lea ax,turnbackcmp ax,addrsje jmp4mov addrs,offset turnrightjmp near ptr turnrightjmp4:lea ax,turnrightcmp ax,addrsje jmp3mov addrs,offset turnbackjmp near ptr turnbackturnright: ;此处实现蛇向左走push dxmov dh,1mov dl,0mov cx,23cmpr1:push cxmov cx,79cmpr2:readh dh,dlcmp pst,2je nextr4jmp near ptr nextrnextr4:readcg dh,dlpop cxjmp near ptr endrnextr:inc dljmp nextr2chgr2:jmp near ptr cmpr2nextr2:loop chgr2sub dl,79inc dhpop cxjmp nextr1chgr1:jmp near ptr cmpr1nextr1:loop chgr1endr:pop dxinc dlwrite dh,dl,snkjmp near ptr wrt1turnup: ;此处实现蛇向上走push dxmov dh,1mov dl,0mov cx,23cmpu1:push cxmov cx,79cmpu2:readh dh,dlcmp pst,2jne nextu3jmp nextu4nextu3:jmp near ptr nextunextu4:readcg dh,dlpop cxjmp near ptr endunextu:inc dljmp nextu2chgu2:jmp near ptr cmpu2nextu2:loop chgu2sub dl,79inc dhpop cxjmp nextu1chgu1:jmp near ptr cmpu1nextu1:loop chgu1endu:pop dxdec dhwrite dh,dl,snkjmp near ptr wrt1turndown: ;此处实现蛇向下走push dxmov dh,1mov dl,0mov cx,23cmpd1:push cxmov cx,79cmpd2:readh dh,dlcmp pst,2jne nextd3jmp nextd4nextd3:jmp near ptr nextdnextd4:readcg dh,dlpop cxjmp near ptr enddnextd:inc dljmp nextd2chgd2:jmp near ptr cmpd2nextd2:loop chgd2sub dl,79inc dhpop cxjmp nextd1chgd1:jmp near ptr cmpd1nextd1:loop chgd1endd:pop dxinc dhwrite dh,dl,snkjmp near ptr wrt1turnback: ;此处实现蛇向右走push dxmov dh,1mov dl,0mov cx,23cmpb1:push cxmov cx,79cmpb2:readh dh,dlcmp pst,2jne nextb3jmp nextb4nextb3:jmp near ptr nextbnextb4:readcg dh,dlpop cxjmp near ptr endbnextb:jmp nextb2chgb2:jmp near ptr cmpb2nextb2:loop chgb2sub dl,79inc dhpop cxjmp nextb1chgb1:jmp near ptr cmpb1nextb1:loop chgb1endb:pop dxdec dlwrite dh,dl,snkjmp near ptr wrt1exit:mov ax,0 ;恢复int9中断mov es,axpush ds:[0]pop es:[9*4]push ds:[2]pop es:[9*4+2]mov ah,4chint 21hint9: ;更改后的中断服务程序push axin al,60hmov adrs,almov al,20hout 20h,aliretDLY PROC near ;延时子程序PUSH CXPUSH DXMOV DX,10000DL1: MOV CX,9801DL2: LOOP DL2DEC DXJNZ DL1POP DXPOP CXRETDLY ENDPRAND1 PROCPUSH CXPUSH DXPUSH AXSTIMOV AH,0 ;读时钟计数器值INT 1AHMOV AX,DX ;清高6位AND AH,3MOV DL,23 ;除23,产生0~23余数DIV DLMOV frow,AH ;余数存frow,作随机行数 POP AXPOP DXPOP CXRETRAND1 ENDPRAND2 PROCPUSH CXPUSH DXPUSH AXSTIMOV AH,0 ;读时钟计数器值INT 1AHMOV AX,DX ;清高6位AND AH,3MOV DL,79 ;除79,产生0~79余数DIV DLMOV fcol,AH ;余数存fcol,作随机列数 POP AXPOP DXPOP CXRETRAND2 ENDPCODE ENDSEND start。

C++贪吃蛇源代码

C++贪吃蛇源代码

#include "graphics.h"#include "stdio.h"#define MAX 200#define MAXX 30#define MAXY 30#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#define ESC 283#define ENTER 7181#define PAGEUP 18688#define PAGEDOWN 20736#define KEY_U 5749#define KEY_K 9579#define CTRL_P 6512#define TRUE 1#define FALSE 0#define GAMEINIT 1#define GAMESTART 2#define GAMEHAPPY 3#define GAMEOVER 4struct SPlace{int x;int y;int st;} place[MAX];int speed;int count;int score;int control;int head;int tear;int x,y;int babyx,babyy;int class;int eat;int game;int gamedelay[]={5000,4000,3000,2000,1000,500,250,100}; int gamedelay2[]={1000,1};static int hitme=TRUE,hit = TRUE; void init(void);void nextstatus(void);void draw(void);void init(void){int i;for(i=0;i<MAX;i++){place[i].x = 0;place[i].y = 0;place[i].st = FALSE;}place[0].st = TRUE;place[1].st = TRUE;place[1].x = 1;speed = 9;count = 0;score = 0;control = 4;head = 1;tear = 0;x = 1;y = 0;babyx = rand()%MAXX;babyy = rand()%MAXY;eat = FALSE;game = GAMESTART;}void nextstatus(void){int i;int exit;int xx,yy;xx = x;yy = y;switch(control){case 1: y--; yy = y-1; break;case 2: y++; yy = y+1; break;case 3: x--; xx = x-1; break;case 4: x++; xx = x+1; break;}hit = TRUE;if ( ((control == 1) || (control ==2 )) && ( (y < 1) ||(y >= MAXY-1)) || (((control == 3) || (control == 4)) && ((x < 1) ||(x >= MAXX-1) ) ) ){hit = FALSE;}if ( (y < 0) ||(y >= MAXY) ||(x < 0) ||(x >= MAXX) ){game = GAMEOVER;control = 0;return;}for (i = 0; i < MAX; i++){if ((place[i].st) &&(x == place[i].x) &&(y == place[i].y) ){game = GAMEOVER;control = 0;return;}if ((place[i].st) &&(xx == place[i].x) &&(yy == place[i].y) ){hit = FALSE;goto OUT;}}OUT:if ( (x == babyx) && (y == babyy) ){eat = TRUE;count ++;score += (1+class) * 10;}head ++;if (head >= MAX) head = 0;place[head].x = x;place[head].y = y;place[head].st= TRUE;if (eat == FALSE){place[tear].st = FALSE;tear ++;if (tear >= MAX) tear = 0;}else{eat = FALSE;exit = TRUE;while(exit){babyx = rand()%MAXX;babyy = rand()%MAXY;exit = FALSE;for( i = 0; i< MAX; i++ )if( (place[i].st)&&( place[i].x == babyx) && (place[i].y == babyy))exit ++;}}if (head == tear) game = GAMEHAPPY;}void draw(void){char temp[50];int i,j;for (i = 0; i < MAX; i++ ){setfillstyle(1,9);if (place[i].st)bar(place[i].x*15+1,place[i].y*10+1,place[i].x*15+14,place[i].y*10+9);}setfillstyle(1,4);bar(babyx*15+1,babyy*10+1,babyx*15+14,babyy*10+9);setcolor(8);setfillstyle(1,8);bar(place[head].x*15+1,place[head].y*10+1,place[head].x*15+14,place[head].y*10+9); /* for( i = 0; i <= MAXX; i++ )line( i*15,0, i*15, 10*MAXY);for( j = 0; j <= MAXY; j++ )line( 0, j*10, 15*MAXX, j*10); */rectangle(0,0,15*MAXX,10*MAXY);sprintf(temp,"Count: %d",count);settextstyle(1,0,2);setcolor(8);outtextxy(512,142,temp);setcolor(11);outtextxy(510,140,temp);sprintf(temp,"1P: %d",score);settextstyle(1,0,2);setcolor(8);outtextxy(512,102,temp);setcolor(12);outtextxy(510,100,temp);sprintf(temp,"Class: %d",class);setcolor(8);outtextxy(512,182,temp);setcolor(11);outtextxy(510,180,temp);}main(){int pause = 0;char temp[50];int d,m;int key;int p;static int keydown = FALSE;int exit = FALSE;int stchange = 0;d = VGA;m = VGAMED;initgraph( &d, &m, "" );setbkcolor(3);class = 3;init();p = 1;while(!exit){if (kbhit()){key = bioskey(0);switch(key){case UP: if( (control != 2)&& !keydown)control = 1;keydown = TRUE;break;case DOWN: if( (control != 1)&& !keydown)control = 2;keydown = TRUE;break;case LEFT: if( (control != 4)&& !keydown)control = 3;keydown = TRUE;break;case RIGHT: if( (control != 3)&& !keydown)control = 4;keydown = TRUE;break;case ESC: exit = TRUE;break;case ENTER: init();break;case PAGEUP: class --; if (class<0) class = 0; break;case PAGEDOWN: class ++;if (class>7) class = 7; break;case KEY_U: if( ( (control ==1) ||(control ==2))&& !keydown) control = 3;else if(( (control == 3) || (control == 4))&& !keydown)control = 1;keydown = TRUE;break;case KEY_K: if( ( (control ==1) ||(control ==2))&& !keydown) control = 4;else if(( (control == 3) || (control == 4))&& !keydown)control = 2;keydown = TRUE;break;case CTRL_P:pause = 1 - pause; break;}}stchange ++ ;putpixel(0,0,0);if (stchange > gamedelay[class] + gamedelay2[hit]){stchange = 0;keydown = FALSE;p = 1 - p;setactivepage(p);cleardevice();if (!pause)nextstatus();else{settextstyle(1,0,4);setcolor(12);outtextxy(250,100,"PAUSE");}draw();if(game==GAMEOVER){settextstyle(0,0,6);setcolor(8);outtextxy(101,101,"GAME OVER");setcolor(15);outtextxy(99,99,"GAME OVER");setcolor(12);outtextxy(100,100,"GAME OVER");sprintf(temp,"Last Count: %d",count);settextstyle(0,0,2);outtextxy(200,200,temp);}if(game==GAMEHAPPY){settextstyle(0,0,6);setcolor(12);outtextxy(100,300,"YOU WIN");sprintf(temp,"Last Count: %d",count);settextstyle(0,0,2);outtextxy(200,200,temp);}setvisualpage(p);}}closegraph();}。

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 );}}。

贪吃蛇源代码

贪吃蛇源代码

#include <graphics.h>#include <stdlib.h>#include <conio.h>#include <time.h>#include <stdio.h>#define LEFT 'a'#define RIGHT 'd'#define DOWN 's'#define UP 'w'#define ESC 27#define N 200 /*蛇的最大长度*/int i;char key;int score=0; /*得分*/int gamespeed=100; /*游戏速度自己调整*/struct Food{int x; /*食物的横坐标*/int y; /*食物的纵坐标*/int yes; /*判断是否要出现食物的变量*/ }food; /*食物的结构体*/struct Snake{int x[N];int y[N];int node; /*蛇的节数*/int direction; /*蛇移动方向*/int life; /* 蛇的生命,0活着,1死亡*/ }snake;void Init(void); /*图形驱动*/void Close(void); /*图形结束*/void DrawK(void); /*开始画面*/void GameOver(void); /*结束游戏*/void GamePlay(void); /*玩游戏具体过程*/void PrScore(void); /*输出成绩*//*主函数*/void main(void){Init(); /*图形驱动*/DrawK(); /*开始画面*/GamePlay(); /*玩游戏具体过程*/Close(); /*图形结束*/}/*图形驱动*/void Init(void){int gd=9,gm=2;initgraph(&gd,&gm," ");cleardevice();}/*开始画面,左上角坐标为(50,40),右下角坐标为(610,460)的围墙*/void DrawK(void){/*setbkcolor(LIGHTGREEN);*/setcolor(LIGHTCYAN);setlinestyle(PS_SOLID,0,1); /*设置线型*/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){srand(time(NULL)); /*随机数发生器*/food.yes=1; /*1表示需要出现新食物,0表*/ snake.life=0; /*活着*/snake.direction=1; /*方向往右*/snake.x[0]=100;snake.y[0]=100; /*蛇头*/snake.x[1]=110;snake.y[1]=100;snake.node=2; /*节数*/PrScore(); /*输出得分*/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);rectangle(food.x,food.y,food.x+10,food.y-10);}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;}/*从蛇的第四节开始判断是否撞到自己了,因为蛇头为两节,第三节不可*/ for(i=3;i<snake.node;i++){if(snake.x[i]==snake.x[0]&&snake.y[i]==snake.y[0]){GameOver(); /*显示失败*/snake.life=1;break;}}if(snake.x[0]<55||snake.x[0]>595||snake.y[0]<55||snake.y[0]>455) /*蛇是否撞到墙壁*/{ GameOver(); /*本次游戏结束*/snake.life=1; /*蛇死*/}if(snake.life==1) /*以上两种判断以后,如果蛇*/ break;if(snake.x[0]==food.x&&snake.y[0]==food.y)/*吃到食物以后*/{setcolor(BLACK); /*把画面上的食物东西去*/ rectangle(food.x,food.y,food.x+10,food.y-10);snake.x[snake.node]=-20;snake.y[snake.node]=-20;/*新的一节先放在看不见的位置,下次循环就取前一节的位置*/snake.node++; /*蛇的身体长一节*/food.yes=1; /*画面上需要出现新的食物*/ score+=10;PrScore(); /*输出新得分*/}setcolor(RED); /*画出蛇*/for(i=0;i<snake.node;i++)rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10); Sleep(gamespeed);setcolor(BLACK); /*用黑色去除蛇的的最后*/ rectangle(snake.x[snake.node-1],snake.y[snake.node-1],snake.x[snake.node-1]+10,snake.y[snake.node-1]-10);} /*endwhile(!kbhit)*/if(snake.life==1) /*如果蛇死就跳出循环*/break;key=getch(); /*接收按键*/if (key == ESC) break; /*按ESC键退出*/switch(key){case UP:if(snake.direction!=4) /*判断是否往相反的方向移动*/ snake.direction=3;break;case RIGHT:if(snake.direction!=2) snake.direction=1; break;case LEFT:if(snake.direction!=1) snake.direction=2; break;case DOWN:if(snake.direction!=3) snake.direction=4; break;}}/*endwhile(1)*/}/*游戏结束*/void GameOver(void){cleardevice();PrScore();setcolor(RED);setfont(56,0,"黑体");outtextxy(200,200,"GAME OVER");getch();}/*输出成绩*/void PrScore(void){char str[10];setfillstyle(YELLOW);bar(50,15,220,35);setcolor(BROWN);setfont(16,0,"宋体");sprintf(str,"score:%d",score);outtextxy(55,16,str);}/*图形结束*/void Close(void){closegraph();}。

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;}。

贪吃蛇游戏c语言源代码

贪吃蛇游戏c语言源代码

Ì°³ÔÉßÓÎÏ·cÓïÑÔÔ´´úÂë.txtÊÀÉÏ×îÕä¹óµÄ²»ÊÇÓÀÔ¶µÃ²»µ½»òÒѾ-µÃµ½µÄ£¬¶øÊÇÄãÒѾ-µÃµ½²¢ÇÒËæʱ¶¼ÓпÉÄÜʧȥµÄ¶«Î÷£¡°®ÇéÊǵƣ¬ÓÑÇéÊÇÓ°×Ó¡£µÆÃðʱ£¬Äã»á·¢ÏÖÖÜΧ¶¼ÊÇÓ°×Ó¡£ÅóÓÑ£¬ÊÇÔÚ×îºó¿ÉÒÔ¸øÄãÁ¦Á¿µÄÈË¡£#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);}。

贪吃蛇游戏代码

贪吃蛇游戏代码

贪吃蛇游戏可以使用Python的pygame库来实现。

以下是一份完整的贪吃蛇游戏代码:```pythonimport pygameimport sysimport random#初始化pygamepygame.init()#设置屏幕尺寸和标题screen_size=(800,600)screen=pygame.display.set_mode(screen_size)pygame.display.set_caption('贪吃蛇')#设置颜色white=(255,255,255)black=(0,0,0)#设置蛇和食物的大小snake_size=20food_size=20#设置速度clock=pygame.time.Clock()speed=10snake_pos=[[100,100],[120,100],[140,100]]snake_speed=[snake_size,0]food_pos=[random.randrange(1,(screen_size[0]//food_size))*food_size,random.randrange(1,(screen_size[1]//food_size))*food_size]food_spawn=True#游戏主循环while True:for event in pygame.event.get():if event.type==pygame.QUIT:pygame.quit()sys.exit()keys=pygame.key.get_pressed()for key in keys:if keys[pygame.K_UP]and snake_speed[1]!=snake_size:snake_speed=[0,-snake_size]if keys[pygame.K_DOWN]and snake_speed[1]!=-snake_size:snake_speed=[0,snake_size]if keys[pygame.K_LEFT]and snake_speed[0]!=snake_size:snake_speed=[-snake_size,0]if keys[pygame.K_RIGHT]and snake_speed[0]!=-snake_size:snake_speed=[snake_size,0]snake_pos[0][0]+=snake_speed[0]snake_pos[0][1]+=snake_speed[1]#碰撞检测if snake_pos[0][0]<0or snake_pos[0][0]>=screen_size[0]or\snake_pos[0][1]<0or snake_pos[0][1]>=screen_size[1]or\snake_pos[0]in snake_pos[1:]:pygame.quit()sys.exit()#蛇吃食物if snake_pos[0]==food_pos:food_spawn=Falseelse:snake_pos.pop()if not food_spawn:food_pos=[random.randrange(1,(screen_size[0]//food_size))*food_size,random.randrange(1,(screen_size[1]//food_size))*food_size] food_spawn=True#绘制screen.fill(black)for pos in snake_pos:pygame.draw.rect(screen,white,pygame.Rect(pos[0],pos[1],snake_size,snake_size)) pygame.draw.rect(screen,white,pygame.Rect(food_pos[0],food_pos[1],food_size, food_size))pygame.display.flip()clock.tick(speed)```这个代码实现了一个简单的贪吃蛇游戏,包括基本的游戏循环、蛇的移动、食物的生成和碰撞检测。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
mainFrame.setVisible(true);
begin();
}
//----------------------------------------------------------------------
//keyPressed():按键检测
//----------------------------------------------------------------------
void begin()
{
if(snakeModel==null||!snakeModel.running)
{
snakeModel=new SnakeModel(this,canvasWidth/nodeWidth,
this.canvasHeight/nodeHeight);
(new Thread(snakeModel)).start();
//GreedSnake():初始化游戏界面
//----------------------------------------------------------------------
public GreedSnake()
{
//设置界面元素
mainFrame=new JFrame("GreedSnake");
*要点分析:
*1)数据结构:matrix[][]用来存储地图上面的信息,如果什么也没有设置为false,
* 如果有食物或蛇,设置为true;nodeArray,一个LinkedList,用来保存蛇的每
* 一节;food用来保存食物的位置;而Node类是保存每个位置的信息。
*2)重要函数:
* changeDirection(int newDirection) ,用来改变蛇前进的方向,而且只是
//updateScore():改变计分牌
//----------------------------------------------------------------------
public void updateScore(#43;snakeModel.score;
break;
case KeyEvent.VK_DOWN:
snakeModel.changeDirection(SnakeModel.DOWN);
break;
case KeyEvent.VK_LEFT:
snakeModel.changeDirection(SnakeModel.LEFT);
paintCanvas.addKeyListener(this);
cp.add(paintCanvas,BorderLayout.CENTER);
JPanel panelButtom=new JPanel();
panelButtom.setLayout(new BorderLayout());
drawNode(g,n);
updateScore();
}
//----------------------------------------------------------------------
//drawNode():绘画某一结点(蛇身或食物)
//----------------------------------------------------------------------
break;
case KeyEvent.VK_SUBTRACT:
case KeyEvent.VK_PAGE_DOWN:
snakeModel.speedDown();// 减速
break;
case KeyEvent.VK_SPACE:
case KeyEvent.VK_P:
snakeModel.changePauseState();// 暂停或继续
public class GreedSnake implements KeyListener
{
JFrame mainFrame;
Canvas paintCanvas;
JLabel labelScore;//计分牌
SnakeModel snakeModel=null;// 蛇
public static final int canvasWidth=200;
private void drawNode(Graphics g,Node n)
{
g.fillRect(n.x*nodeWidth,n.y*nodeHeight,nodeWidth-1,nodeHeight-1);
}
//----------------------------------------------------------------------
//keyReleased():空函数
//----------------------------------------------------------------------
public void keyReleased(KeyEvent e)
{
}
//----------------------------------------------------------------------
public static void main(String[] args)
{
GreedSnake gs=new GreedSnake();
}
}
/**************************************************************************
cp.add(panelButtom,BorderLayout.SOUTH);
mainFrame.addKeyListener(this);
mainFrame.pack();
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp=mainFrame.getContentPane();
labelScore=new JLabel("Score:");
cp.add(labelScore,BorderLayout.NORTH);
paintCanvas=new Canvas();
paintCanvas.setSize(canvasWidth+1,canvasHeight+1);
break;
default:
}
//重新开始
if(keyCode==KeyEvent.VK_R || keyCode==KeyEvent.VK_S
|| keyCode==KeyEvent.VK_ENTER)
{
snakeModel.running=false;
begin();
}
}
//----------------------------------------------------------------------
Iterator it=na.iterator();
while(it.hasNext())
{
Node n=(Node)it.next();
drawNode(g,n);
}
// draw the food
g.setColor(Color.RED);
Node n=snakeModel.food;
break;
case KeyEvent.VK_RIGHT:
snakeModel.changeDirection(SnakeModel.RIGHT);
break;
case KeyEvent.VK_ADD:
case KeyEvent.VK_PAGE_UP:
snakeModel.speedUp();// 加速
//repaint():绘制游戏界面(包括蛇和食物)
//----------------------------------------------------------------------
void repaint()
{
Graphics g=paintCanvas.getGraphics();
//keyTyped():空函数
//----------------------------------------------------------------------
public void keyTyped(KeyEvent e)
{
}
//----------------------------------------------------------------------
public void keyPressed(KeyEvent e)
{
int keyCode=e.getKeyCode();
if(snakeModel.running) switch(keyCode)
{
case KeyEvent.VK_UP:
snakeModel.changeDirection(SnakeModel.UP);
panelButtom.add(labelHelp,BorderLayout.CENTER);
labelHelp=new JLabel("SPACE or P for pause",JLabel.CENTER);
相关文档
最新文档