c语言贪吃蛇UI界面版
C语言实现贪吃蛇游戏
C语言实现贪吃蛇游戏.txt每天早上起床都要看一遍“福布斯”富翁排行榜,如果上面没有我的名字,我就去上班。
谈钱不伤感情,谈感情最他妈伤钱。
我诅咒你一辈子买方便面没有调料包。
/*===========================================================*程序名:贪吃蛇/*===========================================================*调用库:*----------------------*图形库graphics.h,随机库stdlib.h*===========================================================*/#include <graphics.h>#include <stdlib.h>/*===========================================================*宏定义:*----------------------*上、下、左、右、退出(ESC),暂停(PAUSE),确定(ENTER)*alive---蛇活着,dead---蛇死亡*no---食物不存在,yes---食物存在*N---蛇最大长度,达到200时游戏完成*===========================================================*/#define LEFT 0x4b00#define RIGHT 0x4d00#define DOWN 0x5000#define UP 0x4800#define ESC 0x011b#define SPACE 0x3920#define ENTER 0x1c0d#define alive 1#define dead 0#define yes 1#define no 0#define N 200/*===========================================================*自定义函数以及全局变量声明*---------------------------*Score---统计吃的食物个数;Speed_degree:控制蛇速度变量*===========================================================*/void make_full_screen();void start_screen();void menu();void wall_note();void play_game();void score();void game_over();void close_full_screen();void victory();void forum();void leave_or_again();void victory();int Score,Speed_degree;/*=========================================================== *自定义函数:make_full_screen()*---------------------------------*初始化图形界面*===========================================================*/ void make_full_screen(){int driver=DETECT,mode;registerbgidriver(EGAVGA_driver);initgraph(&driver,&mode,"");cleardevice();}/*=========================================================== *自定义函数:start_screen()*------------------------------*贪吃蛇游戏的欢迎界面*===========================================================*/ void start_screen(){int i,p,color=9;settextstyle(0,0,2);setcolor(GREEN);outtextxy(150,400,"Press any key to loading...");setcolor(YELLOW);outtextxy(200,450,"Deviser:caolvchong");forum();while(bioskey(1)==0) /*当没有按键时显示snake*/{settextstyle(0,0,6);for(i=9;i<15;i++){color++;if(color>=14) color=9;setcolor(color);outtextxy(200,200,"SNAKE");for(p=1;p<3;p++)delay(50000);}}bioskey(0);/*返回键盘值,不然按下的扫描码将被后面检测按键函数接收*/ cleardevice();/*清屏*/}/*===========================================================*自定义函数:menu()*------------------------------*贪吃蛇游戏的菜单界面*===========================================================*/void menu(){int j=100,k=j,n,key,tag=1;char *char_up=NULL,*char_down=NULL;/*----------------------------------------------*参数说明:*j:作为显示选择条(bar)的位置参数*k: 作为清除选择条的位置参数*key:接收按键参数*tag:跳出menu()函数的标签,触发条件按下enter**char_up,*char_down接收ASCII码的24(↑)和25(↓)*----------------------------------------------*/setcolor(RED);settextstyle(0,0,2);outtextxy(15,15,"choose a level");setcolor(LIGHTBLUE);settextstyle(0,0,3);outtextxy(15,100,"Easy");outtextxy(15,150,"Normal");outtextxy(15,200,"Hard");setcolor(GREEN);settextstyle(0,0,2);sprintf(char_up,"%c",24);outtextxy(150,350,char_up);sprintf(char_down,"%c",25);outtextxy(210,350,char_down);outtextxy(170,350,"or ");outtextxy(230,350,"to select");outtextxy(150,380,"ENTER to play");outtextxy(150,410,"ESC to exit");setfillstyle(2,YELLOW);bar(190,j,215,j+25);forum();while(tag!=0){setfillstyle(1,BLACK);bar(190,k,215,k+25);setfillstyle(2,YELLOW);bar(190,j,215,j+25);key=bioskey(0);switch(key){case DOWN: k=j;if(j<200) j+=50;break;case UP: k=j;if(j>100) j-=50;break;case ENTER: tag=0;break;case ESC: close_full_screen(); /*退出*/}switch(j){case 100:Speed_degree=12;break;case 150:Speed_degree=8;break;case 200:Speed_degree=4;break; /*对应各等级的速度延迟循环次数*/ }}}/*===========================================================*自定义函数:wall_note()*------------------------------*贪吃蛇游戏的围墙,就是蛇的活动范围*以及游戏中提示按键:ESC--退出;SPACE--暂停*===========================================================*/void wall_note(){cleardevice();setlinestyle(0,0,3);setcolor(LIGHTRED);rectangle(47,57,603,453);setfillstyle(1,LIGHTGREEN);bar(55,10,600,40);settextstyle(0,0,3);setcolor(RED);outtextxy(58,15,"ESC:exit");outtextxy(305,15,"SPACE:pause");forum();}/*=========================================================== *自定义函数:play_game()*------------------------------*具体的游戏过程*===========================================================*/ void play_game(){struct{int x[N];int y[N];int block;int life;int direction;}snake;struct{int x;int y;int exist;}food;int i,key;/*---------------------------------*参数说明:*结构体snake.[x],snake.[y]为蛇身体坐标*snake.block蛇的节数;snake.life蛇生命参数*snake.direction蛇的运动方向*--------------*结构体food.x,food.y为食物坐标*food.exist食物存在参数*-------------*i:一些循环控制参量*key:接收键盘按键参量*----------------------------------*/randomize();/*初始化随机库*/snake.x[0]=100;snake.y[0]=100;snake.direction=RIGHT;snake.life=alive;snake.block=3;food.exist=no;score();/*初始分数*//*-----------------------------------*初始化:*蛇的头部位置,运动方向向右,生命活着*节数为3,食物开始不存在,初始化分数显示为0*-----------------------------------*/for(;;)/* 循环,作用于下面while(!kbhit),按键后重新开始* while(!hkbit)循环,并对按键分析,实现上下左右*以及退出暂停的检测*/{while(!kbhit())/*没有按键时,实现对食物是否存在的判断,对于不存*在时产生食物,并画出;*对蛇移动的处理:自动向前移动,对接收来的上下左*右的处理,对蛇运动过程是否导致死亡判断,对蛇身*体变长以及画出蛇的处理*对分数的处理:显示分数,对是否完全200个进行判断*/{if(food.exist==no)/*没有食物时,随机出现食物*/{food.x=random(531)+60;food.y=random(381)+60;/*随机出现食物,确保食物在蛇的活动范围内*/while(food.x%10!=0) food.x++;while(food.y%10!=0) food.y++;/*确保食物在屏幕坐标10的正数倍,这样才能被蛇吃到*/ food.exist=yes;/*食物存在了*/for(i=0;i<snake.block;i++)if(food.x==snake.x&&food.y==snake.y){food.exist=no;break;}/*如果食物在蛇的身体内,重新产生食物*/}setlinestyle(0,0,1);setcolor(RED);rectangle(food.x,food.y,food.x+10,food.y+10);/*画出食物*/for(i=snake.block-1;i>0;i--){snake.x=snake.x[i-1];snake.y=snake.y[i-1];}/*蛇身体后面一格变前面一格,实现蛇移动的原理*/switch(snake.direction){case RIGHT: snake.x[0]+=10;break;case LEFT: snake.x[0]-=10;break;case UP: snake.y[0]-=10;break;case DOWN: snake.y[0]+=10;break;}/*蛇上下左右移动的处理*/for(i=4;i<snake.block;i++)if(snake.x==snake.x[0]&&snake.y==snake.y[0]){snake.life=dead;break;}/*对蛇是否碰到自己的判断,碰到自己,蛇死*/if(snake.x[0]<48||snake.x[0]>597||snake.y[0]<53||snake.y[0]>447) snake.life=dead; /*碰到墙,蛇死*/if(snake.life==dead){game_over();break;}/*如果蛇死的话,显示游戏结束,退出while(!hkbit())循环*/if(food.x==snake.x[0]&&food.y==snake.y[0])/*食物被吃*/{setcolor(BLACK);rectangle(food.x,food.y,food.x+10,food.y+10);/*把食物去掉*/ snake.block++;/*蛇身增加*/Score++; /*分数增加*/score();/*统计显示分数*/victory();/*吃到食物200个显示完成游戏*/food.exist=no;/*食物被吃,食物就不存在了*/}setcolor(LIGHTBLUE);for(i=1;i<snake.block;i++){setlinestyle(0,0,1);rectangle(snake.x,snake.y,snake.x+10,snake.y+10);}/*画蛇*/setcolor(YELLOW);rectangle(snake.x[0],snake.y[0],snake.x[0]+10,snake.y[0]+10);/*设置蛇的头部*/snake.x[snake.block]=-100;snake.y[snake.block]=-100;for(i=0;i<Speed_degree;i++)delay(10000);setcolor(BLACK);rectangle(snake.x[snake.block-1],snake.y[snake.block-1],snake.x[snake.block-1]+10,snake.y[snake.block-1]+10);/*去掉蛇的最后一节*/}key=bioskey(0);/*等待按键*/if(key==SPACE) bioskey(0);/*暂停*/else if(key==ESC) closegraph();/*结束游戏*/else if(key==RIGHT&&snake.direction!=LEFT) snake.direction=RIGHT; else if(key==UP&&snake.direction!=DOWN) snake.direction=UP;else if(key==LEFT&&snake.direction!=RIGHT) snake.direction=LEFT; else if(key==DOWN&&snake.direction!=UP) snake.direction=DOWN; if(snake.life==dead) break;}}/*===========================================================*自定义函数:score()*------------------------------*统计显示分数*===========================================================*/void score(){char *str=NULL;setfillstyle(0,BLACK);bar(250,460,405,490);setcolor(LIGHTGREEN);settextstyle(0,0,2);sprintf(str,"Score:%d",Score);outtextxy(255,460,str);}/*=========================================================== *自定义函数:victory()*------------------------------*吃到食物200个,完成游戏*===========================================================*/ void victory(){if(Score==200){cleardevice();setcolor(YELLOW);settextstyle(0,0,6);outtextxy(100,200,"Victory!");forum();leave_or_again();}}/*=========================================================== *自定义函数:game_over()*------------------------------*显示游戏结束,选择继续游戏还是离开*===========================================================*/ void game_over(){cleardevice();score();setcolor(RED);settextstyle(0,0,6);outtextxy(100,200,"Game Over");forum();leave_or_again();}/*=========================================================== *自定义函数:leave_or_again()*------------------------------*离开还是重新游戏选择*至于菜单条的设计与前面menu()类似*===========================================================*/void leave_or_again(){int j=300,k,key,tag=1;while(tag!=0){setcolor(BLUE);settextstyle(0,0,3);outtextxy(150,300,"Leave");outtextxy(150,350,"Again");setfillstyle(1,BLACK);bar(330,k,355,k+25);setfillstyle(2,YELLOW);bar(330,j,355,j+25);key=bioskey(0);switch(key){case DOWN: k=j;if(j<350) j+=50;break;case UP: k=j;if(j>300) j-=50;break;case ENTER: tag=0;break;}}switch(j){case 300:close_full_screen();case 350:cleardevice();Score=0;menu();wall_note();play_game();break;}}*===========================================================*自定义函数:close_full_screen()*------------------------------*关闭图形界面*===========================================================*/ void close_full_screen(){cleardevice();closegraph();}/*=========================================================== *主函数:*------------------------------*调用图形界面--->开始欢迎界面--->菜单界面*--->画围墙--->游戏过程--->结束图形界面*===========================================================*/ main(){make_full_screen();start_screen();menu();wall_note();play_game();close_full_screen();}/*============================END============================*/。
C语言项目案例之贪吃蛇
C语⾔项⽬案例之贪吃蛇项⽬案例:贪吃蛇下载链接:1. 初始化墙代码:// 初始化墙void init_wall(void){for (size_t y = 0; y <= HIGH; ++y){for (size_t x = 0; x <= WIDE; ++x){if (x == WIDE || y == HIGH) // 判断是否到墙{printf("=");}else{printf(" ");}}printf("\n");}}效果:2. 定义蛇和⾷物类型typedef struct{int x;int y;}FOOD; // ⾷物typedef struct{int x;int y;}BODY; // ⾝体typedef struct{int size; // ⾝体长度BODY body[WIDE*HIGH];}SNAKE; // 蛇3. 初始化蛇和⾷物// 定义⼀个蛇和⾷物SNAKE snake;FOOD food;// 初始化⾷物void init_food(void){food.x = rand() % WIDE; // 随机⽣成坐标food.y = rand() % HIGH;}// 初始化蛇void init_snake(void){snake.size = 2;// 将蛇头初始化到墙中间snake.body[0].x = WIDE / 2;snake.body[0].y = HIGH / 2;// 蛇⾝紧跟蛇头snake.body[1].x = WIDE / 2 - 1;snake.body[1].y = HIGH / 2;}4. 显⽰UI// 显⽰UIvoid showUI(void){// 显⽰⾷物// 存放光标位置COORD coord;coord.X = food.x;coord.Y = food.y;// 光标定位SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); putchar('$');// 显⽰蛇for (size_t i = 0; i < snake.size; ++i){// 设置光标coord.X = snake.body[i].x;coord.Y = snake.body[i].y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); if (i == 0)}else{putchar('#');}}}效果:最终代码// main.c#define _CRT_SECURE_NO_WARNINGS#include "./snakeGame.h"int main(void){// 取消光标CONSOLE_CURSOR_INFO cci;cci.bVisible = FALSE; // 取消光标cci.dwSize = sizeof(cci);SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cci); system("color 2");printf("欢迎来到贪吃蛇\n准备好了吗?按s/S开始,q/Q退出\n"); char ch = _getch();switch (ch){case 's':case 'S':system("color 0");system("cls");break;default:return 0;}init_wall();init_food();init_snake();showUI();playGame();return 0;}// snakeGame.c#include "./snakeGame.h"// 定义⼀个蛇和⾷物SNAKE snake;FOOD food;// ⽅向增量int dx = 0;int dy = 0;int lx, ly; // 尾节点// 初始化⾷物void init_food(void){food.x = rand() % WIDE; // 随机⽣成坐标food.y = rand() % HIGH;}// 初始化蛇void init_snake(void){snake.size = 2;snake.fraction = 0;// 将蛇头初始化到墙中间snake.body[0].x = WIDE / 2;snake.body[0].y = HIGH / 2;snake.body[1].x = WIDE / 2 - 1;snake.body[1].y = HIGH / 2;}// 初始化墙void init_wall(void){for (size_t y = 0; y <= HIGH; ++y){for (size_t x = 0; x <= WIDE; ++x){if (x == WIDE || y == HIGH) // 判断是否到墙{printf("=");}else{printf(" ");}}printf("\n");}printf("分数:0\n");}// 显⽰UIvoid showUI(void){// 显⽰⾷物// 存放光标位置COORD coord;coord.X = food.x;coord.Y = food.y;// 光标定位SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);putchar('$');// 显⽰蛇for (size_t i = 0; i < snake.size; ++i){// 设置光标coord.X = snake.body[i].x;coord.Y = snake.body[i].y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);if (i == 0){putchar('@');}else{putchar('#');}}// 处理尾节点coord.X = lx;coord.Y = ly;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);putchar(' ');coord.X = WIDE;coord.Y = HIGH;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);printf("\n分数:%d\n",snake.fraction);}void playGame(void){COORD _coord;system("color 7");char key = 'D';// 蛇不能撞墙while (snake.body[0].x >= 0 && snake.body[0].x <= WIDE && snake.body[0].y >= 0 && snake.body[0].y <= HIGH) {// 蛇不能撞⾃⼰for (size_t i = 1; i < snake.size; ++i){if (snake.body[0].x == snake.body[i].x && snake.body[0].y == snake.body[i].y){goto OVER;}}// 撞⾷物if (snake.body[0].x == food.x && snake.body[0].y == food.y){++snake.size;++snake.fraction;// 随机出现⾷物init_food();}// 控制蛇移动// 判断是否按下按键if (_kbhit()){key = _getch(); // 不需要敲回车,按下就⽴马确认}// 判断W A S D中哪个按键按下switch (key){case 'w':case 'W':dx = 0;dy = -1;break;case 'a':case 'A':dx = -1;dy = 0;break;case 's':case 'S':dx = 0;dy = 1;break;case 'd':dx = 1;dy = 0;break;case 'q':case 'Q':_coord.X = WIDE;_coord.Y = HIGH;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), _coord); putchar('\n');return;}// 蛇移动// 记录尾节点位置lx = snake.body[snake.size - 1].x;ly = snake.body[snake.size - 1].y;for (size_t i = snake.size - 1; i > 0; --i){snake.body[i].x = snake.body[i - 1].x;snake.body[i].y = snake.body[i - 1].y;}// 更新蛇头snake.body[0].x += dx;snake.body[0].y += dy;showUI();Sleep(500); // 延时}// 游戏结束OVER:system("color 4");_coord.X = 6;_coord.Y = HIGH + 1;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), _coord); printf("\n游戏结束");printf("按r/R重新开始,按q/Q退出\n");char _key;_key = _getch();switch (_key){case 'r':case 'R':system("cls");init_wall();init_food();init_snake();showUI();playGame();case 'Q':case 'q':default:system("color 7");return;}}// snakeGame.h#pragma once#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <Windows.h>#define WIDE 60 // 长#define HIGH 20 // ⾼typedef struct{int x;int y;}FOOD; // ⾷物typedef struct{int x;int y;}BODY; // ⾝体typedef struct{int size; // ⾝体长度int fraction; // 分数BODY body[WIDE*HIGH];}SNAKE; // 蛇void init_wall(void);void init_food(void);void init_snake(void);void showUI(void);void playGame(void);。
超简单贪吃蛇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;}。
(完整word版)C语言最简洁的贪吃蛇源代码
C语言最简洁的贪吃蛇源代码.txt每天早上起床都要看一遍“福布斯”富翁排行榜,如果上面没有我的名字,我就去上班。
谈钱不伤感情,谈感情最他妈伤钱。
我诅咒你一辈子买方便面没有调料包。
#include〈graphics.h>#include<conio。
h〉#include〈dos.h〉#include<bios。
h>#include<stdlib。
h〉#define STATIC 0#define TRUE 1#define FALSE 0#define UP 1#define RIGHT 2#define DOWN 3#define LEFT 4#define VK_LEFT 0x4b00 /*上下左右键的值*/#define VK_RIGHT 0x4d00#define VK_DOWN 0x5000#define VK_UP 0x4800#define VK_ESC 0x011bint board[22][22];int snakelength=0;struct snake{public:int x=0;int y=0;int direction;}body[20];snake food;void makefood();/*产生一个食物*/int eatfood(); /*蛇吃掉食物*/void right(); /*上下左右的函数了*/void down();void left();void up();void getdirection(); /*判断蛇的方向*/move(snake *body)/*让蛇动起来*/{int x=body[0].x,y=body[0].y;if(body—>direction==RIGHT&&board[y][x+1]!=1)right();else if(body—>direction==DOWN&&board[y+1][x]!=1)down(); else if(body->direction==LEFT&&board[y][x—1]!=1)left(); else if(body—>direction==UP&&board[y-1][x]!=1)up();return 0;}void print() /*在屏幕上显示蛇*/{int i,j,x=0,y=0;for(i=1;i〈21;i++)for(j=1;j<21;j++)board[i][j]=0;for(i=0;i〈20;i++){x=body[i]。
c语言贪吃蛇
c语言贪吃蛇本文实例为大家分享了C语言实现简单贪吃蛇游戏的具体代码,供大家参考,具体内容如下:用指针数组来表示蛇,p[0]表示蛇头控制方向:w,s,a,d-->上下左右 j,k-->加速、减速键盘控制需要用到线程代码:#include <stdio.h>#include <pthread.h>#include <stdlib.h>#include <time.h>#include <unistd.h>#define X 20#define Y 40char head='@';//蛇头的形状char body='O';//蛇身的形状char a[X][Y]={'O','O','O','@'};char *p[X*Y]={&a[0][3],&a[0][2],&a[0][1],&a[0][0]};//p[0]表示蛇头int n=3; //蛇身的长度(不带蛇头)int i,j;int f=1; //标志位:1.右;2.上;3.左;4.下;-1.退出int us=200000;//用于usleep,延时0.2秒void right(){*p[n]=0;for(i=n;i>0;i--){p[i]=p[i-1];}*p[0]=body;p[0]=p[0]+1;//蛇头向右移*p[0]=head;}void left(){*p[n]=0;for(i=n;i>0;i--) {p[i]=p[i-1];}*p[0]=body;p[0]=p[0]-1;*p[0]=head;}void down(){*p[n]=0;for(i=n;i>0;i--) {p[i]=p[i-1];}*p[0]=body;p[0]=p[0]+Y;*p[0]=head;}void up(){*p[n]=0;for(i=n;i>0;i--) {p[i]=p[i-1];}*p[0]=body;p[0]=p[0]-Y;*p[0]=head;}void show(){system("clear"); for(i=0;i<Y;i++) printf("-"); printf("\n");for(i=0;i<X;i++){for(j=0;j<Y;j++){if(a[i][j]==0)printf(" ");elseprintf("%c",a[i][j]);}printf("\n");}for(i=0;i<Y;i++)printf("-");printf("\nw,s,a,d->上下左右;j,k->加减速;ESC退出\n"); }int ran()//随机数生成*{srand(time(NULL));lb:i=rand()%X;j=rand()%Y;//随机位置的值为0,则产生*;否则继续找随机位置if(a[i][j]==0)a[i][j]='*';elsegoto lb;}void eat(){if(f==1)//右{if(*(p[0]+1)=='*'){n++;//长度增加p[n]=p[n-1];ran();//随机数生成*}}if(f==2)//上{if(*(p[0]-Y)=='*'){n++;//长度增加p[n]=p[n-1];ran();//随机数生成*}}if(f==3)//左{if(*(p[0]-1)=='*'){n++;//长度增加p[n]=p[n-1];ran();//随机数生成*}}if(f==4)//下{if(*(p[0]+Y)=='*'){n++;//长度增加p[n]=p[n-1];ran();//随机数生成*}}}void fail(){if(p[0]<&a[0][0]||p[0]>&a[X-1][Y-1])//蛇头不在矩阵内{printf("fail!\n");f=-1;}if(f==1)//右{for(i=n;i>0;i--){if((p[0]+1)==p[i])//右边是自己的身体{printf("fail!\n");f=-1;}}}if(f==2)//上{for(i=n;i>0;i--){if((p[0]-Y)==p[i])//上边是自己的身体{printf("fail!\n");f=-1;}}}if(f==3)//左{for(i=n;i>0;i--){if((p[0]-1)==p[i])//左边是自己的身体{printf("fail!\n");f=-1;}}}if(f==4)//下{for(i=n;i>0;i--){if((p[0]+Y)==p[i])//下边是自己的身体{printf("fail!\n");f=-1;}}}}void *key(void *arg)//控制方向:w,s,a,d-->上下左右{char k;while(1){k=getchar();if(k=='w')//上f=2;if(k=='s')//下f=4;if(k=='a')//左f=3;if(k=='d')//右f=1;if(k=='j')//加速us=us*4/5;if(k=='k')//减速us=us*5/4;if(k==27)//ESC{printf("退出!\n");f=-1;}usleep(100);}}int main(){system("stty -icanon");//关闭缓冲区,输入字符无需回车直接接受pthread_t pid;pthread_create(&pid , NULL , key , NULL);//创建线程,键盘控制ran();while(1){show(); //显示usleep(us);fail(); //判断是否会咬到自己eat(); //判断是否能吃到*if(f==1)//右right();if(f==2)//上up();if(f==3)//左left();if(f==4)//下down();if(f==-1)//退出{pthread_cancel(pid);//关闭线程return -1;}}return 0; }。
C语言课程设计报告——贪吃蛇源程序
C 语言课程设计(小游戏贪吃蛇得程序设计报告)设计人:班级:201年月号目录一:概述1:研究背景及意义2:设计得任务与需要知识点3:具体完成设计内容二:需求分析1:功能需求2:操作方法三:总体设计1:模块划分2:数据结构设计四:详细设计1:主空摸块设计2:绘制游戏界面3:游戏得具体过程4:游戏得结束处理5:显示排行榜信息模块五:程序得调试与测试1:动画与音乐同步2:蛇得运行3:终止程序六:结论七::结束语八:程序清单九:参考文献一. 概述本课程设计以软件工程方法为指导,采用了结构化,模块化得程序设计方法,以C语言技术为基础,使用TurboC++3、0为主要开发工具,对贪吃蛇游戏进行了需求分析,总体设计,详细设计,最终完成系统得实现与测试。
1、1 研究得背景及意义随着社会得发展,人们生活得节奏日益加快,越来越多得人加入了全球化得世界。
人们不再拘泥与一小块天地,加班,出差成了现代人不可避免得公务。
而此时一款可以随时随地娱乐得游戏成为了人们得需要。
此次课程设计完成得贪吃蛇小游戏,正就是为了满足上述需求而设计出来得。
贪吃蛇游戏虽小,却设计诸多得知识点。
通过开发贪吃蛇游戏系统,可使读者初步了解使用软件工程得与那个发,技术与工具开发软件得过程,进一步掌握结构化,模块化得程序设计方法与步骤,进一步掌握总体数据结构设计,模块划分方法,掌握局部变量,全局变量,结构体,共用体,数组,指针,文件等数据结构得使用方法,掌握图形,声音,随机数等多种库函数得使用方法,学习动画,音乐,窗口,菜单,键盘等多项编程技术,进一步学会软件调试,测试,组装等软件测试方法,为后续课程得学习与将来实际软件开发打下坚实得基础。
1、2设计得任务与需要得知识点1、2、1 课程设计主要完成得任务1)、通过编写“贪吃蛇游戏”程序,掌握结构化,模块块化程序设计得思想,培养解决实际问题得能力。
2)有同步播放动画,声音效果。
3)设计好数组元素与蛇,食物得对应关系。
c语言贪吃蛇UI界面版
c语言U I界面版贪吃蛇使用ege图形库,游戏实现单双人功能。
道具有炸弹,随机魔盒,炸弹。
有随机障碍物生成。
不附加图片。
/*****************************************************************************出品方:债组* 成员:冯强陈志豪邓青松俄木木果* 时间:2016/7/11 ********************************************************************************/#include "graphics.h"#include <stdio.h>#include<time.h>#include<stdlib.h>#include<stdio.h>#include<time.h>#include<windows.h>#include <process.h>#define printf outtextint speed=5;#define U 1#define D 2#define L 3#define R 4#define A 5#define S 6#define W 7#define Dd 8#define VK_A 0x41//虚拟键值宏定义#define VK_S 0x53#define VK_W 0x57#define VK_D 0X44#define VK_N 0X4E#define VK_M 0x4d#define wd 10//蛇身的宽#define hg 10//蛇身的高//蛇身的一个节点typedef struct SNAKE{int x;int y;struct SNAKE *next;}snake;//全局变量//int score = 0, add = 10, score1 = 0, add1 = 10;;//总得分与每次吃食物得分。
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"stdafx.h"#include<stdio.h>#include<time.h>#include<windows.h>#include<stdlib.h>#include<conio.h>#define U 1#define D 2#define L 3#define R 4 //蛇的状态 U:上 D:下 L:左 R:右typedef struct snake //蛇⾝的⼀个节点{int x; //节点的x坐标int y; //节点的y坐标struct snake *next; //蛇⾝的下⼀个节点}snake;int score=0,add=10; //总得分和每吃⼀次⾷物的得分int highscore=0; //最⾼分int status,sleeptime=200; //蛇前进状态,每次运⾏的时间间隔snake *head,*food; //蛇头指针,⾷物指针snake *q; //遍历蛇时⽤的指针int endgamestatus=0; //游戏结束时的状态HANDLE hOut; //控制台句柄void gotoxy(int x,int y);int color(int c);void printsnake();void wlcome();void createmap();void scoreandtips();void initsnake();void createfood();int biteself();void cantcrosswall();void speedup();void speeddown();void snakemove();void keyboardcontrol();void lostdraw();void endgame();void choose();void file_out();void file_in();void explation();main(){system("mode con cols=100 lines=30");printsnake();wlcome();file_out();keyboardcontrol();endgame();}void gotoxy(int x,int y)//设置光标位置{COORD c;c.X=x;c.Y=y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c); //定位光标的位置}int color(int c)//设置颜⾊{SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),c);return 0;}void printsnake()//打印字符蛇{color(3);printf("学号:1910101099"); gotoxy(35,1);color(6);printf("/^\\/^\\");gotoxy(34,2);printf("|_| o|");gotoxy(33,2);color(2);printf("_");gotoxy(25,3);color(12);printf("\\/");gotoxy(31,3);color(2);printf("/");gotoxy(37,3);color(6);printf("\\_/");gotoxy(41,3);color(10);printf(" \\");gotoxy(26,4);color(12);printf("\\____");gotoxy(32,4);printf("_________");gotoxy(31,4);color(2);printf("|");gotoxy(43,4);color(10);printf("\\");gotoxy(32,5);color(2);printf("\\_______");gotoxy(44,5);color(10);printf("\\");gotoxy(39,6);printf("| | \\");gotoxy(38,7);printf("/ / \\");gotoxy(37,8);printf("/ / \\ \\");gotoxy(35,9);printf("/ / \\ \\");gotoxy(34,10);printf(" / / \\ \\");gotoxy(33,11);printf("/ / _----_ \\ \\");gotoxy(32,12);gotoxy(32,14);printf("\\ ~-____-~ _-~ ~-_ ~-_-~ /"); gotoxy(33,15);printf("~-_ _-~ ~-_ _-~");gotoxy(35,16);printf("~--____-~ ~-___-~");}void wlcome()//欢迎界⾯{int n;int i,j=1;gotoxy(43,18);color(11);printf("贪吃蛇⼤作战");color(14);for(i=20;i<=26;i++){for(j=27;j<=74;j++){gotoxy(j,i);if(i==20||i==26){printf("-");}else if(j==27||j==74){printf("|");}}}color(12);gotoxy(35,22);printf("1.开始游戏");gotoxy(55,22);printf("2.游戏说明");gotoxy(35,24);printf("3.退出游戏");gotoxy(29,27);color(3);printf("请选择1 2 3\n");color(14);scanf("%d",&n);switch(n){case 1:system("cls");//清屏createmap();initsnake();createfood();keyboardcontrol();break;case 2:explation();break;break;case 3:exit(0);break;}}void createmap()//创建地图{int i,j;for(i=0;i<58;i+=2){gotoxy(i,0);color(5);printf("□");gotoxy(i,26);gotoxy(0,i);printf("□");gotoxy(56,i);printf("□");}for(i=2;i<56;i+=2){for(j=1;j<26;j++){gotoxy(i,j);color(3);printf("■\n\n");}}}void scoreandtips()//游戏界⾯右侧的得分和⼩提⽰ {file_out();gotoxy(64,4);color(11);printf("*最⾼纪录*: %d",highscore);gotoxy(64,8);color(14);printf("得分: %d ",score);color(13);gotoxy(73,11);printf("⼩提⽰");gotoxy(60,13);color(6);printf("+---------------------+");gotoxy(60,25);printf("+---------------------+");color(3);gotoxy(64,14);printf("每个⾷物得分:%d分",add);gotoxy(64,16);printf("不能穿墙,不能咬到⾃⼰");gotoxy(64,18);printf("⽤↑↓←→分别控制蛇的移动");gotoxy(64,20);printf("F1为加速,F2为减速");gotoxy(64,22);printf("space: 暂停游戏");gotoxy(64,24);printf("ESC:退出游戏");}void file_out()//打开⽂件记录最⾼分{FILE *fp;fp=fopen("save.txt","a+");fscanf(fp,"%d",&highscore);fclose(fp);}void initsnake(){snake *tail;int i;tail=(snake*)malloc(sizeof(snake));tail->x=24;tail->y=5;tail->next=NULL;for(i=1;i<=4;i++){head=(snake*)malloc(sizeof(snake));head->next=tail;head->x=24+2*i;head->y=5;tail=head;}while(tail!=NULL){gotoxy(tail->x,tail->y);}void createfood()//随机出现⾷物{snake *food_1;srand((unsigned)time(NULL));food_1=(snake*)malloc(sizeof(snake));while((food_1->x%2!=0)){food_1->x=rand()%52+2;}food_1->y=rand()%24+1;q=head;while(q->next==NULL){if(q->x==food_1->x&&q->y==food_1->y){free(food_1);createfood();}q=q->next;}gotoxy(food_1->x,food_1->y);food=food_1;color(12);printf("@");}int biteself(){snake *self; //定义self为蛇⾝上除蛇头以外的节点self=head->next;while(self!=NULL){if(self->x==head->x&&self->y==head->y){return 1;}self=self->next;}return 0;}void cantcrosswall(){if(head->x==0||head->x==56||head->y==0||head->y==26) {endgamestatus=1;endgame();}}void speedup()//加速{if(sleeptime>=50){sleeptime=sleeptime-10;add=add+2;}}void speeddown()//减速{if(sleeptime<350){sleeptime=sleeptime+30;add=add-2;if(sleeptime==350){add=1;}}}void snakemove()//控制⽅向if(status==U)//上{nexthead->x=head->x; //向上前进时,x不变,y-1nexthead->y=head->y-1;nexthead->next=head;head=nexthead;q=head;//如果下⼀个位置上有⾷物,下⼀个位置的坐标和⾷物坐标相同if(nexthead->x==food->x&&nexthead->y==food->y){while(q!=NULL){gotoxy(q->x,q->y);color(14);printf("★");q=q->next;}score=score+add;speedup();createfood();}else{while(q->next->next!=NULL)//如果没有遇见⾷物{gotoxy(q->x,q->y);color(14);printf("★");q=q->next;}//经过上⾯的循环,q指向蛇尾,蛇尾的下⼀步就是蛇⾛过去的位置 gotoxy(q->next->x,q->next->y);color(3);printf("■");//恢复⾛过的位置free(q->next);q->next=NULL;}}if(status==D){nexthead->x=head->x; //向下前进时,x不变,y+1nexthead->y=head->y+1;nexthead->next=head;head=nexthead;q=head;//如果下⼀个位置上有⾷物,下⼀个位置的坐标和⾷物坐标相同if(nexthead->x==food->x&&nexthead->y==food->y){while(q!=NULL){gotoxy(q->x,q->y);color(14);printf("★");q=q->next;}score=score+add;speedup();createfood();}else{while(q->next->next!=NULL)//如果没有遇见⾷物{gotoxy(q->x,q->y);color(14);printf("★");q=q->next;}//经过上⾯的循环,q指向蛇尾,蛇尾的下⼀步就是蛇⾛过去的位置 gotoxy(q->next->x,q->next->y);color(3);if(status==L)//左{nexthead->x=head->x-2; //向左前进时,x不变,y+1nexthead->y=head->y;nexthead->next=head;head=nexthead;q=head;//如果下⼀个位置上有⾷物,下⼀个位置的坐标和⾷物坐标相同if(nexthead->x==food->x&&nexthead->y==food->y){while(q!=NULL){gotoxy(q->x,q->y); //⾷物变成蛇⾝上的⼀部分color(14);printf("★");q=q->next;}score=score+add;speedup();createfood();}else{while(q->next->next!=NULL)//如果没有遇见⾷物{gotoxy(q->x,q->y);color(14);printf("★");q=q->next;}//经过上⾯的循环,q指向蛇尾,蛇尾的下⼀步就是蛇⾛过去的位置 gotoxy(q->next->x,q->next->y);color(3);printf("■");//恢复⾛过的位置free(q->next);q->next=NULL;}}if(status==R){nexthead->x=head->x+2; //向上前进时,x不变,y-1nexthead->y=head->y;nexthead->next=head;head=nexthead;q=head;//如果下⼀个位置上有⾷物,下⼀个位置的坐标和⾷物坐标相同if(nexthead->x==food->x&&nexthead->y==food->y){while(q!=NULL){gotoxy(q->x,q->y);color(14);printf("★");q=q->next;}score=score+add;speedup();createfood();}else{while(q->next->next!=NULL)//如果没有遇见⾷物{gotoxy(q->x,q->y);color(14);printf("★");q=q->next;}//经过上⾯的循环,q指向蛇尾,蛇尾的下⼀步就是蛇⾛过去的位置 gotoxy(q->next->x,q->next->y);color(3);if(biteself()==1){endgamestatus=2;endgame();}}void keyboardcontrol(){status=R;while(1){scoreandtips();//GetAsyncKeyState函数⽤来判断函数调⽤指定虚拟键的状态 if(GetAsyncKeyState(VK_UP)&&status!=D){status=U;}else if(GetAsyncKeyState(VK_DOWN)&&status!=U){status=D;}else if(GetAsyncKeyState(VK_LEFT)&&status!=R){status=L;}else if(GetAsyncKeyState(VK_RIGHT)&&status!=L){status=R;}if(GetAsyncKeyState(VK_SPACE)){while(1){//调⽤sleep函数,令进程停⽌,直到达到其中设定的参数时间 Sleep(300);if(GetAsyncKeyState(VK_SPACE)){break;}}}else if(GetAsyncKeyState(VK_ESCAPE)){endgamestatus=3;break;}else if(GetAsyncKeyState(VK_F1)){speedup();}else if(GetAsyncKeyState(VK_F2)){if(sleeptime<350){sleeptime=sleeptime+30;add=add-2;if(sleeptime==350){add=1;}}}Sleep(sleeptime);snakemove();}}void lostdraw(){system("cls");int i,j;gotoxy(35,5);color(14);printf("o00o");gotoxy(39,5);color(11);printf("----------");gotoxy(48,5);color(14);printf("---");gotoxy(51,5);color(11);printf("----------");gotoxy(61,5);color(14);printf("o00o");gotoxy(65,5);color(11);printf("-----------------+");for(i=6;i<=19;i++){gotoxy(17,i);printf("|");gotoxy(82,i);printf("|");}gotoxy(17,20);printf("+----------------------------------");gotoxy(52,20);color(11);printf("-----------------------------+");}void endgame(){system("cls");if(endgamestatus==1){lostdraw();gotoxy(35,9);color(12);printf("对不起,您撞到墙了。
基于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语言控制台版贪吃蛇
头文件#ifndef _SNAKE_H_#define _SNAKE_H_/**--------------------------------------------------------------------------*** TYPE AND STRUCT * **--------------------------------------------------------------------------*/enum SNAKE_DIR {U, D, L, R};typedef enum SNAKE_DIR Dir;typedef struct COORDINA TE{int x;int y;}Coordinate;typedef struct SNAKE{Coordinate coord;struct SNAKE * next;}Snake;typedef Snake * Psnake;/**--------------------------------------------------------------------------*** MACRO DEFINITION ***--------------------------------------------------------------------------*/#define min_x 0#define max_x 60#define max_y 24#define min_y 0#define QUIT 0#ifndef FALSE#define FALSE 0#endif#ifndef TRUE#define TRUE 1#endif#define OVER 2/*按键定义*/#define J_FUNC_KEY0x00#define J_CTRL_KEY0xE0#define J_ESC 0x001B#define J_ENTER 0x000D#define J_SPACE 0x0020#define J_BKSPACE 0x0008#define J_LEFT 0xE04B#define J_RIGHT 0xE04D#define J_UP 0xE048#define J_DOWN 0xE050#define J_PGUP 0xE049#define J_DELETE 0xE053#define J_END 0xE04F#define J_PGDW 0xE051#define S_TIME 230#define CALTIME(x) (S_TIME-(x)*22)/*---------------------------------------------------------------------------*//* LOCAL FUNCTION DECLARE *//*---------------------------------------------------------------------------*/void ShowBye (void);void ShowPause (void);void print_explian (void);void gotoxy (int x, int y);void draw_map (Psnake *head);void draw_snake (Psnake *head);void EmptySnake (Psnake *head);void draw_food (Coordinate *food);void HasKey (Dir *direction, int * pause);void IniHead (Psnake * head, Psnake *tail);void IniCoord (Psnake * head, int x, int y);void IniSnake (Psnake * head, Psnake *tail, int n);void DelTail (Psnake *head, Psnake * tail, int x, int y);int Menu();int SetDifficulty(int *diff);int jkGetKey(void);int setCursorV isible(int b);int IniFood (Psnake *head, Coordinate *food);int InSnake (Psnake *head, int x, int y);int MoveSnake (Psnake *head, Psnake *tail, Dir * direction, Coordinate *food, int *leng);int IsOver (Psnake *head, int x, int y);int HitSelf (Psnake *head, int x, int y);int ShowOver (int *score);#endif函数接口实现#include <stdio.h>#include <stdlib.h>#include <windows.h>#include <conio.h>#include <assert.h>#include <time.h>#include "snake.h"//直接移动光标到X,Y坐标上。
C语言实现贪吃蛇小黑窗
C语⾔实现贪吃蛇⼩⿊窗本⽂实例为⼤家分享了C语⾔实现贪吃蛇⼩⿊窗的具体代码,供⼤家参考,具体内容如下思路:1.利⽤整型⼆维数组保存显⽰数据,⼩蛇每移动⼀次清屏并便利数组做到动态效果。
每次移动(清屏)的间隔时间控制了游戏难度,这个时间应不断缩减,直到游戏结束。
2.需要保存⼩蛇移动的⽅向,然后写⼀个函数通过⼩蛇的移动⽅向去处理⼆维数组中的数据,达到移动⼩蛇的⽬的。
3.⼩蛇的移动可分解为两个过程:头部像前⽅⽣长⼀格然后尾部消去⼀格。
如果蛇头吃到⾷物,尾部⽆需消去,此时应⽴即随机⽣成⼀个新的⾷物。
4.游戏开始时⼩蛇应随机⽣成在地图某⼀位置,此时⼩蛇的默认移动⽅向也应该是随机的。
5每次移动前应接收玩家由键盘输⼊的移动⽅向,如果接收到后,判断合法后将其设为⼩蛇的默认移动⽅向,如果玩家未进⾏任何输⼊,⼩蛇应按照默认⽅向移动。
个⼈难点:1.⼩蛇移动该函数需要拿到蛇头当时所在的位置坐标和⼩蛇的移动⽅向。
随后可由蛇头位置往移动⽅向往前⽣长⼀格,即将⼆维数组中⽬标移动位置的数据设置为⼩蛇的数据。
消去蛇尾另写⼀个函数,调⽤前需先判断是否吃到⾷物,是否撞到墙壁或者是⾃⾝,然后决定是否削去尾部。
消去蛇尾需获得蛇尾的位置,所以我们在该函数内加⼊递归搜索蛇尾的算法:进⼊函数后先判断此时的位置是否为蛇尾,若不是就将⾃⾝位置往后移动⼀格(将蛇⾝往后⼀格的坐标输⼊给DeleteTail函数,然后继续此过程),直到遇到蛇尾,然后将其消去(置零)。
具体代码实现如下:int MoveSnake(int trend, int* px, int* py, int data[ROW][COL], int* t){int ret = 1;//默认前进成功//printf("trend=%d\n", trend);switch (trend) {case 1:*py -= 1; break;//向上case 2:*px -= 1; break;//向左case 3:*py += 1; break;//向下case 4:*px += 1; break;//向右}//找到即将前进的坐标if (data[*py][*px] == 6) {data[*py][*px] = trend;CreatFood(data);*t *= 0.9;}//如果蛇头要前进的格⼦是⾷物,向前长⼀格,尾部不变;else if (data[*py][*px] == 0) {data[*py][*px] = trend;//向前长⼀格DeleteTail(*px, *py, data);//消去最后的尾巴}else {ret = 0;printf("前进失败\n");}//前进失败return ret;}int DeleteTail(int x, int y, int data[ROW][COL]){//PrintTest(data);if (data[y][x] <= 4 && data[y][x] >= 1) {switch (data[y][x]) {case 1:if (DeleteTail(x, y + 1, data) == 0) {data[y][x] = 0;}break;case 2:if (DeleteTail(x + 1, y, data) == 0) {data[y][x] = 0;}break;case 3:if (DeleteTail(x, y - 1, data) == 0) {data[y][x] = 0;}break;case 4:if (DeleteTail(x - 1, y, data) == 0) {data[y][x] = 0;}break;}return 1;}else {return 0;}}2.输⼊在实际代码实现的过程中,我发现scanf函数⽆法实现需求,理由是程序执⾏到scanf语句时,会停留在该位置,直到scanf函数扫描到输⼊后,程序才会继续进⾏。
C语言 贪吃蛇游戏
#define LEFT 0x4b00/*向左键*/ #define RIGHT 0x4d00/*向右键*/ #define DOWN 0x5000/*向下键*/ #define UP 0x4800/*向上键*/ #define ESC 0x011b/*〈ESC〉退出键*/ #define N 100/*贪吃蛇的最大长度*/
setfillstyle(1,12);/*用淡红色填充砖的中间部分*/ bar(x+2,y+2,x+sizx-2,y+sizy-2); }
这个函数可以让用户按下任意键而不需要回车键就可以接收到用户的输入。可以用来作为 “press anykey to continue”的实现。
实现过程
(1)预处理模块 在本游戏系统中需要引用一些头文件,以便程序更好的运行。引用头文件需要使用#include命令,
下面即是要引用的文件和引用代码,实现代码如下:
表19.2 cmd参数的设置值
参数值
含义
cmd = 0
cmd = 1
cmd = 2
当cmd是0,bioskey()返回下一个在键盘键入的值(它将等待到按下一个键)。 它返回一个16位的二进制数,包括两个不同的值。当按下一个普通键时,它的低8 位数存放该字符的ASCII码,高8位存放该键的扫描码;对于特殊键(如方向键、 F1~F12等等),低8位为0,高8位字节存放该键的扫描码
声明结构体,food是表示食物基本信息的结构体,snake是定义贪吃蛇基本信息的结构体,代码如下:
struct FOOD int x; /*食物的横坐标*/
贪吃蛇C程序及流程图和模块设计说明
#define N 200#include <graphics.h>#include <stdlib.h>#include <dos.h>#define LEFT 0x4b00#define RIGHT 0x4d00#define DOWN 0x5000#define UP 0x4800#define ESC 0x011bint i,key;int score=0;/*得分*/int gamespeed=50000;/*游戏速度自己调整*/ 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=DETECT,gm;initgraph(&gd,&gm,"c:\\tc");cleardevice();}/*开始画面,左上角坐标为(50,40),右下角坐标为(610,460)的围墙*/ void DrawK(void){/*setbkcolor(LIGHTGREEN);*/setcolor(11);setlinestyle(SOLID_LINE,0,THICK_WIDTH);/*设置线型*/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){randomize();/*随机数发生器*/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)/*食物整个坐标大小需要符合10*10的大小否则社无法迟到*/ 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(0);/*把画面上的食物东西去掉*/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(4);/*画出蛇*/for(i=0;i<snake.node;i++)rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10);delay(gamespeed);setcolor(0);/*用黑色去除蛇的的最后一节*/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=bioskey(0);/*接收按键*/if(key==ESC)/*按ESC键退出*/break;/*判断是否往相反的方向移动(向相反方向移动会死亡)第三类死亡条件*/ elseif(key==UP&&snake.direction!=4)snake.direction=3;elseif(key==RIGHT&&snake.direction!=2)snake.direction=1;elseif(key==LEFT&&snake.direction!=1)snake.direction=2;elseif(key==DOWN&&snake.direction!=3)snake.direction=4;}/*endwhile(1)*/}/*第五部分:游戏结束*/void GameOver(void){cleardevice();PrScore();setcolor(RED);settextstyle(0,0,4);outtextxy(200,200,"GAME OVER"); getch();}/*第六部分:输出成绩*/void PrScore(void){char str[10];setfillstyle(SOLID_FILL,YELLOW); bar(50,15,220,35);setcolor(6);settextstyle(0,0,2);sprintf(str,"score:%d",score); outtextxy(55,20,str);}/*第七部分:结束图形*/void Close(void){getch();closegraph();}本系统分为:初始化即图形驱动函数init()模块、图形界面设计Drawk()模块、游戏GamePlay()模块、输出成绩PrScore()模块、退出游戏Close模块、在游戏模块中通过3个控制语句判断游戏中的蛇是否死亡(3中死亡方式),不出现死亡在游戏结束时候打出成绩,如果出现死亡则跳出循环并打出成绩并进行初始化设定,如果不玩游戏按ESC则退出游戏。
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#include#include#include#include//蛇头移动方向#define UP 1#define DOWN 2#define LEFT 3#define RIGHT 4〃死亡判定(葱墙或葱自己)#define KISSASS 1#define KISSWALL 2//坐标转化#define POINT(x,y) ((y)*80+(x)+1)// 将(x,y)坐标转化为一个int 类数值#define GETX(x) (((x)-1)%80)// 将int 类数值提取出原先的x#define GETY(y) (((y)-1)/80)// 同理,提取出yHANDLE Console;void Position(int x, int y); // 移动光标到(x,y) //Windows.hvoid DrawMap();// 画墙void ShowText(char *text);//根据字符串的长短智能打印出包围字符串的笑脸void ResetSnake();// 初始化贪吃蛇int RefreshSnake();// 更新蛇的移动void CreatFood();// 生成食物void Draw();//画出蛇身和食物void RefreshScreen();// 屏幕刷新void GameOver(int Type);// 游戏结束条件int Gaming();//代码跑起来char play = 0; ////值为1则继续游戏,值为0游戏退出char pause = 0; //值为1则暂停,值为0游戏继续char direction; // 蛇头方向int snake[500]; //snake[0]为蛇头int body; //蛇身体长度int newbody;//吃完食物新长的蛇身int addHead,deleteTail;//增加蛇头擦去蛇尾,使贪吃蛇动起来int food = 0; // 食物void main()(CONSOLE_CURSOR_INFO CurrInfo = { sizeof(CONSOLE_CURSOR_INFO), 0 };Console = GetStdHandle(STD_OUTPUT_HANDLE);DrawMap();ShowT ext("Copyright reserve by 博元");while(Gaming()){if (play)DrawMap();};return 0;}void Position(int x, int y)// 移动光标到(x,y) //Windows.h{COORD coors = { x, y };SetConsoleCursorPosition(Console, coors);}void DrawMap() // 画墙{int i;for (i = 3; i < 70; i = i + 12){Position(i, 0);printf("===我是墙===");}for (i = 0; i < 25; i = i + 1){Position(0, i);printf("|| ");}for (i = 3; i < 70; i = i + 12){Position(i, 24);printf("============");}for (i = 0; i < 25; i = i + 1){Position(76, i); printf("|| ");void ShowText(char *text) //根据字符串的长短智能打印出包围字符串的笑脸(int i;int strLength = strlen(text); // 得到字符串长度Position(40 - (strLength / 2)-1, 11);printf("%c”, 1);for (i = 0; i < strLength + 2; i++)(printf("%c", 1);}printf("%c", 1);Position(40 - (strLength / 2)-1, 12);printf("%c ", 1);printf(text);printf(" %c", 1);Position(40 - (strLength / 2)-1, 13);printf("%c", 1);for (i = 0; i < strLength + 2; i++)(printf("%c", 1);}printf("%c", 1);}void ResetSnake() //初始化贪吃蛇(int x, y;for (x = 39, y = 0; y < 2; y++)(snake[y] = POINT(x, 7 - y);}body = 2; //设定蛇身初始长度为2newbody = 6;addHead = 0;deleteTail = 0;direction = LEFT;}int RefreshSnake() 〃更新蛇的移动〃返回值为1游戏结束( int x, y;memcpy(snake + 1, snake, sizeof(int)*body);if (!newbody){deleteTail = snake[body];snake[body] = 0;}else{body++;newbody--;}x = GETX(snake[0]);y = GETY(snake[0]);switch (direction) //控制蛇头移动方向{case UP:y -= 1; //蛇头向上移动一格(对应坐标y-1 ) snake[0] = POINT(x, y);break;case DOWN:y += 1;snake[0] = POINT(x, y); break;case LEFT:x -= 1;snake[0] = POINT(x, y); break;case RIGHT:x += 1;snake[0] = POINT(x, y); break;}addHead = snake[0];if (x > 75 || x < 3 ||y > 23 || y < 1) // 检测是否撞墙(GameOver(KISSWALL);return 1;}int i;for (i = 1; i < body; i++)if (snake[0] == snake[i]) // 检测是否撞到自己身体(GameOver(KISSASS);return 1;}if (snake[0] == food)(while (1) //食物的位置不与蛇身重合(food = (rand() % (75 * 23));for (i = 0; snake[i]; i++)if (food == snake[i])// 检测是否吃到食物,吃到则reset食物food = 0;if (food) 〃如果food==0 则重新建立一个食物坐标break;}CreatFood(); // 吃了?再来一个!newbody = (rand() % 6) + 1; // 吃完食物蛇身增长一节}return 0;}void CreatFood() // 生成食物(if (GETX(food) > 75 || GETX(food) < 3 || GETY(food) > 23 || GETY(food) < 1) CreatFood;elsePosition(GETX(food), GETY(food));printf("%c”,4);}void Draw() //画出蛇身和食物(system("cls");int i;for (i = 0; snake[i]; i++)(Position(GETX(snake[i]), GETY(snake[i])); printf("%c”,1);}CreatFood();}void RefreshScreen() // 屏幕刷新(if (deleteTail)(Position(GETX(deleteTail), GETY(deleteTail)); printf("");}if (addHead)(Position(GETX(addHead), GETY(addHead)); printf("%c",1);}addHead = deleteTail = 0;}void GameOver(int Type) // 游戏结束条件(switch (Type)(case KISSASS://? 至ij 自己身体ShowT ext("NOOB !当你以光速绕着一棵树奔跑就会发现自己在葱自己!");break;case KISSWALL://撞墙ShowT ext("NOOB !你有考虑过墙的感受吗");}food = 0;play = 0;memset(snake, 0, sizeof(int) * 500); // 存初始化} int Gaming() // 执行int Keyboardinput;Sleep(60);// 速度if (kbhit())(Keyboardinput = getch();if (Keyboardi nput == 0 || Keyboardinput == 0xE0) (Keyboardinput = getch();switch (Keyboardi nput) // 方向控制(case 72:if (direction != DOWN) direction = UP;break;case 80:if (direction != UP)direction = DOWN;break;case 75:if (direction != RiGHT)direction = LEFT;break;case 77:if (direction != LEFT)direction = RiGHT;break;}}if (Keyboardi nput == '\r') // 暂停(if (!play)(play = 1;if (pause)(Draw();pause = 0;}}else(ShowT ext("不许暂停,继续葱!!");play = 0;pause =1;}}else if (KeyboardI nput == 0x1B) // 退出return 0; } if (play)(if (!food)(srand(clock());food = (rand() % (75 * 23)); ResetSnake();Draw();}else(if (!RefreshSnake())(RefreshScreen();}}}。
C语言实现贪吃蛇游戏代码
C语⾔实现贪吃蛇游戏代码本⽂实例为⼤家分享了C语⾔实现贪吃蛇游戏的具体代码,供⼤家参考,具体内容如下//------------------------------------------problm区------------------------------//①思考typedef 定义的变量如何利⽤fwrite进⾏存储//②典型可利⽤sleep()语句类实现控制移动速度//③BOOL PlaySoundW(LPCWSTR, HMODULE, DWORD)”: ⽆法将参数 1 从“const char[8]”转换为“LPCWSTR -->导致原因-->即原因vc2010开发环境中可能找不到字符串的⾳乐导致//④思考怎么消去不是这四个键的情况#include<stdio.h>#include<stdlib.h>#include<Windows.h>#include<conio.h>#include<string.h>#include<time.h>#include <MMSystem.h>//导⼊声⾳头⽂件-->即联合形成#pragma warning(disable:4996)//可以利⽤该代码消去警告类#pragma comment(lib, "Winmm.lib")//链接库//------------------------------------------变量区---------------------------------//---------------------------------------宏定义变量定义----------------------------#define H 24//定义⾼为24#define W 78//定义宽为78#define false 0#define true 1//-------------------------------------⾮宏定义变量定义----------------------------int n=0;//全局变量定⽤于写界⾯的状况int zpalyer=0;//记录总玩家的个数int fs;//⽤于记录玩家的分数int key=72;//⽤于控制玩家的移动⽅向的变量,且赋予初始化值为上int changeFlag = 0;//判断是否吃到了果实,⽤于确定是否需要擦除蛇尾int i;//⽤于函数中控制循环的变量char name[20];char name1[20];struct palyerinfo//定义玩家的名称与分数的结构体{char name[20];int palyefs;}player[100];struct //定义贪吃蛇的⾷物产⽣的坐标类{int x;int y;}food;struct //利⽤链表实现贪吃蛇的长度{int x[100];int y[100];int len;int zfs;int speed;}snake1;//------------------------------------------声明区---------------------------------void xj();void dq();void save();void ck();void xuanz();void jm();void phb();void fs1();int begin();void creatfood();void keyDown();bool sfjs();void getoxy(int x,int y);void ex();int yy();//------------------------------------------函数区---------------------------------//-----------------------------------------界⾯函数区------------------------------void menu1()//进⼊游戏后选择读取⽤户还是新建⽤户{int n;system("color 3e");//即加⼀个语句即可控制颜⾊,即与cmd中类似进⾏控制颜⾊-->控制的是控制台的颜⾊printf("====================================================\n");printf("# #\n");printf("# #\n");printf("# 1. 建⽴新玩家 #\n");printf("# 2. 读取存档 #\n");printf("# #\n");printf("# #\n");printf("====================================================\n");printf(" 选项:");scanf("%d", &n);if (n == 1){xj();}elseif (n == 2){dq();}else{printf("输⼊错误,请重新选择:\n");menu1();}}void menu2()//游戏⾥⾯的主菜单{int n;printf("====================================================\n");printf("# #\n");printf("# 贪吃蛇 Version goddemon #\n");printf("# #\n");printf("# 1. 开始游戏 #\n");printf("# 2. 查看排⾏榜 #\n");printf("# 3. 查看我的分数 #\n");printf("# 4. 退出游戏 #\n");printf("# #\n");printf("# #\n");printf("====================================================\n");printf(" 选项:\n");while (1){scanf_s("%d", &n);switch (n)//选择功能{case 1: begin(); break;case 2: phb(); break;case 3: fs1(); break;case 4: ex(); break;default: printf("输出错误,请重新输⼊:\n"); break;}}}void xj()//新建⽤户的名字{ck();++zpalyer; //注意如果是在退出的时候赋予的值,会出现只能读出两个值的状况特点-->即在⼦函数中赋予值,必须在读取值后进⾏赋予值加减才可,否则可能出现乱码状况 printf("\t\t输⼊⽤户名:\n");//注意利⽤\t\t进⾏控制界⾯-->很nicescanf("%s", name);strcpy(player[zpalyer].name,name);//注意赋值的先后menu2();}void dq()//读取存档⾥⾯的⽤户且进⾏选择{ck();printf("请输⼊读取的姓名:\n");scanf("%s", name1);for (i = 0; i <= zpalyer; i++){if ((strcmp(player[i].name, name1) == 0)){menu2();}elseif(i==zpalyer){printf("未找到该⽤户,请在次选择读取与创建功能\n");menu1();}}}//-----------------------------功能函数区---------------------------------int begin()//开始游戏{system("cls");jm();while (1){keyDown();if (!sfjs())break;creatfood();Sleep(snake1.speed);}player[zpalyer].palyefs = snake1.zfs;getoxy(W / 2, H / 2);printf("本次得分:%d\n",snake1.zfs);Sleep(3000);system("cls");menu2();Sleep(5000);return 0;}void phb()//排⾏榜{int i;printf("====================== 排⾏榜 ====================\n");for (i = 0; i <zpalyer; i++){printf("%s\t%d\n", player[i].name, player[i].palyefs);}printf("====================================================\n");}void fs1()//查看⾃⼰的分数{printf("你的分数为:\n");printf("%d", player[zpalyer].palyefs);}void ex()//退出功能{save();exit(0);}void save(){FILE *fp;fp = fopen("tcs.txt", "w+");fwrite(&zpalyer, 4, 1, fp);for (i = 0; i <= zpalyer; i++){fwrite(&player[i], sizeof(struct palyerinfo), 1, fp);}fclose(fp);}void ck()//读取⽂档中的数据状况{FILE *fp;int i;fp = fopen("tcs.txt", "r+");fread(&zpalyer, 4, 1, fp);for (i = 0; i <=zpalyer; i++){fread(&player[i], sizeof(struct palyerinfo), 1, fp);}fclose(fp);}void xuanz(){int j = 0, x = 1;menu2();}void getoxy(int x,int y)//定位坐标位置的函数{COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);}void jm()//贪吃蛇初始化界⾯{SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY); system("color 3e");//打印上下边界的循环for (i = 0; i <= W; i+=2){getoxy(i, 0);printf("++");getoxy(i,H);//打印下边界printf("++");}for (i = 0; i < H; i++){getoxy(0, i);printf("++");getoxy(W, i);printf("++");//打印下边界}while (1)//⽣成初始化的⾷物{srand((unsigned int)time(NULL));food.x = rand() % (W - 4) + 2;food.y = rand() % (H - 2) + 1;if (food.x % 2 == 0){break;}}getoxy(food.x, food.y);printf("*");snake1.len = 3;snake1.speed = 200;snake1.x[0] = W / 2 + 1;//即在中间区域打印蛇头snake1.y[0] = H / 2;getoxy(snake1.x[0], snake1.y[0]);printf("★");for (i = 1; i < snake1.len; i++)//打印蛇头的状况特点-->利⽤getoxy(光标移动)+printf语句联合打印出蛇 {snake1.x[i] = snake1.x[i - 1] + 2;//即将坐标赋值加2的状况理解snake1.y[i] = snake1.y[i - 1];getoxy(snake1.x[i], snake1.y[i]);printf("★");}getoxy(W - 2,0);return;}void creatfood()//创建⾷物的函数{if (snake1.x[0] == food.x&&snake1.y[0] == food.y)//即蛇会吃掉这个⾷物{while (1){int flag = 1;srand((unsigned int)time(NULL));food.x = rand() % (W - 4) + 2;food.y = rand() % (H - 2) + 1;for (i = 0; i < snake1.len; i++){if (snake1.x[i] == food.x&&snake1.y[i] == food.y){flag = 0;break;}}if (flag&&food.x % 2 == 0)//⽤该语句进⾏判断是否该结束坐标赋值{break;}}getoxy(food.x, food.y);//即创建⾷物,每⼀次都进⾏创造printf("*");snake1.len++;//即蛇的长度加1,因为吃到了⾷物导致snake1.speed -= 5;snake1.zfs += 10;//即⼀个果实的分数等于10分changeFlag = 1;//即意味着吃到了⾷物,不需要擦除蛇尾的含义}return;//即return可以为空}void keyDown()//控制移动的函数{int pre_key = key;//记录前⼀个按键的⽅向if (_kbhit()){fflush(stdin);//getch()读取⽅向键的时候,会返回两次,第⼀次调⽤返回0或者224,第⼆次调⽤返回的才是实际值 key = _getch();//第⼀次调⽤返回的不是实际值key = _getch();//第⼆次调⽤返回实际值}if (changeFlag == 0){getoxy(snake1.x[snake1.len - 1], snake1.y[snake1.len - 1]);printf(" ");//在蛇尾处输出空格即擦去蛇尾}//将蛇的每⼀节依次向前移动⼀节(蛇头除外)for (i = snake1.len - 1; i > 0; i--){snake1.x[i] = snake1.x[i - 1];snake1.y[i] = snake1.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;switch (key){case 75:snake1.x[0] -= 2;//往左break;case 77:snake1.x[0] += 2;//往右break;case 72:snake1.y[0]--;//往上break;case 80:snake1.y[0]++;//往下break;}//打印出蛇头getoxy(snake1.x[0], snake1.y[0]);printf("★");getoxy(W - 2, 0);//由于⽬前没有吃到⾷物,changFlag值为0changeFlag = 0;return;}bool sfjs()//判断游戏是否结束的函数{if (snake1.y[0] == 0 || snake1.y[0] == H){return false;}if (snake1.x[0] == 0 || snake1.x[0] == W){return false;}for (i = 1; i < snake1.len; i++){if (snake1.x[i] == snake1.x[0] && snake1.y[i] == snake1.y[0])//注意判断是否结束的函数需要注意{return false;}}return true;//即返回这个函数本⾝为真}int yy(){PlaySound(TEXT("F:\\⼩苹果.wav"), NULL, SND_NODEFAULT | SND_ASYNC | SND_LOOP);//即利⽤转换参数进⾏代//SND_LOOP-->//重复播放声⾳,必须与SND_ASYNC标志⼀块使⽤//SND_ASYNC-->//⽤异步⽅式播放声⾳,PlaySound函数在开始播放后⽴即返回//SND_NODEFAULT -->不播放缺省声⾳,若⽆此标志,则PlaySound在没找到声⾳时会播放缺省声⾳-->典型找⽂件⾳乐是⽤的格式查看⽅式进⾏找的 return 0;}//------------------------------------------主函数区-------------------------------int main(){yy();menu1();system("pause");return 0;}效果图:更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
纯C语言编写贪吃蛇(附源码,无EasyX、MFC)
纯C语⾔编写贪吃蛇(附源码,⽆EasyX、MFC)⼤⼀下学期,我所选的C语⾔⼯程实践是写⼀个贪吃蛇游戏。
那⼏天真的挺肝的,完成本专业的答辩之后就没怎么动过这程序了。
那时候写的贪吃蛇,还有⼀个栈溢出的问题没有解决,是因为当时所学知识有限,还没想到较好的解决⽅法。
现在⼤⼆上学期,在上了好⼏节数据结构之后,对栈有了⼀定的了解,随着对栈的学习,我想出了解决我写的贪吃蛇栈溢出的办法。
其实是前两天刚刚有这个想法,刚刚才测试并实现了,办法可⾏。
现在我加⼊了计算机学院的创新开放实验室,打算做的⼀个项⽬是微信⼩程序。
以后想记录⼀下我的开发过程和⼀些经历,⼜刚刚完善好贪吃蛇的代码,就简单记录⼀下吧。
因为代码⽐较长,先把参考资料写⼀下,想⾃⼰⼿写⼀遍的建议先看参考资料,再看这⾥的代码参考资料源代码/*预处理*/#include <windows.h>#include <stdio.h>#include <conio.h>#include <string.h>#include <time.h>/*宏定义*/#define YES 1#define NO 0//蛇的移动⽅向#define U 1 //上#define D 2 //下#define L 3 //左#define R 4 //右#define RESPEED 250 //蛇的移动速度/*定义节点*/typedef struct SNAKE{int x;int y;struct SNAKE* next;}snake;/*全局变量*/snake* head, * food; //蛇头指针,⾷物指针snake* q; //遍历蛇的时候⽤到的指针/*【以下为所有函数的声明】*/void HideCursor(void); //隐藏光标void color(short int num); //颜⾊函数void StartWindow(void); //开始界⾯int gotoxy(int x, int y); //定位光标位置void creatMap(void); //创建地图void notice(int* score, int* highscore, int* Time, int* LongTime); //提⽰void initsnake(void); //初始化蛇⾝int biteself(unsigned long* sleeptime); //判断是否咬到了⾃⼰int createfood(void); //随机出现⾷物void endgame(int* score, int* highscore, int* endgamestatus, int* Time, int* LongTime); //结束游戏void pause(int* PauseBegin, int* PauseEnd); //暂停游戏void gamecontrol(unsigned long* sleeptime, int* count, int* score, int* highscore, int* status, int* endgamestatus,int* Time, int* LongTime, int* TimeBegin, int* TimeEnd, int* TimePause, int* PauseBegin, int* PauseEnd); //控制游戏(包含蛇不能穿墙)void snakemove(unsigned long* sleeptime, int* count, int* score, int* status, int* endgamestatus); //蛇移动void gamestart(int* score, int* highscore, int* endgamestatus, int* Time, int* LongTime, int* TimeBegin); //游戏初始化void gamecontinue(unsigned long* sleeptime, int* count, int* score, int* highscore, int* status, int* endgamestatus,int* Time, int* LongTime, int* TimeBegin, int* TimeEnd, int* TimePause, int* PauseBegin, int* PauseEnd); //再来⼀局void stop(unsigned long* sleeptime); //蛇停⽌移动void start(unsigned long* sleeptime); //蛇恢复移动void reset(int* count, int* score, int* Time, int* TimeBegin, int* TimeEnd, int* TimePause, int* PauseBegin, int* PauseEnd); //重置多项数据void updatescore(int* score, int* highscore, int* Time, int* LongTime); //更新多项数据int main(void){unsigned long sleeptime = RESPEED;int score = 0, highscore = 0, count = 0; //count是记录吃到⾷物的次数int status, endgamestatus = 0; //游戏结束情况,0未开始游戏前退出,1撞到墙,2咬到⾃⼰,3主动退出游戏,4通关HideCursor();gamestart(&score, &highscore, &endgamestatus, &Time, &LongTime, &TimeBegin);gamecontrol(&sleeptime, &count, &score, &highscore, &status, &endgamestatus, &Time, &LongTime, &TimeBegin, &TimeEnd, &TimePause, &Pa useBegin, &PauseEnd);endgame(&score, &highscore, &endgamestatus, &Time, &LongTime);gamecontinue(&sleeptime, &count, &score, &highscore, &status, &endgamestatus, &Time, &LongTime, &TimeBegin, &TimeEnd, &TimePause, &P auseBegin, &PauseEnd);return 0;}void HideCursor(void) //隐藏光标{CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);}void color(short int num){HANDLE hConsole = GetStdHandle((STD_OUTPUT_HANDLE));SetConsoleTextAttribute(hConsole, num);}void StartWindow(void){short int i;system("mode con cols=120 lines=30"); //设置窗⼝⼤⼩printf("温馨提⽰:请使⽤键盘操作(⿏标点击可能会导致程序出错)\n");printf("╔═══════════════════════════════════════════════════╗ \n");for (i = 0; i < 26; i++){printf("║ ║ \n");}printf("╚═══════════════════════════════════════════════════╝ \n");gotoxy(23, 2);color(3);printf("贪吃蛇");for (i = 15; ; i--){gotoxy(18, 4);color(i);printf("按任意键加载程序");Sleep(600);if (i == 1){i = 15;}if (kbhit()) //判断是否按键,等待输⼊按键为0,按键为1{break;}}gotoxy(10, 4);printf("1.开始游戏 2.退出游戏");getch();}int gotoxy(int x, int y){HANDLE handle; //定义句柄变量handle,创建⼀个句柄COORD pos; //定义结构体coord (坐标系coord)pos.X = x; //横坐标xpos.Y = y; //纵坐标yhandle = GetStdHandle(STD_OUTPUT_HANDLE); //获取控制台输出句柄(值为-11)SetConsoleCursorPosition(handle, pos); //移动光标return YES;}void creatMap(void){int i;//地图⼤⼩:长24×宽20printf("■");gotoxy(i, 27);printf("■");}for (i = 7; i < 28; i++) //打印左右边框{gotoxy(2, i);printf("■");gotoxy(50, i);printf("■");}}void notice(int* score, int* highscore, int* Time, int* LongTime){system("title 2018051170 Project:贪吃蛇");gotoxy(4, 4);color(15);printf("得分:%3d 最⾼分:%3d ⽣存:%4ds 最久⽣存:%4ds", *score, *highscore, *Time, *LongTime); gotoxy(60, 7);printf("Author: 2018051170 Project: 贪吃蛇");gotoxy(60, 9);printf("游戏说明:");gotoxy(60, 10);printf("不能穿墙,不能咬到⾃⼰");gotoxy(60, 11);printf("↑↓←→控制蛇的移动");gotoxy(60, 12);printf("ESC:退出游戏空格:暂停游戏");}void initsnake(void){int i;snake* tail;tail = (snake*)malloc(sizeof(snake)); //从蛇尾开始,插头法,以x,y设定开始的位置tail->x = 26;tail->y = 14;tail->next = NULL;for (i = 1; i < 3; i++){head = (snake*)malloc(sizeof(snake));head->next = tail;head->x = 26 - 2 * i;head->y = 14;tail = head;}while (tail != NULL) //从头到为,输出蛇⾝{gotoxy(tail->x, tail->y);if (i == 3){color(2);printf("●");i++;}else if (tail != NULL){color(2);printf("■");}tail = tail->next;}}int biteself(unsigned long* sleeptime){snake* self;self = head->next;while (self != NULL){if (self->x == head->x && self->y == head->y)self = self->next;}return NO;}int createfood(void){snake* food_1;food_1 = (snake*)malloc(sizeof(snake));srand((unsigned)time(NULL)); //产⽣⼀个随机数while ((food_1->x % 2) != 0) //保证其为偶数,使得⾷物能与蛇头对其{food_1->x = rand() % 50; //保证其在墙壁⾥X1 < X < X2if (food_1->x <= 4){food_1->x = food_1->x + 4;}}food_1->y = rand() % 27; //保证其在墙壁⾥Y1 < Y < Y2if (food_1->y < 7){food_1->y = food_1->y + 7;}q = head;while (q != NULL) //判断蛇⾝是否与⾷物重合{if (q->x == food_1->x && q->y == food_1->y){free(food_1);return 1;}if (q->next == NULL){break;}q = q->next;}gotoxy(food_1->x, food_1->y);food = food_1;color(3);printf("★");return 0;}void endgame(int* score, int* highscore, int* endgamestatus, int* Time, int* LongTime) {color(15);gotoxy(60, 14);if (*endgamestatus == 0){printf("您退出了游戏。
C语言课程设计贪吃蛇源代码
C语言课程设计贪吃蛇源代码c语言程序贪吃蛇代码#include#include#include#include#include#definen21file*fp;ints;voidboundary(void);//已经开始界面voidend(void);//完结voidgotoxy(intx,inty)//位置函数{coordpos;pos.x=x;pos.y=y;setconsolecursorposition(getstdhandle(std_output_han dle),pos);}voidcolor(inta)//颜色函数{setconsoletextattribute(getstdhandle(std_output_handle),a);}voidinit(intfood[2])//初始化函数(初始化围墙、显示信息、苹果){system(\inti,j;//初始化围墙intwall[n+2][n+2]={{0}};//初始化围墙的二维数组for(i=1;i<=n;i++){for(j=1;j<=n;j++)wall[i][j]=1;}color(10);for(i=0;iprintf(\}gotoxy(n+3,3);//显示信息color(14);printf(\按a,b,c,d改变方向\\n\gotoxy(n+3,1);color(14);printf(\按任意键暂停,按1回到,按2选择退出\\n\gotoxy(n+5,3);color(14);printf(\food[0]=rand()%n+1;//随机发生食物}food[1]=rand()%n+1;gotoxy(food[0],food[1]);color(12);printf(\voidplay()//具体内容玩玩的过程{system(\inti,j;int**snake=null;//定义蛇的二维指针intfood[2];//食物的数组,food[0]代表横坐标,food[1]代表纵坐标intscore=0;//为罚球inttail[2];//此数组为了记录蛇的头的座标intnode=3;//蛇的节数charch='p';srand((unsigned)time(null));//随机数发生器的初始化函数init(food);snake=(int**)realloc(snake,sizeof(int*)*node);//发生改变snake所指内存区域的大小为node长度for(i=0;igotoxy(snake[i][0],snake[i][1]);color(14);printf(\}while(1)//步入消息循环{gotoxy(5,0);color(10);printf(\gotoxy(0,5);color(10);printf(\gotoxy(0,7);color (10);printf(\gotoxy(0,9);color(10);printf(\tail[0]=snake[node-1][0];//将蛇的后一节座标参数值tail数组tail[1]=snake[node-1][1];gotoxy(tail[0],tail[1]);color(0);printf(\for(i=node-1;i>0;i--)//蛇想前移动的关键算法,后一节的占有前一节的地址座标{snake[i][0]=snake[i-1][0];snake[i][1]=snake[i-1][1];gotoxy(snake[i][0],snake[i][1]);color(14);printf(\}if(kbhit())//抓取输出信息{gotoxy(0,n+2);ch=getche();}switch(ch){case'w':snake[0][1]--;break;case's':snake[0][1]++;break;case'a':snake[0][0]--;break;case'd':snake[0][0]++;break;case'1':boundary();break;case'2':end();brea k;default:break;}gotoxy(snake[0][0],snake[0][1]);color(14);printf(\sleep(abs(2 00-0.5*score));//并使随着分数的快速增长蛇的移动速度越来越快if(snake[0][0]==food[0]&&snake[0][1]==food[1])//吞下食物后蛇分数提1,蛇长提1{score++;//分数减少s=score;node++;//节数减少snake=(int**)realloc(snake,sizeof(int*)*node);snake[node-1]=(int*)malloc(sizeof(int)*2);food[0]=rand()%n+1;//产生随机数且要在围墙内部。
贪吃蛇C语言代码实现(难度可选)
贪吃蛇C语⾔代码实现(难度可选)本⽂实例为⼤家分享了C语⾔实现贪吃蛇的具体代码,供⼤家参考,具体内容如下/*****************************************************************************贪吃蛇(难度可选)**********************************制作者:Xu Lizi ⽇期:2012/12/31****************************部分函数有借鉴**********************************************************************************/#include<stdio.h>#include<conio.h>#include<string.h>#include<stdlib.h>#include<time.h>int snakey[100]={5,4,3,2,1}; /*定义蛇的横坐标*/int snakex[100]={1,1,1,1,1}; /*定义蛇的纵坐标,蛇头起始位置为(5,1)*/int life=0; /*定义蛇的⽣命,0表⽰存活,1表⽰死亡*/int lenght=5; /*定义蛇的长度,初始为5节*/char map[12][24]={"***********************", /*y*/"* *","* *","* *","* *","* *","* *","* *","* *","* *","* *",/*x*/ "***********************"};void put_money(int i,int j) /*放钱函数,使⽤随机数,随机出现⾷物*/{int x=0,y=0;srand(time(NULL));while ( (map[y][x]==003) || (map[y][x]==002) || (map[y][x]=='*') || ((x==i)&&(y==j)) ){x=rand()%21+1;y=rand()%10+1;}map[y][x]='$';return;}void output() /*输出*/{system("cls");int i,j;for(i=0; i<12; i++){for(j=0; j<23; j++) printf("%c", map[i][j]);printf("\n");}return;}void gameover() /*游戏结束*/{life=1;printf("笨蛋,输了吧\n");return;}void turn_up() /*向上移动*/{system("cls");int i;if ( (snakex[0]==1) || (map[snakex[0]-1][snakey[0]]==003) ) gameover(); else { if (map[snakex[0]-1][snakey[0]]=='$'){put_money( snakey[0], snakex[0]-1 );lenght++;map[snakex[lenght-1]][snakey[lenght-1]]=003;}for(i=lenght; i>0; i--){snakex[i]=snakex[i-1];snakey[i]=snakey[i-1];}map[snakex[lenght]][snakey[lenght]]=' ';snakex[0]--;for(i=lenght-1; i>0; i--) map[snakex[i]][snakey[i]]=003;map[snakex[0]][snakey[0]]=002;output();}return;}void turn_down() /*向下*/{system("cls");int i;if ( (snakex[0]==10) || (map[snakex[0]+1][snakey[0]]==003) ) gameover();else { if (map[snakex[0]+1][snakey[0]]=='$'){put_money(snakey[0],snakex[0]+1);lenght++;map[snakex[lenght-1]][snakey[lenght-1]]=003;}for(i=lenght; i>0; i--){snakex[i]=snakex[i-1];snakey[i]=snakey[i-1];}snakex[0]++;map[snakex[lenght]][snakey[lenght]]=' ';for(i=lenght-1; i>0; i--) map[snakex[i]][snakey[i]]=003;map[snakex[0]][snakey[0]]=002;output();}return;}void turn_left() /*向左*/{system("cls");int i;if ( (snakey[0]==1) || (map[snakex[0]][snakey[0]-1]==003) ) gameover();else { if (map[snakex[0]][snakey[0]-1]=='$'){put_money(snakey[0]-1,snakex[0]);lenght++;map[snakex[lenght-1]][snakey[lenght-1]]=003;}for(i=lenght; i>0; i--){snakex[i]=snakex[i-1];snakey[i]=snakey[i-1];}map[snakex[lenght]][snakey[lenght]]=' ';snakey[0]--;for(i=lenght-1; i>0; i--) map[snakex[i]][snakey[i]]=003;map[snakex[0]][snakey[0]]=002;output();}return;}void turn_right() /*向右*/{system("cls");int i;if ( (snakey[0]==21) || (map[snakex[0]][snakey[0]+1]==003) ) gameover();else {if (map[snakex[0]][snakey[0]+1]=='$'){put_money(snakey[0]+1,snakex[0]);lenght++;map[snakex[lenght-1]][snakey[lenght-1]]=003;}for(i=lenght; i>0; i--){snakex[i]=snakex[i-1];snakey[i]=snakey[i-1];}map[snakex[lenght]][snakey[lenght]]=' ';snakey[0]++;for(i=lenght-1; i>0; i--) map[snakex[i]][snakey[i]]=003;map[snakex[0]][snakey[0]]=002;output();}return;}int main(){int i,timeover,hard;long start;char name , direcation;printf("\n 向上移动:W ;向下移动:S ; 向左移动:A ;向右移动:D \n");printf("\t请选择难度(数字)\n\t分1~5级,分别代表\n\t1难,2中上,3中,4中下5,易:\n");scanf("%d",&hard);system("cls");for(i=1;i<5;i++) map[1][i]=003; /*输出蛇⾝*/map[1][5]=002; /*输出蛇头*/put_money(0,0);output();while(life!=1) /*当蛇死亡时结束循环*/{/*让蛇⾃动运⾏的函数******有借鉴*/timeover=1;start=clock();while((timeover=(clock()-start<=hard*100))&&!kbhit()); //难度设定if(timeover){direcation=getch();}/*让蛇⾃动运⾏的函数******有借鉴*/switch(direcation){case 'w':turn_up();break;case 's':turn_down();break;case 'a':turn_left();break;case 'd':turn_right();break;}}return 0;}更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
时间:2016/7/11 *
*
*
****************************************************************************
*/
#include "graphics.h"
#include <stdio.h>
c语言贪吃蛇UI界面版
c语言UI界面版贪吃蛇
使用ege图形库,游戏实现单双人功能。道具有炸弹,随机魔盒,炸弹。有随机障碍物生成。
不附加图片 。
/***************************************************************************
*
*
出品方:债组 *
int biteself();
void ();
void gamestart();
void cleanwall();
void updatewall();
void endgame();//iswin改变
void cantcrosswall();//撞墙,改变值
//UI函数
void prompt();
magic_x = rand() % 4;
i++;
if (magic_x == 0 || magic_x==1)
{
if (magic_xx == 1)
{
PlaySound("mgwall.wav", NULL, SND_FILENAME | SND_ASYNC);
score = score + add;
void gomagic();
void createfood();
void creatbomb();
void creatwall();
void drawwall();
void snakemove();
void pausegame();
void gamecircle();
void welcomeintogame();
#define D 2
#define L 3
#define R 4
#define A 5
#define S 6
#define W 7
#define Dd 8
#define VK_A 0x41//虚拟键值宏定义
#define VK_S 0x53
#define VK_W 0x57
#define VK_D 0X44
snake *head, *head1, *food, *bomb,*wall,*magic;
snake *q;//便利第一条蛇用到的指针
snake *q1;//遍历第二条蛇的时候用到的指针
int endgamestatus = 0; //游戏结束的情况,
int wall_suiji_u = 1111, wall_suiji_d = 2222, wall_suiji_r = 333, wall_suiji_l = 444;
muc1.OpenFile("bomm.mp3");
bj = newimage();
ss = newimage();
getimage(ss, "ss.png", 0, 0);//加载蛇身图片
if (oneortwo)
getimage(bj, "m.png", 0, 0);//加载背景图片
else
getimage(bj, "danren.png", 0, 0);//加载背景图片
int wall_u, wall_d, wall_l, wall_r;
int uwall_u, uwall_d, uwall_l, uwall_r;
int magic_x=0,magic_xx;
//后台的函数
void initsnake();
void initsnake1();
void creatmagic();
void pause();
void UI();
void Fence();
void welcometogame();
//后台函数
void gomagic()
{
int i = 5;
PIMAGE ss;
PIMAGE bj;
MUSIC muc;
MUSIC muc1;
muc.OpenFile("good.mp3");
int status, status1, sleeptime=130 ,bomb_suiji = 1234,wall_suiji=5678,magic_suiji=6589,magic_suiji1=3256;//每次运行的时间间隔
int oneortwo = 0;
int dwall=1,isdwall=0;
nexthead->next = head;
head = nexthead;
q = head;
while (q->next->next != NULL)
{
putimage(q->x, q->y, wd, hg, ss, 0, 0);
q = q->next;
}
putimage(q->next->x, q->next->y, wd, hg, bj, q->next->x, q->next->y);
snake * nexthead;
snake * nexthead1;
nexthead = (snake*)malloc(sizeof(snake));
nexthead1 = (snake*)malloc(sizeof(snake));
srand((time_t)magic_suiji);
wall_suiji = wall_suiji + 3652;
#define VK_N 0X4E
#define VK_M 0x4d
#define wd 10//蛇身的宽
#define hg 10//蛇身的高
//蛇身的一个节点
typedef struct SNAKE
{
int x;
int y;
struct SNAKE *next;
}snake;
//全局变量//
int score = 0, add = 10, score1 = 0, add1 = 10;;//总得分与每次吃食物得分。
#include<time.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
#include<windows.h>
#include <process.h>
#define printf outtext
int speed=5;
#define U 1