贪吃蛇游戏.cpp
C++贪吃蛇说明
C语言课程设计报告题目:贪吃蛇指导教师:**院系:电气信息工程学院班级: 01 *名:***学号: 15目录1程序设计目的.......................................... 错误!未定义书签。
2程序设计具体要求...................................... 错误!未定义书签。
3程序功能.............................................. 错误!未定义书签。
4设计思路.............................................. 错误!未定义书签。
5程序清单.............................................. 错误!未定义书签。
6总结与体会............................................ 错误!未定义书签。
7结束语................................................ 错误!未定义书签。
1、课程设计目的:1.进一步掌握和利用C语言进行行程设计的能力;2.进一步理解和运用结构化程序设计的思想和方法;3.初步掌握开发一个小型实用系统的基本方法;4.学会调试一个较长程序的基本方法;5.学会利用流程图表示算法;6.掌握书写程序设计开发文档的能力(书写课程设计报告)。
2、课程设计具体要求:贪吃蛇是一种风靡全球的小游戏,就是一条小蛇,不停地在屏幕上游走,吃各个方向出现的蛋,越吃越长。
只要蛇头碰到屏幕四周,或者碰到自己的身子,小蛇就立即毙命。
和别的游戏不同,贪食蛇是一个悲剧性的游戏。
许多电子游戏都是打通关到底,游戏操作者以胜利而告终。
而贪食蛇的结局却是死亡。
“贪食蛇”,要命的就在一个“贪”字上。
所以,有时候真的需要及时收手,不要逼人太甚。
如果没有余地,就算你的手再快,面临的结局也是——崩盘。
C语言小游戏源代码《贪吃蛇》
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;
用Qt做贪吃蛇游戏
用Qt做贪吃蛇游戏开始游戏:撞到自己蛇身游戏结束:跳出界外游戏结束:main.cpp代码:#include<QtGui/QApplication>#include"mysnake.h"int main(int argc,char*argv[]) {QApplication a(argc,argv);mySnake w;w.show();return a.exec();}mysnake.h代码:#ifndef MYSNAKE_H#define MYSNAKE_H#include<QDialog>#include<QPainter>#include<QKeyEvent>#include<QString>#include<QFont>#include<QRect>#include<QTimer>namespace Ui{class mySnake;}class mySnake:public QDialog {Q_OBJECTpublic:explicit mySnake(QWidget*parent=0);~mySnake();void paintEvent(QPaintEvent*event);void init_Snake();//初始化void speed();//移动速度QRect createRect();//产生一个随机矩形void isEat();//判断是否吃到void isHit();//判断是否撞到自己private slots:void Snake_update();private:void keyPressEvent(QKeyEvent*key);Ui::mySnake*ui;bool isRun;//是否启动bool isOver;//是否结束QRect*SnakeRect;//蛇身QRect SnakeHeard;//蛇头QRect temp_SnakeRect;//随机矩形int SnakeLen;//蛇长QTimer*timer;//定时器int direction;//蛇移动方向QString display;//开始、结束提示QString scoreLabel;//得分标签int score;//得分};#endif//MYSNAKE_Hmysnake.cpp代码:#include"mysnake.h"#include"ui_mysnake.h"mySnake::mySnake(QWidget*parent):QDialog(parent),ui(new Ui::mySnake){ui->setupUi(this);}mySnake::~mySnake(){delete ui;}void mySnake::paintEvent(QPaintEvent*) {QPainter painter(this);if(!isRun){init_Snake();}//画背景painter.setPen(Qt::black);painter.setBrush(Qt::blue);painter.drawRect(15,15,260,260);painter.setPen(Qt::black);painter.setBrush(Qt::black);painter.drawRect(20,20,250,250);painter.setPen(Qt::blue);for(int ii=2;ii<=27;ii++){painter.drawLine(20,ii*10,270,ii*10);painter.drawLine(ii*10,20,ii*10,270);}QFont font("Courier",12);painter.setFont(font);painter.setPen(Qt::blue);painter.drawText(30,290,"By chenjt3533creation!");//显示开始、结束QFont font1("Courier",24);painter.setFont(font1);painter.setPen(Qt::red);painter.setBrush(Qt::red);painter.drawText(40,150,display);//计分QFont font2("Courier",15);painter.setFont(font2);painter.setPen(Qt::red);painter.setBrush(Qt::red);painter.drawText(290,60,scoreLabel);painter.drawText(360,60,QString::number(score));//画蛇painter.setBrush(Qt::red);painter.setPen(Qt::black);painter.drawRect(temp_SnakeRect);painter.drawRects(SnakeRect,SnakeLen);if(!isOver)speed();//运动速度}void mySnake::keyPressEvent(QKeyEvent*event){QKeyEvent*key=(QKeyEvent*)event;switch(key->key()){case Qt::Key_Up:direction=1;break;case Qt::Key_Down:direction=2;break;case Qt::Key_Left:direction=3;break;case Qt::Key_Right:direction=4;break;default:;}}void mySnake::init_Snake()//初始化snake{SnakeLen=5;//初始化snake的长度为5direction=2;//初始化snake的运动方向向下display="GAME START...";scoreLabel="Score:";score=0;isRun=true;isOver=false;temp_SnakeRect=createRect();SnakeRect=new QRect[SnakeLen];for(int i=0;i<SnakeLen;i++){QRect rect(100,70+10*i,10,10);SnakeRect[i]=rect;}SnakeHeard=SnakeRect[SnakeLen-1];}void mySnake::Snake_update(){display="";SnakeHeard=SnakeRect[SnakeLen-1];isHit();isEat();for(int j=0;j<SnakeLen-1;j++){SnakeRect[j]=SnakeRect[j+1];}switch(direction){case1:SnakeHeard.setHeight(SnakeHeard.height()-10);SnakeHeard.setTop(SnakeHeard.top()-10);break;case2:SnakeHeard.setHeight(SnakeHeard.height()+10);SnakeHeard.setTop(SnakeHeard.top()+10);break;case3:SnakeHeard.setLeft(SnakeHeard.left()-10);SnakeHeard.setRight(SnakeHeard.right()-10);break;case4:SnakeHeard.setLeft(SnakeHeard.left()+10);SnakeHeard.setRight(SnakeHeard.right()+10);break;default:;}SnakeRect[SnakeLen-1]=SnakeHeard;if(SnakeHeard.left()<20||SnakeHeard.right()>270||SnakeHeard.top()>260 ||SnakeHeard.bottom()<20){display="GAME OVER!";isOver=true;}update();//paintEvent更新}void mySnake::speed()//运动速度{timer=new QTimer(this);timer->setSingleShot(true);//将会只启动定时器一次,启动后每经过一次设定的时间就发送一次timeout()timer->start(500);//1秒connect(timer,SIGNAL(timeout()),SLOT(Snake_update()));}QRect mySnake::createRect()//产生一个随机矩形{int x,y;x=qrand()%25;y=qrand()%25;QRect rect(20+x*10,20+y*10,10,10);return rect;}void mySnake::isEat(){if(SnakeHeard==temp_SnakeRect){SnakeHeard=temp_SnakeRect;SnakeRect[SnakeLen]=SnakeHeard;SnakeLen++;temp_SnakeRect=createRect();score+=10;}}void mySnake::isHit(){for(int i=0;i<SnakeLen-1;i++){if(SnakeHeard==SnakeRect[i]){display="GAME OVER!";isOver=true;update();}}}。
C语言程序设计:贪吃蛇程序源代码用TC2.0编译
C语言程序设计:贪吃蛇程序源代码用TC2.0编译本程序为贪吃蛇游戏,想必大家都玩过这个游戏,程序源代码用TC2.0编译通过,需要图形驱动文件的支持,在TC2.0的集成环境中有.本程序利用数据结构中的链表,来将蛇身连接,同时当蛇吃到一定数目的东西时会自动升级,及移动速度会加快,程序会时刻将一些信息显示在屏幕上,包括所得分数,要吃多少东西才能升级,并且游戏者可以自己手动选择游戏级别,级别越高,蛇的移动速度越快.另外,此游戏可能与CPU的速度有关系.源代码如下:******************************************************************************* ***/*******************************COMMENTS**********************************/ /* snake_game.c*//* it is a game for entermainment.*//* in the begin,there is only a snake head,and it will have to eat food *//* to become stronger,and it eat a piece of food each time,it will *//* lengthen it's body,with the number of food the snake eats going up,it *//* will become long more and more,and the score will goes up also. *//* there is always useful information during the game process. *//* if the path by which the snake goes to eat food is the shortest,the *//* score will add up a double.*//**//* enjoy yourself,and any problem,contact <blldw@> *//*************************************************************************//* all head file that will be used */#include<stdio.h>#include<time.h>#include<graphics.h>#include<stdlib.h>#include<ctype.h>#include<string.h>/* useful MACRO */#define FOOD_SIZE 8#define SCALE 8#define UP_KEY 0x4800#define DOWN_KEY 0x5000#define LEFT_KEY 0x4b00#define RIGHT_KEY 0x4d00#define MOVE_UP 1#define MOVE_LEFT 2#define MOVE_DOWN 3#define MOVE_RIGHT 4#define INV ALID_DIRECTION 0#define QUIT_KEYC 0x1051#define QUIT_KEY 0x1071#define SELECT_KEYC 0x1f53#define SELECT_KEY 0x1f73#define PAUSE_KEYC 0x1950#define PAUSE_KEY 0x1970#define DEFAULT_LEVEL 1#define HELP_COLOR WHITE#define WELCOME_COLOR WHITE#define DEFAULT_COLOR GREEN/* define the macro as follows to improve the game in future */#define FOOD_COLOR YELLOW#define SNAKE_HEAD_COLOR RED#define DEFAULT_SNAKE_COLOR YELLOW#define EXIT_COLOR WHITE#define SCORE_COLOR YELLOW/* sturcture for snake body mainly ,and food also */typedef struct food_infor *FOOD_INFOR_PTR;typedef struct food_infor{int posx; /* position for each piece of snake body */int posy;int next_move; /* next move direction */int pre_move; /* previous move direction,seems unuseful */int beEaten; /* xidentifier for snake body or food */FOOD_INFOR_PTR next; /* pointer to next piece of snake body */ FOOD_INFOR_PTR pre; /* pointer to previous piece of snake body */ }FOOD_INFOR;/* structure for snake head */typedef struct _snake_head{int posx;int posy;int next_move;int pre_move;int eatenC; /* number of food that have been eaten */int hop; /* number of steps to eat food */FOOD_INFOR_PTR next; /* pointer to the first piece of eaten food */ }SNAKE_HEAD;/* the left-up corner and right-down corner */typedef struct point{int x;int y;}POINT;/* standards for game speed*//* before level 5,the time interval is level_b[level - 1] / 10,and after */ /* level 5,the time interval is 1.00 / level_b[level - 1] */float level_b[9] = {10.0,8.0,6.0,3.0,1.0,20.0,40.0,160.0,640.0};/* available varary */SNAKE_HEAD snake_head;FOOD_INFOR *current; /* always point to food */POINT border_LT,border_RB;int driver,mode; /* for graphics driver */int maxx,maxy; /* max length and width of screen,in pixel */int eaten; /* identifier if the food is eaten */int score = 0; /* total score */int level = DEFAULT_LEVEL; /* level or speed */float interval; /* based on speed */int snake_color = DEFAULT_SNAKE_COLOR; /* snake body color */ int hopcount = 0; /* the shortest number of steps for snake *//* to eat food *//* all sub function */void init_graphics();void generate_first_step();int judge_death();int willeatfood();void generate_food();void addonefood();void redrawsnake();void show_all();void sort_all();void change_direction();void help();void show_score(int);void change_level();void show_level();void release(SNAKE_HEAD);int can_promote();void win();void show_infor_to_level();void show_eaten();void calculate_hop();/* main function or entry */void main(){char str[50] = "YOU LOSE!!!"; /* fail information */ clock_t start;int querykey;int tempx,tempy;/* if fail and want to resume game,go here */retry:init_graphics();show_all(); /* show wall */generate_first_step(); /* generate food and snake head */ show_score(score); /* show score to player */eaten = 0;/* begin to play game */while(1){if(judge_death() == 1) /* die */break;if(willeatfood() == 1){eaten = 1;addonefood();snake_head.hop ++;if(snake_head.hop == hopcount)score += level * 2;elsescore += level;can_promote();show_score(score);}sort_all();redrawsnake();snake_head.hop ++;show_infor_to_level();show_eaten();show_all();change_direction();if(eaten == 1){generate_food();calculate_hop();snake_head.hop = 0;eaten = 0;}if(level <= 5)interval = level_b[level - 1] / 10.0;elseinterval = 1.00 / level_b[level - 1];start = clock();while((clock() - start) / CLK_TCK < interval) {querykey = bioskey(1);if(querykey != 0){switch(bioskey(0)){case UP_KEY:snake_head.next_move = MOVE_UP;break;case LEFT_KEY:snake_head.next_move = MOVE_LEFT;break;case DOWN_KEY:snake_head.next_move = MOVE_DOWN;break;case RIGHT_KEY:snake_head.next_move = MOVE_RIGHT;break;case SELECT_KEYC:case SELECT_KEY:change_level();score = 0;show_score(score);show_level();break;case PAUSE_KEYC:case PAUSE_KEY:while(!bioskey(1));break;case QUIT_KEYC:case QUIT_KEY:goto exit_game;default:break;}}}}settextstyle(DEFAULT_FONT,0,2);setcolor(EXIT_COLOR);tempx = border_LT.x + (border_RB.x - border_LT.x - textwidth(str)) / 2; tempy = border_LT.y + (border_RB.y - border_LT.y) / 2;outtextxy(tempx,tempy,str);strcpy(str,"press <R/r> to retry,or ENTER key to exit");tempy += textheight(str) * 2;settextstyle(DEFAULT_FONT,0,1);tempx = border_LT.x + (border_RB.x - border_LT.x - textwidth(str)) / 2; outtextxy(tempx,tempy,str);select:while(!bioskey(1));querykey = bioskey(0);if((querykey == 0x1372) || (querykey == 0x1352)){level = DEFAULT_LEVEL;score = 0;release(snake_head);closegraph();goto retry;}if(querykey != 0x1c0d)goto select;closegraph();return;exit_game:release(snake_head);closegraph();}/* sub function show_eaten() *//* function: to show the total number piece of food *//* that have been eaten by snake any time */void show_eaten(){int tempx,tempy;int size;void *buf;char str[15];settextstyle(DEFAULT_FONT,0,1);setcolor(DEFAULT_COLOR);sprintf(str,"eaten:%d",snake_head.eatenC);tempx = 0;tempy = border_LT.y + textheight(str) * 6;size = imagesize(tempx,tempy,tempx + textwidth(str) + textwidth("A"), tempy + textheight(str));buf = malloc(size);getimage(tempx,tempy,tempx + textwidth(str) + textwidth("A"), tempy + textheight(str),buf);putimage(tempx,tempy,buf,XOR_PUT);outtextxy(tempx,tempy,str);free(buf);}/* sub function: show_infor_to_level *//* function:show information to player that how many pieces *//* of food have to been eaten to get to next level *//* ,and this is not related with score,but only *//* eaten number of food*//**//* level standard:let highlevel stand for the number of *//* pieces of food that can be put int the *//* vertical direction of play area,and *//* before level 5,as long as the snake eat *//* a quarter of highlevel,it will go to next *//* level,and between level 5 and 7,as long *//* as the snake eat one thirds of highlevel, *//* it will go to next level,and between *//* level 8 and 9,the snake will go to next *//* level as long as it eat half of highlevel *//* note: level is between 1 to 9. */void show_infor_to_level(){int highlevel;int size;int tempx,tempy;int toeat;void *buf;char str[50];highlevel = (border_RB.y - border_LT.y) / SCALE;switch(level){case 1:case 2:case 3:case 4:toeat = (highlevel / 4) * level - snake_head.eatenC;break;case 5:case 6:case 7:toeat = (highlevel + highlevel / 3 * (level - 4)) - snake_head.eatenC; break;case 8:case 9:toeat = (highlevel * 2 + highlevel / 2 * (level - 7)) -snake_head.eatenC;break;default:break;}settextstyle(DEFAULT_FONT,0,1);setcolor(DEFAULT_COLOR);if(snake_head.next == NULL){sprintf(str,"next level");tempx = 0;tempy = border_LT.y + textheight(str) * 2;outtextxy(tempx,tempy,str);}if(toeat < 0)toeat = 0;sprintf(str,"%d:%d",level + 1,toeat);tempx = 0;tempy = border_LT.y + textheight(str) * 4;size = imagesize(tempx,tempy,tempx + textwidth(str) + textwidth("A"),tempy +textheight(str));buf = malloc(size);getimage(tempx,tempy,tempx + textwidth(str) + textwidth("A"),tempy +textheight(str),buf);putimage(tempx,tempy,buf,XOR_PUT);outtextxy(tempx,tempy,str);free(buf);}/* sub function: win() *//* function:if the player pass level 9,this function *//* will be called ,to show "YOU WIN information *//* and after a key is pressed,the game will go *//* on,but all is back to begin,excepte the *//* snake body length.*/void win(){char str[] = "YOU WIN";int tempx,tempy;settextstyle(DEFAULT_FONT,0,8);setcolor(WELCOME_COLOR);tempx = border_LT.x + (border_RB.x - border_LT.x - textwidth(str)) / 2; tempy = border_LT.y + (border_RB.y - border_LT.y - textheight(str)) / 2;outtextxy(tempx,tempy,str);while(!bioskey(1));}/* sub function: can_promote() *//* function:see if the snake can go to next level on basis *//* of the snake length.*//**//* note:standards of promote level is instructed above */int can_promote(){/* compare SCORE with standard level score */int high_level;static int last_score = 0;high_level = (border_RB.y - border_LT.y) / SCALE;switch(level){case 1:case 2:case 3:case 4:if(snake_head.eatenC == (high_level / 4 * level))level ++;last_score = score;break;case 5:case 6:case 7:if(snake_head.eatenC == (high_level + high_level / 3 * (level - 4))) level ++;last_score = score;break;case 8:if(snake_head.eatenC == (high_level * 2 + high_level / 2 ))level ++;last_score = score;break;case 9:if(snake_head.eatenC == (high_level * 3)){win();score = 0;last_score = 0;level = DEFAULT_LEVEL;}break;default:break;}show_level();}/* sub function: calulate_hop() *//* function: calculate the shortest path from snake head to *//* the food it will eaten. */void calculate_hop(){hopcount = (snake_head.posx >= current->posx) ? ((snake_head.posx - current->posx) /SCALE) :((current->posx - snake_head.posx) / SCALE);hopcount += (snake_head.posy >= current->posy) ? ((snake_head.posy - current->posy) /SCALE) :((current->posy - snake_head.posy) / SCALE);}/* sub function: release()*//* function:free memory before exit game or restart */void release(SNAKE_HEAD snake_head){FOOD_INFOR_PTR traceon,last;traceon = snake_head.next;snake_head.eatenC = 0;snake_head.next = NULL;snake_head.hop = 0;while(traceon)if(traceon->next != NULL)traceon = traceon->next;elsebreak;while(traceon){last = traceon->pre;free(traceon);traceon = last;}}/* sub function: show_level()x *//* function:show level information to player anytime */void show_level(){char str[20];int size;void *buf;settextstyle(DEFAULT_FONT,0,1);setcolor(DEFAULT_COLOR);sprintf(str,"Level:%d",level);size = imagesize(0,border_LT.y,textwidth(str),border_LT.y + textheight(str)); buf = malloc(size);getimage(0,border_LT.y,textwidth(str),border_LT.y + textheight(str),buf);putimage(0,border_LT.y,buf,XOR_PUT);free(buf);outtextxy(0,border_LT.y,str);}/* sub function: change_level() *//* function:if the play choose "select level <S/S>" item, *//* this function will be called */void change_level(){int c;int size;void *buf;int tempx,tempy;char str[] = "new level (1--9):";settextstyle(DEFAULT_FONT,0,1);setcolor(DEFAULT_COLOR);tempx = 0;tempy = border_LT.y - textheight("A") * 3 / 2;outtextxy(tempx,tempy,str);goon:while(!bioskey(1));c = bioskey(0);if((c == 0x1051) || (c == 0x1071))goto exit;if(isdigit(c&0x00ff))level = (c&0x00ff) - 48;elsegoto goon;exit:size = imagesize(tempx,tempy,tempx + textwidth(str),tempy + textheight(str)); buf = malloc(size);getimage(tempx,tempy,tempx + textwidth(str),tempy + textheight(str),buf); putimage(tempx,tempy,buf,XOR_PUT);free(buf);}/* sub function: show_score() *//* function:show score information to player anytime */void show_score(int count){int th;int size;char str[20];settextstyle(DEFAULT_FONT,0,2);setcolor(SCORE_COLOR);sprintf(str,"Score: %d",count);th = textheight("hello");if((count == 0) && (snake_head.next == NULL)){outtextxy(border_LT.x + (border_RB.x - border_LT.x) / 4,border_LT.y - 2 * th,str);}else{size = imagesize(border_LT.x + (border_RB.x - border_LT.x) / 4,border_LT.y - 2 * th,border_LT.x + (border_RB.x - border_LT.x) / 4 +textwidth(str) + textwidth("100"),border_LT.y - 2 * th + th);buf = malloc(size);getimage(border_LT.x + (border_RB.x - border_LT.x) / 4,border_LT.y - 2 * th, border_LT.x + (border_RB.x - border_LT.x) / 4 + textwidth(str) +textwidth("100"),border_LT.y - 2 * th + th,buf);putimage(border_LT.x + (border_RB.x - border_LT.x) / 4,border_LT.y - 2 * th,buf,XOR_PUT);outtextxy(border_LT.x + (border_RB.x - border_LT.x) / 4,border_LT.y - 2 * th,str);free(buf);}}/* sub function: help()*//* function: show help information at the beginning of game *//* and let player know how to play the game */void help(){int th;settextstyle(DEFAULT_FONT,0,1);setcolor(HELP_COLOR);th = textheight("hello");sprintf(str,"move left : %c",27);outtextxy(border_LT.x,border_RB.y,str);sprintf(str,"move up : %c",24);outtextxy(border_LT.x + (border_RB.x - border_LT.x) / 2,border_RB.y,str);sprintf(str,"move down : %c",25);outtextxy(border_LT.x,border_RB.y + th + 2,str);sprintf(str,"move right: %c",26);outtextxy(border_LT.x + (border_RB.x - border_LT.x) / 2,border_RB.y + th + 2,str);outtextxy(border_LT.x,border_RB.y + th * 2 + 4,"quit <Q/q>");outtextxy(border_LT.x + textwidth("quit <Q/q>") * 3 / 2,border_RB.y + th * 2 + 4, "pause <P/p>");outtextxy(border_LT.x + (border_RB.x - border_LT.x) / 2,border_RB.y + th * 2 + 4,"select level <S/s>");}/* sub function: show_all()*//* function:redraw the play area,means show wall */void show_all(){int i,j;setcolor(DEFAULT_COLOR);/*for(i = border_LT.x; i <= border_RB.x; i += SCALE)for(j = border_LT.y; j <= border_RB.y; j += SCALE)rectangle(i,j,i + SCALE, j + SCALE);*/rectangle(border_LT.x,border_LT.y,border_RB.x,border_RB.y);}/* sub function: generate_food()*//* function:after the food is eaten by snake,the function will *//* be called to generate another food,and it will *//* ensure that the generated food shouldn't appeare *//* in the snake body.*/void generate_food(){FOOD_INFOR_PTR traceon;int tempx,tempy;generate:current->posx = random(border_RB.x - SCALE / 2);while((current->posx <= border_LT.x) || ((current->posx - border_LT.x) % SCALE == 0) || ((current->posx - border_LT.x) % SCALE % (SCALE / 2) != 0))current->posx ++;current->posy = random(border_RB.y - SCALE / 2);while((current->posy <= border_LT.y) || ((current->posy - border_LT.y) % SCALE == 0) || ((current->posy - border_LT.y) % SCALE % (SCALE / 2) != 0))current->posy ++;traceon = snake_head.next;while(traceon){if((traceon->posx == current->posx) && (traceon->posy == current->posy))goto generate;traceon = traceon->next;}if(current->posx - border_LT.x == SCALE / 2)current->posx += SCALE;if(border_RB.x - current->posx == SCALE / 2)current->posx -= SCALE;if(current->posy - border_LT.y == SCALE / 2)current->posy += SCALE;if(border_RB.y - current->posy == SCALE / 2)current->posy -= SCALE;setcolor(DEFAULT_COLOR);rectangle(current->posx - SCALE / 2,current->posy - SCALE / 2, current->posx + SCALE / 2,current->posy + SCALE / 2); setfillstyle(SOLID_FILL,YELLOW);floodfill(current->posx,current->posy,DEFAULT_COLOR);}/* sub function: init_graphics()*//* function:initialize the game interface */void init_graphics(){driver = DETECT;mode = 0;initgraph(&driver,&mode,"*.bgi");maxx = getmaxx();maxy = getmaxy();border_LT.x = maxx / SCALE;border_LT.y = maxy / SCALE;border_RB.x = maxx * (SCALE - 1) / SCALE;border_RB.y = maxy * (SCALE - 1) / SCALE;while((border_RB.x - border_LT.x) % FOOD_SIZE)(border_RB.x) ++;while((border_RB.y - border_LT.y) % FOOD_SIZE)(border_RB.y) ++;while((border_RB.y - border_LT.y) % ( 12 * SCALE))border_RB.y += SCALE;setcolor(DEFAULT_COLOR);rectangle(border_LT.x,border_LT.y,border_RB.x,border_RB.y);help();show_level();}/* sub function: generateX_first_step() *//* function:generate snake head and first food to prepare for *//* game to start,and this function will also initialize*//* the move direction of snake head,and show welcome *//* information to player.*/void generate_first_step(){char str[] = "welcome to snake game,press ENTER key to start";int size;int tempx,tempy;void *buf;randomize();/* generate snake head */snake_head.posx = random(border_RB.x - SCALE / 2);while((snake_head.posx <= border_LT.x) || ((snake_head.posx - border_LT.x) % SCALE == 0)||((snake_head.posx - border_LT.x) % SCALE % (SCALE / 2) != 0))snake_head.posx ++;snake_head.posy = random(border_RB.y - SCALE / 2);while((snake_head.posy <= border_LT.y) || ((snake_head.posy - border_LT.y) % SCALE == 0)||((snake_head.posy - border_LT.y) % SCALE % (SCALE / 2) != 0))snake_head.posy ++;setcolor(DEFAULT_COLOR);rectangle(snake_head.posx - SCALE / 2,snake_head.posy - SCALE / 2,snake_head.posx + SCALE / 2,snake_head.posy + SCALE / 2);setfillstyle(SOLID_FILL,SNAKE_HEAD_COLOR);floodfill(snake_head.posx,snake_head.posy,DEFAULT_COLOR);/* generate first food */current = (FOOD_INFOR_PTR)malloc(sizeof(FOOD_INFOR));goon_generate:current->posx = random(border_RB.x - SCALE / 2);while((current->posx <= border_LT.x) || ((current->posx - border_LT.x) % SCALE == 0) || ((current->posx - border_LT.x) % SCALE % (SCALE / 2) != 0))current->posx ++;current->posy = random(border_RB.y - SCALE / 2);while((current->posy <= border_LT.y) || ((current->posy - border_LT.y) % SCALE == 0) || ((current->posy - border_LT.y) % SCALE % (SCALE / 2) != 0))current->posy ++;if((current->posx == snake_head.posx) && (current->posy == snake_head.posy))goto goon_generate;rectangle(current->posx - SCALE / 2,current->posy - SCALE / 2,current->posx + SCALE / 2,current->posy + SCALE / 2);setfillstyle(SOLID_FILL,FOOD_COLOR);floodfill(current->posx,current->posy,DEFAULT_COLOR);calculate_hop();snake_head.next = NULL;snake_head.eatenC = 0;snake_head.hop = 0;current->next = NULL;current->pre = NULL;current->beEaten = 0;current->next_move = INV ALID_DIRECTION;current->pre_move = INV ALID_DIRECTION;if(snake_head.posx == current->posx){if(snake_head.posy > current->posy)snake_head.next_move = MOVE_UP;elsesnake_head.next_move = MOVE_DOWN;}else{if(snake_head.posx < current->posx)snake_head.next_move = MOVE_RIGHT;elsesnake_head.next_move = MOVE_LEFT;}snake_head.pre_move = snake_head.next_move;settextstyle(DEFAULT_FONT,0,1);setcolor(WELCOME_COLOR);tempx = border_LT.x + (border_RB.x - border_LT.x - textwidth(str)) / 2; tempy = border_LT.y - textheight("A") * 6 / 2;outtextxy(tempx,tempy,str);size = imagesize(tempx,tempy,tempx + textwidth(str),tempy + textheight(str));buf = malloc(size);getimage(tempx,tempy,tempx + textwidth(str),tempy + textheight(str),buf);while(bioskey(0) != 0x1c0d);putimage(tempx,tempy,buf,XOR_PUT);free(buf);}/* sub function: judge_death()*//* function:judge if the snake will die because of incorrect *//* move,there are two things that will result *//* the snake to death:first,it run into the wall *//* ,and second,it run into its body.*/int judge_death(){/* return 1 means will die,and return 0 means will survive */int tempx,tempy;switch(snake_head.next_move){case MOVE_UP:tempx = snake_head.posx;tempy = snake_head.posy - SCALE;break;case MOVE_LEFT:tempx = snake_head.posx - SCALE;tempy = snake_head.posy;break;case MOVE_DOWN:tempx = snake_head.posx;tempy = snake_head.posy + SCALE;break;case MOVE_RIGHT:tempx = snake_head.posx + SCALE;tempy = snake_head.posy;break;default:break;}if((tempx < border_LT.x) || (tempx > border_RB.x) || (tempy < border_LT.y) || (tempy > border_RB.y))return 1;if(getpixel(tempx,tempy) == snake_color){FOOD_INFOR_PTR traceon;traceon = snake_head.next;while(traceon != NULL){if((traceon->posx == tempx) && (traceon->posy == tempy)) return 1;traceon = traceon->next;}}return 0; /* survive */}/* sub function: willeatfood() *//* function:judge if the sanke can eat food.the method like */ /* this:provided that the snake move a step based *//* on its next move direction,and if this place *//* have food,then the snake can eat food. */int willeatfood(){/* 1 means will eat food ,and 0 means won't eat food */int tempx,tempy;switch(snake_head.next_move){case MOVE_UP:tempx = snake_head.posx;tempy = snake_head.posy - SCALE;break;case MOVE_LEFT:tempx = snake_head.posx - SCALE;tempy = snake_head.posy;break;case MOVE_DOWN:tempx = snake_head.posx;tempy = snake_head.posy + SCALE;break;case MOVE_RIGHT:tempx = snake_head.posx + SCALE;tempy = snake_head.posy;break;default:break;}if(getpixel(tempx,tempy) == FOOD_COLOR)return 1;return 0;}/* sub function: addonefood() *//* function: this function will lengthen the snake body *//* this function is important because it will *//* not only locate memory for new snake body, *//* but also handle the relationship of pointer*//* between the new snake body and its previous*//* snake body.*/void addonefood(){FOOD_INFOR_PTR traceon;snake_head.eatenC ++ ;traceon = snake_head.next;if(snake_head.next == NULL) /* haven't eaten any food */{traceon = (FOOD_INFOR_PTR)malloc(sizeof(FOOD_INFOR));switch(snake_head.next_move){case MOVE_UP:traceon->posx = snake_head.posx;traceon->posy = snake_head.posy + SCALE;break;case MOVE_LEFT:traceon->posx = snake_head.posx + SCALE;traceon->posy = snake_head.posy;break;case MOVE_DOWN:traceon->posx = snake_head.posx;traceon->posy = snake_head.posy - SCALE;break;case MOVE_RIGHT:traceon->posx = snake_head.posx - SCALE;traceon->posy = snake_head.posy;break;default:break;}traceon->next_move = snake_head.next_move;traceon->pre_move = snake_head.next_move;traceon->next = NULL;traceon->pre = NULL;traceon->beEaten = 1;snake_head.next = traceon;}else{while(traceon){if(traceon->next != NULL)traceon = traceon->next;elsebreak;}traceon->next = (FOOD_INFOR_PTR)malloc(sizeof(FOOD_INFOR));traceon->next->next = NULL;traceon->next->pre = traceon;traceon = traceon->next;switch(traceon->pre->next_move){case MOVE_UP:traceon->posx = traceon->pre->posx;traceon->posy = traceon->pre->posy + SCALE;break;case MOVE_LEFT:traceon->posx = traceon->pre->posx + SCALE;traceon->posy = traceon->pre->posy;break;case MOVE_DOWN:traceon->posx = traceon->pre->posx;traceon->posy = traceon->pre->posy - SCALE;break;case MOVE_RIGHT:traceon->posx = traceon->pre->posx - SCALE;traceon->posy = traceon->pre->posy;break;default:break;}traceon->next_move = traceon->pre->next_move;traceon->pre_move = traceon->pre->next_move;traceon->beEaten = 1;}}/* sub function: sort_all()*//* function:this function will calculate the next position of snake *//* and it is assume the snake has move to next position,but*//* haven't appeared yet.*/void sort_all(){/* sort all food,include snake head,and virtual place */FOOD_INFOR_PTR traceon;void *buf;int size;size = imagesize(snake_head.posx - SCALE / 2,snake_head.posy - SCALE / 2, snake_head.posx + SCALE / 2,snake_head.posy + SCALE /2);buf = malloc(size);getimage(snake_head.posx - SCALE / 2,snake_head.posy - SCALE / 2, snake_head.posx + SCALE / 2,snake_head.posy + SCALE / 2,buf); putimage(snake_head.posx - SCALE / 2,snake_head.posy - SCALE / 2,buf,XOR_PUT);switch(snake_head.next_move){case MOVE_UP:snake_head.posy -= SCALE;break;case MOVE_LEFT:snake_head.posx -= SCALE;break;case MOVE_DOWN:snake_head.posy += SCALE;break;case MOVE_RIGHT:snake_head.posx += SCALE;break;default:break;}traceon = snake_head.next;while(traceon){getimage(traceon->posx - SCALE / 2,traceon->posy - SCALE / 2, traceon->posx + SCALE / 2,traceon->posy + SCALE / 2,buf); putimage(traceon->posx - SCALE / 2,traceon->posy - SCALE / 2, buf,XOR_PUT);switch(traceon->next_move){case MOVE_UP:traceon->posy -= SCALE;break;case MOVE_LEFT:traceon->posx -= SCALE;break;case MOVE_DOWN:traceon->posy += SCALE;break;case MOVE_RIGHT:traceon->posx += SCALE;break;default:break;}traceon = traceon->next;}free(buf);}/* sub function: redrawsnake()*//* function:the function will redraw the snake based on function*/ /* sort_all().*/void redrawsnake(){。
超简单贪吃蛇c语言代码编写
超简单贪吃蛇c语言代码编写贪吃蛇其实就是实现以下几步——1:蛇的运动(通过“画头擦尾”来达到蛇移动的视觉效果)2:生成食物3:蛇吃食物(实现“画头不擦尾”)4:游戏结束判断(也就是蛇除了食物,其余东西都不能碰)#include<stdio.h>#include<stdlib.h>#include<windows.h>#include<conio.h>#include<time.h>#define width 60#define hight 25#define SNAKESIZE 200//蛇身的最长长度int key=72;//初始化蛇的运动方向,向上int changeflag=1;//用来标识是否生成食物,1表示蛇还没吃到食物,0表示吃到食物int speed=0;//时间延迟struct {int len;//用来记录蛇身每个方块的坐标int x[SNAKESIZE];int y[SNAKESIZE];int speed;}snake;struct{int x;int y;}food;void gotoxy(int x,int y)//调用Windows的API函数,可以在控制台的指定位置直接操作,这里可暂时不用深究{COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }//■○void drawmap(){//打印图框for (int _y = 0; _y < hight; _y++){for (int x = 0; x < width; x+=2){if (x == 0 || _y == 0 || _y == hight - 1 || x == width - 2){gotoxy(x, _y);printf("■");}}}//打印蛇头snake.len=3;snake.x[0]=width/2;snake.y[0]=hight/2;gotoxy(snake.x[0],snake.y[0]);printf("■");//打印蛇身for(int i=1;i<snake.len;i++){snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1]+1;gotoxy(snake.x[i],snake.y[i]);printf("■");}//初始化食物的位置food.x=20;food.y=20;gotoxy(food.x,food.y);printf("○");}/**控制台按键所代表的数字*“↑”:72*“↓”:80*“←”:75*“→”:77*/void snake_move()//按键处理函数{int history_key=key;if (_kbhit()){fflush(stdin);key = _getch();key = _getch();}if(changeflag==1)//还没吃到食物,把尾巴擦掉{gotoxy(snake.x[snake.len-1],snake.y[snake.len-1]);printf(" ");}for(int i=snake.len-1;i>0;i--){snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1];}if(history_key==72&&key==80)key=72;if(history_key==80&&key==72)key=80;if(history_key==75&&key==77)key=75;if(history_key==77&&key==75)key=77;switch(key){case 72:snake.y[0]--;break;case 75:snake.x[0]-= 2;break;case 77:snake.x[0]+= 2;break;case 80:snake.y[0]++;break;}gotoxy(snake.x[0],snake.y[0]);printf("■");gotoxy(0,0);changeflag=1;}void creatfood(){if(snake.x[0] == food.x && snake.y[0] == food.y)//只有蛇吃到食物,才能生成新食物{changeflag=0;snake.len++;if(speed<=100)speed+=10;while(1){srand((unsigned int) time(NULL));food.x=rand()%(width-6)+2;//限定食物的x范围不超出围墙,但不能保证food.x 为偶数food.y=rand()%(hight-2)+1;for(int i=0;i<snake.len;i++){if(food.x==snake.x[i]&&food.y==snake.y[i])//如果产生的食物与蛇身重合则退出break;}if(food.x%2==0)break;//符合要求,退出循环}gotoxy(food.x,food.y);printf("○");}}bool Gameover(){//碰到围墙,OVERif(snake.x[0]==0||snake.x[0]==width-2)return false;if(snake.y[0]==0||snake.y[0]==hight-1) return false;//蛇身达到最长,被迫OVERif(snake.len==SNAKESIZE)return false;//头碰到蛇身,OVERfor(int i=1;i<snake.len;i++){if(snake.x[0]==snake.x[i]&&snake.y[0]==snake.y[i])return false;}return true;}int main(){system("mode con cols=60 lines=27");drawmap();while(Gameover()){snake_move();creatfood();Sleep(350-speed);//蛇的移动速度}return 0;}。
C语言实现贪吃蛇游戏(命令行)
C语⾔实现贪吃蛇游戏(命令⾏)这是⼀个纯C语⾔写的贪吃蛇游戏,供⼤家参考,具体内容如下#include<stdio.h>#include<stdlib.h>#include<windows.h>#include<time.h>#include<conio.h>#define SNAKE_LENGTH 100//定义蛇的最⼤长度#define SCREEN_WIDETH 80#define SCREEN_HEIGHT 30//定义每⼀节蛇的坐标struct coor{int x;int y;};//枚举⽅向enum CH {right = VK_RIGHT,left = VK_LEFT,up = VK_UP,down = VK_DOWN};//定义蛇的属性struct snake{int len;//当前蛇的长度struct coor coord[SNAKE_LENGTH];//每⼀节蛇的坐标enum CH CH;//定义蛇的⽅向int SPEED;int flag;//定义蛇的状态 1表⽰存活 0表⽰死亡}snake;//光标移动函数void gotoxy(int x, int y){COORD pos;pos.X = x;pos.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);}//初始化游戏界⾯void init_sence(){//初始化上下墙for (int i = 0; i < SCREEN_WIDETH; i += 2){gotoxy(i,0);printf("■");gotoxy(i, SCREEN_HEIGHT);printf("■");}//初始化左右墙for (int i = 0; i <=SCREEN_HEIGHT; i++){gotoxy(0, i);printf("■");gotoxy(SCREEN_WIDETH,i);printf("■");}//打印提⽰信息gotoxy(SCREEN_WIDETH + 5, 2);printf("\t\t贪吃蛇");gotoxy(SCREEN_WIDETH + 5, 6);printf("2018//12//1");gotoxy(SCREEN_WIDETH + 5, 8);printf("作者:⼩⾖芽");gotoxy(SCREEN_WIDETH + 5, 10);printf("F1:加速\tF2:减速");gotoxy(SCREEN_WIDETH + 5, 12);printf("CTRL:继续\t空格:暂停");gotoxy(SCREEN_WIDETH + 5, 14);printf("ESC:退出游戏");gotoxy(SCREEN_WIDETH + 5, 28);printf("建议:QQ:2862841130:::");}struct foodcoord {int x;int y;int flag;//定义⾷物的状态}food;//**这是c程序**#include"snake.h"//蛇的移动void move_snake();//画出蛇void draw_snake();//产⽣⾷物void creatfood();//判断蛇是否吃到⾷物void eatfood();//判断蛇是否死掉void SnakeState();int main(){//设置窗⼝⼤⼩system("mode con cols=110 lines=31");//设置标题SetConsoleTitleA("贪吃蛇");//初始化蛇begin:snake.CH = VK_RIGHT;//初始化⽅向snake.len = 5; //初始化长度snake.SPEED = 300;//初始化蛇的移动速度snake.coord[1].x = SCREEN_WIDETH / 2;//初始化蛇头的坐标 snake.coord[1].y = SCREEN_HEIGHT / 2;snake.coord[2].x = SCREEN_WIDETH / 2-2;//初始化蛇头的坐标 snake.coord[2].y = SCREEN_HEIGHT / 2;snake.coord[3].x = SCREEN_WIDETH / 2-4;//初始化蛇头的坐标 snake.coord[3].y = SCREEN_HEIGHT / 2;//初始化⾷物状态food.flag = 1;//1表⽰吃到⾷物 0表⽰没有吃到⾷物//初始化⾷物状态snake.flag = 1;//1活 0死init_sence();//初始化游戏界⾯while (1){draw_snake();//画蛇Sleep(snake.SPEED);//蛇的移动速度move_snake();//移动蛇if(food.flag)creatfood();//产⽣⾷物eatfood();//判断是否吃到⾷物SnakeState();//判断蛇是否死亡if (!snake.flag)break;}system("cls");gotoxy(SCREEN_WIDETH/2, SCREEN_HEIGHT/2-4);printf(" GAME OVER");gotoxy(SCREEN_WIDETH / 2-6, SCREEN_HEIGHT / 2+2);printf("你的得分是:\t\t\t%d ",snake.len-1);gotoxy(SCREEN_WIDETH / 2-6, SCREEN_HEIGHT / 2+4);printf("我不服再来:\t\t\tCTRL ");gotoxy(SCREEN_WIDETH / 2-6, SCREEN_HEIGHT / 2+6);printf("算了垃圾游戏毁我青春:\t\tESC");while (1){if (GetAsyncKeyState(VK_CONTROL)){system("cls");goto begin;}else if (GetAsyncKeyState(VK_ESCAPE))return 0;}}//蛇的移动void move_snake(){//判断是否有按键操作if (GetAsyncKeyState(up)){if(snake.CH!=down)snake.CH = up;}else if (GetAsyncKeyState(down)){if (snake.CH != up)snake.CH = down;}else if (GetAsyncKeyState(right)){if (snake.CH != left)snake.CH = right;}else if (GetAsyncKeyState(left)){if (snake.CH != right)snake.CH = left;}else if (GetAsyncKeyState(VK_F1)){if(snake.SPEED>=100)snake.SPEED -= 50;}else if (GetAsyncKeyState(VK_F2)){if (snake.SPEED <= 3000)snake.SPEED += 100;}//根据检测到的⽅向改变蛇头的位置switch (snake.CH){case right:snake.coord[1].x += 2; break;case left:snake.coord[1].x -= 2; break;case up:snake.coord[1].y -= 1; break;case down:snake.coord[1].y += 1; break;}}//画出蛇void draw_snake(){//画出蛇头gotoxy(snake.coord[1].x, snake.coord[1].y);printf("□");//画出蛇⾝,直接⼀个for循环实现for (int i = 2; i <= snake.len; i++){gotoxy(snake.coord[i].x, snake.coord[i].y);printf("□");}//擦掉尾巴gotoxy(snake.coord[snake.len].x, snake.coord[snake.len].y); printf(" ");//遍历每⼀节蛇for (int i = snake.len; i >1; i--){snake.coord[i].x = snake.coord[i - 1].x;snake.coord[i].y = snake.coord[i - 1].y;}gotoxy(0, 0);printf("■");gotoxy(85, 25);printf("得分:%d ", snake.len-1);}//产⽣⾷物void creatfood(){//随机种⼦⽣成srand((unsigned)time(NULL));if(food.flag)while (1){food.x = rand() % 80;food.y = rand() % 30;if (food.x % 2 == 0 && food.x >= 2 && food.x <= 78 && food.y > 1 && food.y < 30){int flag = 0;//判断产⽣的⾷物可不可能在蛇的⾝体上for (int i = 1; i <= snake.len; i++){if (snake.coord[i].x == food.x&&snake.coord[i].y == food.y){flag = 1;break;}}if (flag)continue;//绘制⾷物else{gotoxy(food.x, food.y);printf("⊙");food.flag = 0;break;}}}food.flag = 0;}//判断蛇是否吃到⾷物void eatfood(){//只需要判断蛇头是否与⾷物重合if (food.x == snake.coord[1].x&&food.y == snake.coord[1].y){snake.len+=1;food.flag = 1;}}//判断蛇是否死掉void SnakeState(){if (snake.coord[1].x < 2 || snake.coord[1].x>78 || snake.coord[1].y < 1 || snake.coord[1].y>29) snake.flag = 0;for (int i = 2; i <= snake.len; i++){if (snake.coord[1].x == snake.coord[i].x&&snake.coord[1].y == snake.coord[i].y)snake.flag = 0;}}更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
贪吃蛇游戏c语言源代码
outtextxy(160,220,"Game Over");
loop1:key=bioskey(0);
if(key==Enter)
{cleardevice();
TheFirstBlock();
}
else
if(key==ESC)
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);
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);
{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)
void Snake_Bodyadd(void);
c语言课程设计贪吃蛇设计
Part Three
C语言基础知识
数据类型和变量
基本数据类型:int、float、char、double等 复合数据类型:数组、结构体、指针等 变量声明:使用关键字"int"、"float"等声明变量 变量赋值:使用"="为变量赋值 变量作用域:局部变量、全局变量等 变量生命周期:从声明到释放的过程
结构体和联合体:包括结构 体定义、结构体初始化、结 构体访问、联合体定义、联 合体初始化、联合体访问等
函数和数组
函数:C语言中的基本单元,用于实现特定功能
数组:C语言中的基本数据类型,用于存储一组相同类型 的数据
数组函数:如strlen()、strcpy()等,用于操作字符串
指针:C语言中的重要概念,用于指向内存地址
Part Four
贪吃蛇游戏设计
游戏逻辑设计
游戏结束:当蛇碰到边界或 自己时结束
游戏循环:不断更新蛇的位 置和方向
游戏开始:初始化蛇的位置 和方向
得分计算:根据吃到的食物 数量计算得分
游戏难度:根据得分调整游 戏难度,如增加蛇的速度或
改变食物的位置
游戏界面:设计游戏界面, 包括蛇、食物、边界等元素
Part Seven
总结和展望
课程设计收获和体会
掌握了C语言的基本语法和编 程技巧
学会了如何设计并实现一个完 整的游戏项目
提高了解决问题的能力和团队 协作能力
对游戏开发有了更深入的了解 和兴趣
C语言在游戏开发中的应用前景
游戏开发中,C语言具有高效、稳定的特点,适合开发大型游戏。 C语言具有广泛的应用领域,可以开发各种类型的游戏,如动作、冒险、策略等。 C语言具有强大的社区支持,可以找到大量的游戏开发资源和教程。 C语言在游戏开发中具有广泛的应用前景,可以开发出更多优秀的游戏作品。
基于C语言实现的贪吃蛇游戏完整实例代码
基于C语⾔实现的贪吃蛇游戏完整实例代码本⽂以实例的形式讲述了基于C语⾔实现的贪吃蛇游戏代码,这是⼀个⽐较常见的游戏,代码备有⽐较详细的注释,对于读者理解有⼀定的帮助。
贪吃蛇完整实现代码如下:#include <graphics.h>#include <conio.h>#include <stdlib.h>#include <dos.h>#define NULL 0#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#define ESC 283#define ENTER 7181struct snake{int centerx;int centery;int newx;int newy;struct snake *next;};struct snake *head;int grade=60; /*控制速度的*******/int a,b; /* 背静遮的位置*/void *far1,*far2,*far3,*far4; /* 蛇⾝指针背静遮的指针⾍⼦*/int size1,size2,size3,size4; /* **全局变量**/int ch=RIGHT; /**************存按键开始蛇的⽅向为RIGHT***********/int chy=RIGHT;int flag=0; /*********判断是否退出游戏**************/int control=4; /***********判断上次⽅向和下次⽅向不冲突***/int nextshow=1; /*******控制下次蛇⾝是否显⽰***************/int scenterx; /***************随即矩形中⼼坐标***************/int scentery;int sx; /*******在a b 未改变前得到他们的值保证随机矩形也不在此出现*******/int sy;/************************蛇⾝初始化**************************/void snakede(){struct snake *p1,*p2;head=p1=p2=(struct snake *)malloc(sizeof(struct snake));p1->centerx=80;p1->newx=80;p1->centery=58;p1->newy=58;p1=(struct snake *)malloc(sizeof(struct snake));p2->next=p1;p1->centerx=58;p1->newx=58;p1->centery=58;p1->newy=58;p1->next=NULL;}/*******************end*******************/void welcome() /*************游戏开始界⾯ ,可以选择 速度**********/{int key;int size;int x=240;int y=300;int f;void *buf;setfillstyle(SOLID_FILL,BLUE);bar(98,100,112,125);setfillstyle(SOLID_FILL,RED);buf=malloc(size);getimage(98,100,112,125,buf);cleardevice();setfillstyle(SOLID_FILL,BLUE);bar(240,300,390,325);outtextxy(193,310,"speed:");setfillstyle(SOLID_FILL,RED);bar(240,312,390,314);setcolor(YELLOW);outtextxy(240,330,"DOWN");outtextxy(390,330,"UP");outtextxy(240,360,"ENTER to start..." );outtextxy(270,200,"SNAKE");fei(220,220);feiyang(280,220);yang(340,220);putimage(x,y,buf,COPY_PUT);setcolor(RED);rectangle(170,190,410,410);while(1){ if(bioskey(1)) /********8选择速度部分************/key=bioskey(0);switch(key){case ENTER:f=1;break;case DOWN:if(x>=240){ putimage(x-=2,y,buf,COPY_PUT);grade++;key=0;break;}case UP:if(x<=375){ putimage(x+=2,y,buf,COPY_PUT);grade--;key=0;break;}}if (f==1)break;} /********** end ****************/free(buf);}/*************************随即矩形*****************//***********当nextshow 为1的时候才调⽤此函数**********/void ran(){ int nx;int ny;int show; /**********控制是否显⽰***********/int jump=0;struct snake *p;p=head;if(nextshow==1) /***********是否开始随机产⽣***************/while(1){show=1;randomize();nx=random(14);ny=random(14);scenterx=nx*22+58;scentery=ny*22+58;while(p!=NULL){if(scenterx==p->centerx&&scentery==p->centery||scenterx==sx&&scentery==sy)}elsep=p->next;if(jump==1)break;}if(show==1){putimage(scenterx-11,scentery-11,far3,COPY_PUT); nextshow=0;break;}}}/***********过关动画**************/void donghua(){ int i;cleardevice();setbkcolor(BLACK);randomize();while(1){for(i=0;i<=5;i++){putpixel(random(640),random(80),13);putpixel(random(640),random(80)+80,2);putpixel(random(640),random(80)+160,3);putpixel(random(640),random(80)+240,4);putpixel(random(640),random(80)+320,1);putpixel(random(640),random(80)+400,14);}setcolor(YELLOW);settextstyle(0,0,4);outtextxy(130,200,"Wonderful!!");setfillstyle(SOLID_FILL,10);bar(240,398,375,420);feiyang(300,400);fei(250,400);yang(350,400);if(bioskey(1))if(bioskey(0)==ESC){flag=1;break;}}}/*************************end************************//***********************初始化图形系统*********************/ void init(){int a=DETECT,b;int i,j;initgraph(&a,&b,"");}/***************************end****************************//***画⽴体边框效果函数******/void tline(int x1,int y1,int x2,int y2,int white,int black) { setcolor(white);line(x1,y1,x2,y1);line(x1,y1,x1,y2);setcolor(black);line(x2,y1,x2,y2);line(x1,y2,x2,y2);}/****end*********//*************飞洋标志**********/int feiyang(int x,int y){int feiyang[18][18]={ {0,0,0,0,0,0,1,1,1,1,1,1,0,1,1,0,0,0}, {0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,0,0,0},{0,0,0,0,1,1,1,0,0,0,0,0,1,1,1,0,0,0},{0,0,1,1,0,1,1,1,1,1,1,0,0,0,0,0,0,0},{0,0,1,1,1,1,1,0,0,1,0,0,1,1,0,0,0,0},{0,0,1,1,1,0,0,0,0,1,0,1,1,1,0,0,0,0},{0,0,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0},{0,0,1,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0},{0,0,1,1,0,0,0,1,1,0,0,1,1,0,0,1,0,0},{0,0,1,1,1,0,0,1,1,0,0,1,1,0,0,1,0,0},{0,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,0,0},{0,0,0,1,1,1,0,1,1,1,1,1,0,0,1,0,0,0},{0,0,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0},{0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,0,0,0},{0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (feiyang[i][j]==1)putpixel(j+x,i+y,RED);}}/********"飞"字*************/int fei(int x,int y){int fei[18][18]={{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0},{0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0},{0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0},{0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (fei[i][j]==1)putpixel(j+x,i+y,BLUE);}}/*********"洋"字**************/int yang(int x,int y){int yang[18][18]={{0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0}, {1,1,0,0,0,0,1,1,1,0,0,0,1,1,0,0,0,0},{0,1,1,1,0,0,0,1,1,1,0,1,1,0,0,0,0,0},{0,0,1,1,0,0,0,0,0,1,1,1,0,0,0,1,0,0},{0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0},{0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0},{0,0,1,1,0,0,0,1,1,1,1,1,1,1,1,0,0,0},{0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0},{0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,0},{0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},{0,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0},{1,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++)}/******************主场景**********************/int bort(){ int a;setfillstyle(SOLID_FILL,15);bar(49,49,71,71);setfillstyle(SOLID_FILL,BLUE);bar(50,50,70,70);size1=imagesize(49,49,71,71);far1=(void *)malloc(size1);getimage(49,49,71,71,far1);cleardevice();setfillstyle(SOLID_FILL,12);bar(49,49,71,71);size2=imagesize(49,49,71,71);far2=(void *)malloc(size2);getimage(49,49,71,71,far2);setfillstyle(SOLID_FILL,12);bar(49,49,71,71);setfillstyle(SOLID_FILL,GREEN);bar(50,50,70,70);size3=imagesize(49,49,71,71);far3=(void *)malloc(size3);getimage(49,49,71,71,far3);cleardevice(); /*取蛇⾝节点背景节点⾍⼦节点end*/setbkcolor(8);setfillstyle(SOLID_FILL,GREEN);bar(21,23,600,450);tline(21,23,600,450,15,8); /***开始游戏场景边框⽴体效果*******/ tline(23,25,598,448,15,8);tline(45,45,379,379,8,15);tline(43,43,381,381,8,15);tline(390,43,580,430,8,15);tline(392,45,578,428,8,15);tline(412,65,462,85,15,8);tline(410,63,464,87,15,8);tline(410,92,555,390,15,8);tline(412,94,553,388,15,8);tline(431,397,540,420,15,8);tline(429,395,542,422,15,8);tline(46,386,377,428,8,15);tline(44,384,379,430,8,15);setcolor(8);outtextxy(429,109,"press ENTER ");outtextxy(429,129,"---to start"); /*键盘控制说明*/outtextxy(429,169,"press ESC ");outtextxy(429,189,"---to quiet");outtextxy(469,249,"UP");outtextxy(429,289,"LEFT");outtextxy(465,329,"DOWN");outtextxy(509,289,"RIGHT");setcolor(15);outtextxy(425,105,"press ENTER ");outtextxy(425,125,"---to start");outtextxy(425,165,"press ESC ");outtextxy(425,185,"---to quiet");outtextxy(465,245,"UP");outtextxy(425,285,"LEFT");outtextxy(461,325,"DOWN");outtextxy(505,285,"RIGHT"); /*******end*************/setcolor(8);outtextxy(411,52,"score");outtextxy(514,52,"left");setcolor(15);outtextxy(407,48,"score");outtextxy(510,48,"left");size4=imagesize(409,62,465,88); /****分数框放到内存********/far4=(void *)malloc(size4);getimage(409,62,465,88,far4);outtextxy(415,70,"0"); /***************输⼊分数为零**********/outtextxy(512,70,"20"); /*************显⽰还要吃的⾍⼦的数⽬*********/ bar(46,46,378,378);feiyang(475,400);fei(450,400);yang(500,400);outtextxy(58,390,"mailto:************************");outtextxy(58,410,"snake game");outtextxy(200,410,"made by yefeng");while(1){ if(bioskey(1))a=bioskey(0);if(a==ENTER)break;}}/******************gameover()******************/void gameover(){ char *p="GAME OVER";int cha;setcolor(YELLOW);settextstyle(0,0,6);outtextxy(100,200,p);while(1){if(bioskey(1))cha=bioskey(0);if(cha==ESC){flag=1;break;}}}/***********显⽰蛇⾝**********************/void snakepaint(){struct snake *p1;p1=head;putimage(a-11,b-11,far2,COPY_PUT);while(p1!=NULL){putimage(p1->newx-11,p1->newy-11,far1,COPY_PUT);p1=p1->next;}}/****************end**********************//*********************蛇⾝刷新变化游戏关键部分 *******************/void snakechange(){struct snake *p1,*p2,*p3,*p4,*p5;int i,j;static int n=0;static int score;static int left=20;char sscore[5];char sleft[1];p2=p1=head;while(p1!=NULL){ p1=p1->next;if(p1->next==NULL){a=p1->newx;b=p1->newy; /************记录最后节点的坐标************/sx=a;sy=b;}p1->newx=p2->centerx;p1->newy=p2->centery;p2=p1;}p1=head;p1=p1->next;}/********判断按键⽅向*******/if(bioskey(1)){ ch=bioskey(0);if(ch!=RIGHT&&ch!=LEFT&&ch!=UP&&ch!=DOWN&&ch!=ESC) /********chy为上⼀次的⽅向*********/ ch=chy;}switch(ch){case LEFT: if(control!=4){head->newx=head->newx-22;head->centerx=head->newx;control=2;if(head->newx<47)gameover();}else{ head->newx=head->newx+22;head->centerx=head->newx;control=4;if(head->newx>377)gameover();}chy=ch;break;case DOWN:if(control!=1){ head->newy=head->newy+22;head->centery=head->newy;control=3;if(head->newy>377)gameover();}else{ head->newy=head->newy-22;head->centery=head->newy;control=1;if(head->newy<47)gameover();}chy=ch;break;case RIGHT: if(control!=2){ head->newx=head->newx+22;head->centerx=head->newx;control=4;if(head->newx>377)gameover();}else{ head->newx=head->newx-22;head->centerx=head->newx;control=2;if(head->newx<47)gameover();}chy=ch;break;case UP: if(control!=3){ head->newy=head->newy-22;head->centery=head->newy;control=1;if(head->newy<47)gameover();}else{ head->newy=head->newy+22;head->centery=head->newy;control=3;if(head->newy>377)gameover();case ESC:flag=1;break;}/* if 判断是否吃蛇*/if(flag!=1){ if(head->newx==scenterx&&head->newy==scentery){ p3=head;while(p3!=NULL){ p4=p3;p3=p3->next;}p3=(struct snake *)malloc(sizeof(struct snake));p4->next=p3;p3->centerx=a;p3->newx=a;p3->centery=b;p3->newy=b;p3->next=NULL;a=500;b=500;putimage(409,62,far4,COPY_PUT); /********** 分数框挡住**************/putimage(500,62,far4,COPY_PUT); /*********把以前的剩下⾍⼦的框挡住********/ score=(++n)*100;left--;itoa(score,sscore,10);itoa(left,sleft,10);setcolor(RED);outtextxy(415,70,sscore);outtextxy(512,70,sleft);nextshow=1;if(left==0) /************判断是否过关**********/donghua(); /*******如果过关,播放过关动画*********************/}p5=head; /*********************判断是否⾃杀***************************/p5=p5->next;p5=p5->next;p5=p5->next;p5=p5->next; /****从第五个节点判断是否⾃杀************/while(p5!=NULL){if(head->newx==p5->centerx&&head->newy==p5->centery){ gameover();break;}elsep5=p5->next;}}}/************snakechange()函数结束*******************//*****************************主函数******************************************/int main(){ int i;init(); /**********初始化图形系统**********/welcome(); /*********8欢迎界⾯**************/bort(); /*********主场景***************/snakede(); /**********连表初始化**********/while(1){ snakechange();if(flag==1)break;snakepaint();ran();for(i=0;i<=grade;i++)delay(3000);free(far3);free(far4);closegraph(); return 0;}。
c++ 代码小游戏(贪吃蛇)
{
if(p->x==x&&p->y==y)
{
flag=1;
break;
}
else
p=p->next;
}
return flag;
}
class CFood
{
public:
void GetFood(CSnake &snake);
m.Moving(snake);
f.point[snake.tail->x][snake.tail->y]='+';
f.OutFrame();
Sleep(250);
}
}
}
void main()
{
char c;
cout<<"游戏规则:W:上 S:下 A:左 D: 右; 或者用键盘的↑↓←→键控制"<<endl;
cout<<"是否开始游戏 是:Y 否:N"<<endl;
cin>>&c;
if(c!='y'&&c!='Y')
{
cout<<"退出游戏!"<<endl;
exit(0);
}
else
{
system("cls");
run();
}
}
{
srand((unsigned int) time(NULL));
food_x=rand()%(LINE-2)+1;
C语言实现双人贪吃蛇游戏实例代码
C语⾔实现双⼈贪吃蛇游戏实例代码贪吃蛇双⼈⼩游戏,每局游戏两分钟,死亡则直接失败,若时间结束,则分⾼者获胜。
上源代码:1234567891011121314151617181920212223242526272829303132 33 34 35#include <stdio.h>#include <stdlib.h>#include <Windows.h> #include <time.h>#include<stdbool.h>35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99#include<stdbool.h>#include <conio.h>#define SNAKESIZE 100#define MAPWIDTH 118#define MAPHEIGHT 29struct{ //保存⾷物坐标int x;int y;}food;struct{int len;int x[SNAKESIZE];int y[SNAKESIZE];}snake;struct{int len;int x[SNAKESIZE];int y[SNAKESIZE];}snake1;char key = '8';//初始⽅向向上char key1 = 'w';int changeFlag = 0 , changeFlag1 = 0;int speed=150 , sorce = 0 , sorce1 = 0 , sec=0 , min=2;void gotoxy(int x, int y)//移动光标到指定位置{COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }void MAP()//打印边框和两条蛇的起始位置{for(int i = 0; i <= MAPWIDTH; i += 2)//打印最上⾯和最下⾯两横边框{gotoxy(i, 0);printf("■");gotoxy(i, MAPHEIGHT);printf("■");}for(int i = 1; i < MAPHEIGHT; i++)//打印最左⾯和最右⾯{gotoxy(0, i);printf("■");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 = snake1.len = 4;//给两条蛇的长度赋初值snake.x[0] = MAPWIDTH / 2 + 31;//然后分别打印两条蛇⾝部分snake.y[0] = MAPHEIGHT / 2;snake1.x[0] = MAPWIDTH / 2 -31;snake1.y[0] = MAPHEIGHT / 2;gotoxy(snake.x[0], snake.y[0]);99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 gotoxy(snake.x[0], snake.y[0]);printf("■");gotoxy(snake1.x[0], snake1.y[0]);printf("●");for(int i = 1; i < snake.len; i++){snake.x[i] = snake.x[i - 1];snake.y[i] = snake.y[i - 1]+1;gotoxy(snake.x[i], snake.y[i]);printf("■");snake1.x[i] = snake1.x[i - 1];snake1.y[i] = snake1.y[i - 1]+1;gotoxy(snake1.x[i], snake1.y[i]);printf("●");}gotoxy(MAPWIDTH , 0);//把光标移⾛return;}void OPERATION()//操作函数{char pre_key = key , pre_key1 = key1 , s;//保存两条蛇上⼀次的⽅向if(_kbhit()){s = getch();if(s=='w'||s=='s'||s=='a'||s=='d'||s=='W'||s=='S'||s=='A'||s=='D')key1=s;else if(s=='8'||s=='5'||s=='4'||s=='6')key=s;}if(changeFlag == 0)//没吃到⾷物{gotoxy(snake.x[snake.len - 1], snake.y[snake.len - 1]);printf(" ");//在蛇尾处输出空格即擦去蛇尾}if(changeFlag1 == 0){gotoxy(snake1.x[snake1.len - 1], snake1.y[snake1.len - 1]);printf(" ");//在蛇尾处输出空格即擦去蛇尾}//将蛇的每⼀节依次向前移动⼀节(蛇头除外)for(int i = snake.len - 1; i > 0; i--){snake.x[i] = snake.x[i - 1];snake.y[i] = snake.y[i - 1];}for(int i = snake1.len - 1; i > 0; i--){snake1.x[i] = snake1.x[i - 1];snake1.y[i] = snake1.y[i - 1];}//蛇当前移动的⽅向不能和前⼀次的⽅向相反,⽐如蛇往左⾛的时候不能直接按右键往右⾛ //如果当前移动⽅向和前⼀次⽅向相反的话,把当前移动的⽅向改为前⼀次的⽅向if(pre_key == '8'&& key == '5')key = '8';if(pre_key == '5'&& key == '8')key = '5';if(pre_key == '4'&& key == '6')key = '4';if(pre_key == '6'&& key == '4')key = '6';if(pre_key1 == 'w'&& key1 == 's')key1 = 'w';if(pre_key1 == 's'&& key1 == 'w')key1 = 's';if(pre_key1 == 'a'&& key1 == 'd')key1 = 'a';if(pre_key1 == 'd'&& key1 == 'a')key1 = 'd';163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 key1 = 'd';//判断蛇头应该往哪个⽅向移动switch(key){case'4':snake.x[0] -= 2;//往左break;case'6':snake.x[0] += 2;//往右break;case'8':snake.y[0]--;//往上break;case'5':snake.y[0]++;//往下break;}gotoxy(snake.x[0], snake.y[0]);printf("■");changeFlag = 0;switch(key1){case'a':case'A':snake1.x[0] -= 2;//往左break;case'd':case'D':snake1.x[0] += 2;//往右break;case'w':case'W':snake1.y[0]--;//往上break;case's':case'S':snake1.y[0]++;//往下break;}gotoxy(snake1.x[0], snake1.y[0]);printf("●");changeFlag1 = 0;gotoxy(MAPWIDTH, 0);return;}void createFood(){if(snake.x[0] == food.x && snake.y[0] == food.y)//蛇头碰到⾷物{//蛇头碰到⾷物即为要吃掉这个⾷物了,因此需要再次⽣成⼀个⾷物 while(1){int a = 1 , b=1;srand((unsigned int)time(NULL));food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;//随机⽣成的⾷物不能在蛇的⾝体上for(int i = 0; i < snake.len; i++){if(snake.x[i] == food.x && snake.y[i] == food.y){a = 0;break;}}for(int i = 0; i < snake1.len; i++){if(snake1.x[i] == food.x && snake1.y[i] == food.y){b = 0;break;}226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 }//随机⽣成的⾷物不能横坐标为奇数,也不能在蛇⾝,否则重新⽣成if(a==1&&b==1 && food.x % 2 == 0)break;}//绘制⾷物gotoxy(food.x, food.y);printf("★");snake.len++;//吃到⾷物,蛇⾝长度加1sorce += 10;speed -= 5;//随着吃的⾷物越来越多,速度会越来越快changeFlag = 1;//很重要,因为吃到了⾷物,就不⽤再擦除蛇尾的那⼀节,以此来造成蛇⾝体增长的效果 }return;}void createFood1(){if(snake1.x[0] == food.x && snake1.y[0] == food.y)//蛇头碰到⾷物{//蛇头碰到⾷物即为要吃掉这个⾷物了,因此需要再次⽣成⼀个⾷物while(1){int a = 1 , b=1;srand((unsigned int)time(NULL));food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;//随机⽣成的⾷物不能在蛇的⾝体上for(int i = 0; i < snake.len; i++){if(snake.x[i] == food.x && snake.y[i] == food.y){a = 0;break;}}for(int i = 0; i < snake1.len; i++){if(snake1.x[i] == food.x && snake1.y[i] == food.y){b = 0;break;}}//随机⽣成的⾷物不能横坐标为奇数,也不能在蛇⾝,否则重新⽣成if(a==1&&b==1&& food.x % 2 == 0)break;}//绘制⾷物gotoxy(food.x, food.y);printf("★");snake1.len++;//吃到⾷物,蛇⾝长度加1sorce1 += 10;speed -= 5;//随着吃的⾷物越来越多,速度会越来越快changeFlag1 = 1;//很重要,因为吃到了⾷物,就不⽤再擦除蛇尾的那⼀节,以此来造成蛇⾝体增长的效果 }return;}bool check(){//蛇头碰到上下边界,游戏结束if(snake.y[0] == 0 || snake.y[0] == MAPHEIGHT)return true;//蛇头碰到左右边界,游戏结束if(snake.x[0] == 0 || snake.x[0] == MAPWIDTH)return true;//蛇头碰到蛇⾝,游戏结束for(int i = 1; i < snake.len; i++){290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 {if(snake.x[i] == snake.x[0] && snake.y[i] == snake.y[0])return true;}for(int i = 0; i < snake1.len; i++){if(snake1.x[i] == snake.x[0]&&snake1.y[i] == snake.y[0])return true;}return false;}bool check1(){//蛇头碰到上下边界,游戏结束if(snake1.y[0] == 0 || snake1.y[0] == MAPHEIGHT)return true;//蛇头碰到左右边界,游戏结束if(snake1.x[0] == 0 || snake1.x[0] == MAPWIDTH)return true;//蛇头碰到蛇⾝,游戏结束for(int i = 1; i < snake1.len; i++){if(snake1.x[i] == snake1.x[0] && snake1.y[i] == snake1.y[0])return true;}for(int i = 0; i < snake.len; i++){if(snake.x[i] == snake1.x[0] && snake.y[i] == snake1.y[0])return true;}return false;}void MENU ()//打印菜单界⾯{printf("\n\n\n\n\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 ║开始:┃ 1┃规则:┃ 2┃退出:┃ 3┃║\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");switch(getch()){case'1':system("cls");START();break;case'2':system("cls");RULE();MENU();break;case'3':exit(0);break;default:system("cls");printf("error");MENU();}}void RULE (){system("cls");//清屏printf("\t╔══════════════════════════════════════════════════════════════════════════════════════════════════╗\n"); printf("\t║本游戏玩家⼀(左侧)通过按键W、S、A、D(不区分⼤⼩写)四个键分别控制snake1上移、下移、左移和右移。
C课程设计贪吃蛇小游戏内附完整源码及附件.doc
温馨提示程序语言:C、C++、C#、Python(红色字体表示本课设使用的程序设计语言)图形功能选项:Win32控制台程序(黑框、文本界面)、Win32程序、MFC、WinForm、DirectX10(黑体标明表示本课设的程序图形类别,默认为非图形界面Win32控制台程序)数据结构:基础类型、数组、链表、双向链表、搜索树(非平衡二叉树)、平衡二叉树、链表与平衡二叉树相结合、堆栈、队列、串、图(黑体标明表示本课设使用的数据结构)C++语言项:STL库(黑体标明表示使用C++的STL库)编译环境:Windows 7 64位旗舰版(Linux及其他环境请谨慎下载)集成开发环境:Visual C++ 6.0、DEVC++、CodeBlocks、Visual Studio 2015均可通过编译。
(浅蓝色字体表示需要运行修改后的版本,请用户自行选择源代码测试)分多头文件编译:否(所有代码基本都包含在一个文件内,如需试验头文件功能,请自行参考相关文献)内容说明:1、课设题目及预览内容将在第二页开始展示。
2、代码行数:259行3、目录所示内容,本文基本涵盖,如无内容,会在本页进行说明。
4、附录绝对包含用户使用手册及程序完整源代码和详细注释。
5、如需下载其他头文件(例如DirectX需另行配置),本文会在此进行说明。
6、本文撰写内容仅供学习参考,另外,由于本人水平有限,编写之处难免存在错误和纰漏,恳请各位老师或同学批评指正。
上机报告程序实践名称:________________________________学生姓名:________________________________专业:________________________________班级:________________________________学号:________________________________指导教师:________________________________上机成绩:________________________________上机地点:________________________________上机时间:____________年_______月_______日一、上机目的与上机要求(可以有多个目标及要求,对应多个上机内容)1、上机目的(具体的目的,类似于“提出问题”)将理论用于实践,更充分的掌握课本的知识,巩固并加深对课本知识的理解,进一步提高我们的动手编程能力。
贪吃蛇游戏代码(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++)< p="">{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) ) ) ){}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) ) {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*1 5+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();}</max;i++)<>。
贪吃蛇 cpp
文件名
内容
-----------------------
SnakeTest.cpp
#include "Snake.h"
int main(){
Snake sk;
bool isDead = false;
while (!isDead){
isDead = sk.update();
}
return 0;
}
void Snake::test(){
cout << "errr!" << endl;
}
void Snake::show(){
for (int i = 0; i < MAP_H; ++i){
for (int j = 0; j < MAP_W; ++j){
Snake.h
// 贪吃蛇内容
#include <iostream>
#include <vector>
#include <queue>
#include "MyPoint.h"
using namespace std;
const int MAP_W = 60;
const int MAP_H = 22;
setX(px);
setY(py);
}
/*MyPoint(MyPoint & mp){
setX(mp.getX());
setY(mp.getY());
}*/
~MyPoint(){}
void setX(int px){
经典游戏贪吃蛇代码(c++编写)
经典游戏贪吃蛇代码(c++编写)/* 头文件 */#include#includeusing namespace std;#ifndef SNAKE_H#define SNAKE_Hclass Cmp{friend class Csnake;int rSign; //横坐标int lSign; //竖坐标public://friend bool isDead(const Cmp& cmp); Cmp(int r,int l){setPoint(r,l);}Cmp(){}void setPoint(int r,int l){rSign=r;lSign=l;}Cmp operator-(const Cmp &m)const{return Cmp(rSign - m.rSign,lSign - m.lSign);}Cmp operator+(const Cmp &m)const{return Cmp(rSign + m.rSign,lSign + m.lSign);}};const int maxSize = 5; //初始蛇身长度class Csnake{Cmp firstSign; //蛇头坐标Cmp secondSign;//蛇颈坐标Cmp lastSign; //蛇尾坐标Cmp nextSign; //预备蛇头int row; //列数int line; //行数int count; //蛇身长度vector<vector > snakeMap;//整个游戏界面queue snakeBody; //蛇身public:int GetDirections()const;char getSymbol(const Cmp& c)const //获取指定坐标点上的字符{return snakeMap[c.lSign][c.rSign];}Csnake(int n) //初始化游戏界面大小{if(n<20)line=20+2;else if(n>30)line = 30 + 2;else line=n+2;row=line*3+2;}bool isDead(const Cmp& cmp){return ( getSymbol(cmp)=='c' || cmp.rSign == row-1 || cmp.rSign== 0 || cmp.lSign == line-1 || cmp.lSign == 0 );}void InitInstance(); //初始化游戏界面bool UpdataGame(); //更新游戏界面void ShowGame(); //显示游戏界面};#endif // SNAKE_H====================================== ==============================/* 类的实现及应用*/#include#include#include#include "snake.h"using namespace std;//测试成功void Csnake::InitInstance(){snakeMap.resize(line); // snakeMap[竖坐标][横坐标]for(int i=0;i{snakeMap[i].resize(row);for(int j=0;j{snakeMap[i][j]=' ';}}for(int m=1;m{//初始蛇身snakeMap[line/2][m]='c';//将蛇身坐标压入队列snakeBody.push(Cmp(m,(line/2)));//snakeBody[横坐标][竖坐标]}//链表头尾firstSign=snakeBody.back();secondSign.setPoint(maxSize-1,line/2);}//测试成功int Csnake::GetDirections()const{if(GetKeyState(VK_UP)<0) return 1; //1表示按下上键if(GetKeyState(VK_DOWN)<0) return 2; //2表示按下下键if(GetKeyState(VK_LEFT)<0) return 3; //3表示按下左键if(GetKeyState(VK_RIGHT)<0)return 4; //4表示按下右键return 0;}bool Csnake::UpdataGame(){//-----------------------------------------------//初始化得分0static int score=0;//获取用户按键信息int choice;choice=GetDirections();cout<<"Total score: "<<score</</score<</vector/随机产生食物所在坐标int r,l;//开始初始已经吃食,产生一个食物static bool eatFood=true;//如果吃了一个,才再出现第2个食物if(eatFood){do{//坐标范围限制在(1,1)到(line-2,row-2)对点矩型之间srand(time(0));r=(rand()%(row-2))+1; //横坐标l=(rand()%(line-2))+1;//竖坐标//如果随机产生的坐标不是蛇身,则可行//否则重新产生坐标if(snakeMap[l][r]!='c'){snakeMap[l][r]='*';}}while (snakeMap[l][r]=='c');}switch (choice){case 1://向上//如果蛇头和社颈的横坐标不相同,执行下面操作if(firstSign.rSign!=secondSign.rSign)nextSign.setPoint(firstSi gn.rSign,firstSign.lSign-1);//否则,如下在原本方向上继续移动else nextSign=firstSign+(firstSign-secondSign); break;case 2://向下if(firstSign.rSign!=secondSign.rSign)nextSign.setPoint(firstSi gn.rSign,firstSign.lSign+1);else nextSign=firstSign+(firstSign-secondSign); break;case 3://向左if(firstSign.lSign!=secondSign.lSign)nextSign.setPoint(firstSi gn.rSign-1,firstSign.lSign);else nextSign=firstSign+(firstSign-secondSign);break;case 4://向右if(firstSign.lSign!=secondSign.lSign)nextSign.setPoint(firstSi gn.rSign+1,firstSign.lSign);else nextSign=firstSign+(firstSign-secondSign);break;default:nextSign=firstSign+(firstSign-secondSign);}//----------------------------------------------------------if(getSymbol(nextSign)!='*' && !isDead(nextSign)) //如果没有碰到食物(且没有死亡的情况下),删除蛇尾,压入新的蛇头{//删除蛇尾lastSign=snakeBody.front();snakeMap[lastSign.lSign][lastSign.rSign]=' ';snakeBody.pop();//更新蛇头secondSign=firstSign;//压入蛇头snakeBody.push(nextSign);firstSign=snakeBody.back();snakeMap[firstSign.lSign][firstSign.rSign]='c';//没有吃食eatFood=false;return true;}//-----吃食-----else if(getSymbol(nextSign)=='*' && !isDead(nextSign)){secondSign=firstSign;snakeMap[nextSign.lSign][nextSign.rSign]='c';//只压入蛇头snakeBody.push(nextSign);firstSign=snakeBody.back();eatFood=true;//加分score+=20;return true;}//-----死亡-----else {cout<<"Dead"<<endl;cout<<"your "<<score<}void Csnake::ShowGame(){for(int i=0;i{for(int j=0;jcout<cout<}Sleep(1);system("cls");}======================================================================/*主函数部分 */#include#include "snake.h"#includeusing namespace std;int main(){Csnake s(20);s.InitInstance();//s.ShowGame();int noDead;do{s.ShowGame();noDead=s.UpdataGame();}while (noDead</endl;cout<<"your>);system("pause");return 0;}。
C++实现简单贪吃蛇游戏
C++实现简单贪吃蛇游戏我⼤概在⼀个多⽉前把⾃⼰上学期写的c代码的贪吃蛇游戏push到csdn上,并且说c风格的贪吃蛇写起来有些⿇烦(),准备⽤⾯向对象的c++再写⼀遍。
现在我们专业恰好刚教完了c++,学校也布置了⼀道简单的贪吃蛇的编程题⽬,实现下来,的确觉得c++的思路清晰很多,所以再次把c++的代码push上来,供⼤家对⽐参考:)直接上代码,c++把整个游戏拆分成⼏个⽂件,分开上,有⼀定的c++基础的同学应该可以很容易看懂。
1、全局头⽂件(global.hpp)#ifndef _GLOBAL_H_#define _GLOBAL_H_#ifndef SYMBOLS#define HEAD '@'#define BODY 'X'#define EMPTY '+'#define FOOD '$'#endif // !SYMBOLSenum direction { up = 0, down = 1, left = 2, right = 4, freeze = 5 };struct point {int x;int y;point(int x = 0, int y = 0) : x(x), y(y) {}point(const point& another) : x(another.x), y(another.y) {}point& operator=(const point& other) {x = other.x;y = other.y;return *this;}friend bool operator==(const point& point1, const point& point2) {return point1.x == point2.x && point1.y == point2.y;}point& move(direction d) {switch (d) {case up:x--;break;case down:x++;break;case left:y--;break;case right:y++;break;case freeze:default:break;}return *this;}};#endif // !_GLOBAL_H_2、snake类的声明和实现(snake.hpp)(为了简化结构,把声明和实现共同放在了hpp⽂件⾥,减少了⼀点封装性,实际上应该分开头⽂件和实现⽂件好⼀点)此处使⽤了容器list作为蛇⾝(body)的表达形式,这样可以⾮常⽅便地进⾏表达,读者有兴趣可以⽤数组实现⼀下,⼀不⼩⼼就会出现有趣的内存错误。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
unsigned char Bit_Self(SNAKE *s);
void Debug(void);
/*
***主函数
*/
unsigned char main()
{
Game_Init();
Game_Control();
{
unsigned int x, y;
struct snake *next;
}SNAKE;
/*
***全局变量
*/
unsigned int Score = 0;
unsigned int Direction, Time_sleep = 250;
q->next = tail; //上一节点的next指向tail
q = q->next;//or q = tail //q移动指向tail q充当指挥者
}
q->next = NULL;
q = head;//q 指向头
#define UP 1
#define DOWN 2
#define LEFT 3
#define RIGHT 4
/*
***结构体
*/
typedef struct snake//蛇身的一个节点
{
SNAKE *tail;
unsigned int i = 0;
head = (SNAKE *)malloc(sizeof(SNAKE));
head->x = 12*2;
head->y = 12;
head->next = NULL;
food_1->y = rand()%(MAP_HEIGHT -1)+1;
q = head;
}
else
{
q = q->next;
}
}
return 0;
}
/****************************************************************
void Wall_Cross(SNAKE *s)
{
if (s->x == 0 || s->x == MAP_WIDTH*2 || s->y == 0 || s->y== MAP_HEIGHT )
{
Game_status = 1;
* Function Name: Wall_Cross
* Description : 判断是否撞墙
* Parameter : SNAKE *s
* Return : void
***************************************************************/
/****************************************************************
* Function Name: Food_Create()
* Description : 创造食物
* Parameter : void
* Return : void
* Parameter : void
* Retuபைடு நூலகம்n : void
***************************************************************/
void Map_Create(void)
#include <Windows.h>//包含WinCon.h
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
/*
***宏定义
*/
#define MAP_WIDTH 20
#define MAP_HEIGHT 20
q = head;
for (i = 0;i <=0; i++)
{
tail = (SNAKE *)malloc(sizeof(SNAKE));
tail->x = 12*2+2*i;
tail->y = 12;
* Parameter : SNAKE *s
* Return : 0 没有咬到自己
: 1 咬到自己
***************************************************************/
unsigned char Bit_Self(SNAKE *s)
SetConsoleCursorPosition(houtput,pos);
}
/****************************************************************
* Function Name: Map_Create
* Description : 创建地图
food_1 =(SNAKE *)malloc(sizeof(SNAKE));
food_1->x = 2*(rand()%(MAP_WIDTH - 1)+1);
food_1->y = rand()%(MAP_HEIGHT -1)+1;
q = head;
void Map_Create(void);
void Snake_Init(void);
void Pause(void);
void Game_Control(void);
void Game_Init(void);
void Game_End(void);
void Wall_Cross(SNAKE *s);
* Parameter : unsigned int x, unsigned int y
* Return : void
***************************************************************/
void Pos_Set(unsigned int x, unsigned int y)
{
COORD pos;
HANDLE houtput;
pos.X = x;
pos.Y = y;
houtput = GetStdHandle(STD_OUTPUT_HANDLE);
while(q != NULL)
{
Pos_Set(q->x, q->y);
if(q == head)printf("X");
else printf("o");
q = q->next;
}
}
printf("■");
}
}
/****************************************************************
* Function Name: Snake_Init()
* Description : 蛇的初始化
while(q != NULL)
{
if (q->x == food_1->x && q->y == food_1->y)
{
food_1->x = 2*(rand()%(MAP_WIDTH - 1)+1);
Game_End();
}
}
/****************************************************************
* Function Name: Bit_Self
* Description : 判断蛇是否要到自己
//Game_End();
return 0;
}
/****************************************************************
* Function Name: Pos_Set
* Description : 设置光标位置
***************************************************************/
void Food_Create(void)
{
SNAKE *food_1;
srand((unsigned )time(NULL));
* Parameter : void
* Return : void
***************************************************************/
void Snake_Init(void)
SNAKE *head, *food;//蛇头指针, 食物指针
SNAKE *q;//遍历和判断蛇的时候用到的指针
unsigned char Game_status = 0;// 游戏结束的情况:1:撞到墙;2:咬到自己;3:主动退出游戏。
/*
***函数声明
*/
void Pos_Set(unsigned int x, unsigned int y);
{
q = head;
while (q != NULL)
{
if ((q->x == s->x) && (q->y == s->y))