贪吃蛇c源代码(贪吃蛇c语言项目源代码)
admin 发布:2022-12-19 21:19 138
本篇文章给大家谈谈贪吃蛇c源代码,以及贪吃蛇c语言项目源代码对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
- 1、C语言的贪吃蛇源代码
- 2、求 贪吃蛇C语言代码
- 3、贪吃蛇c语言代码
- 4、求贪吃蛇C语言代码
- 5、c语言贪吃蛇源代码怎么用?
C语言的贪吃蛇源代码
//******友情提示:如想速度快点,请改小_sleep(500)函数中参数*****
#include stdio.h
#include stdlib.h
#include conio.h
#include string.h
#include time.h
const int H = 8; //地图的高
const int L = 16; //地图的长
char GameMap[H][L]; //游戏地图
int key; //按键保存
int sum = 1, over = 0; //蛇的长度, 游戏结束(自吃或碰墙)
int dx[4] = {0, 0, -1, 1}; //左、右、上、下的方向
int dy[4] = {-1, 1, 0, 0};
struct Snake //蛇的每个节点的数据类型
{
int x, y; //左边位置
int now; //保存当前节点的方向, 0,1,2,3分别为左右上下
}Snake[H*L];
const char Shead = '@'; //蛇头
const char Sbody = '#'; //蛇身
const char Sfood = '*'; //食物
const char Snode = '.'; //'.'在地图上标示为空
void Initial(); //地图的初始化
void Create_Food(); //在地图上随机产生食物
void Show(); //刷新显示地图
void Button(); //取出按键,并判断方向
void Move(); //蛇的移动
void Check_Border(); //检查蛇头是否越界
void Check_Head(int x, int y); //检查蛇头移动后的位置情况
int main()
{
Initial();
Show();
return 0;
}
void Initial() //地图的初始化
{
int i, j;
int hx, hy;
system("title 贪吃蛇"); //控制台的标题
memset(GameMap, '.', sizeof(GameMap)); //初始化地图全部为空'.'
system("cls");
srand(time(0)); //随机种子
hx = rand()%H; //产生蛇头
hy = rand()%L;
GameMap[hx][hy] = Shead;
Snake[0].x = hx; Snake[0].y = hy;
Snake[0].now = -1;
Create_Food(); //随机产生食物
for(i = 0; i H; i++) //地图显示
{
for(j = 0; j L; j++)
printf("%c", GameMap[i][j]);
printf("\n");
}
printf("\n小小C语言贪吃蛇\n");
printf("按任意方向键开始游戏\n");
getch(); //先接受一个按键,使蛇开始往该方向走
Button(); //取出按键,并判断方向
}
void Create_Food() //在地图上随机产生食物
{
int fx, fy;
while(1)
{
fx = rand()%H;
fy = rand()%L;
if(GameMap[fx][fy] == '.') //不能出现在蛇所占有的位置
{
GameMap[fx][fy] = Sfood;
break;
}
}
}
void Show() //刷新显示地图
{
int i, j;
while(1)
{
_sleep(500); //延迟半秒(1000为1s),即每半秒刷新一次地图
Button(); //先判断按键在移动
Move();
if(over) //自吃或碰墙即游戏结束
{
printf("\n**游戏结束**\n");
printf(" _\n");
getchar();
break;
}
system("cls"); //清空地图再显示刷新吼的地图
for(i = 0; i H; i++)
{
for(j = 0; j L; j++)
printf("%c", GameMap[i][j]);
printf("\n");
}
printf("\n小小C语言贪吃蛇\n");
printf("按任意方向键开始游戏\n");
}
}
void Button() //取出按键,并判断方向
{
if(kbhit() != 0) //检查当前是否有键盘输入,若有则返回一个非0值,否则返回0
{
while(kbhit() != 0) //可能存在多个按键,要全部取完,以最后一个为主
key = getch(); //将按键从控制台中取出并保存到key中
switch(key)
{ //左
case 75: Snake[0].now = 0;
break;
//右
case 77: Snake[0].now = 1;
break;
//上
case 72: Snake[0].now = 2;
break;
//下
case 80: Snake[0].now = 3;
break;
}
}
}
void Move() //蛇的移动
{
int i, x, y;
int t = sum; //保存当前蛇的长度
//记录当前蛇头的位置,并设置为空,蛇头先移动
x = Snake[0].x; y = Snake[0].y; GameMap[x][y] = '.';
Snake[0].x = Snake[0].x + dx[ Snake[0].now ];
Snake[0].y = Snake[0].y + dy[ Snake[0].now ];
Check_Border(); //蛇头是否越界
Check_Head(x, y); //蛇头移动后的位置情况,参数为: 蛇头的开始位置
if(sum == t) //未吃到食物即蛇身移动哦
for(i = 1; i sum; i++) //要从蛇尾节点向前移动哦,前一个节点作为参照
{
if(i == 1) //尾节点设置为空再移动
GameMap[ Snake[i].x ][ Snake[i].y ] = '.';
if(i == sum-1) //为蛇头后面的蛇身节点,特殊处理
{
Snake[i].x = x;
Snake[i].y = y;
Snake[i].now = Snake[0].now;
}
else //其他蛇身即走到前一个蛇身位置
{
Snake[i].x = Snake[i+1].x;
Snake[i].y = Snake[i+1].y;
Snake[i].now = Snake[i+1].now;
}
GameMap[ Snake[i].x ][ Snake[i].y ] = '#'; //移动后要置为'#'蛇身
}
}
void Check_Border() //检查蛇头是否越界
{
if(Snake[0].x 0 || Snake[0].x = H
|| Snake[0].y 0 || Snake[0].y = L)
over = 1;
}
void Check_Head(int x, int y) //检查蛇头移动后的位置情况
{
if(GameMap[ Snake[0].x ][ Snake[0].y ] == '.') //为空
GameMap[ Snake[0].x ][ Snake[0].y ] = '@';
else
if(GameMap[ Snake[0].x ][ Snake[0].y ] == '*') //为食物
{
GameMap[ Snake[0].x ][ Snake[0].y ] = '@';
Snake[sum].x = x; //新增加的蛇身为蛇头后面的那个
Snake[sum].y = y;
Snake[sum].now = Snake[0].now;
GameMap[ Snake[sum].x ][ Snake[sum].y ] = '#';
sum++;
Create_Food(); //食物吃完了马上再产生一个食物
}
else
over = 1;
}
求 贪吃蛇C语言代码
#include windows.h
#include stdlib.h
#include time.h
#include stdio.h
#include string.h
#include conio.h
#define N 21
int apple[3],num;
char score[3];
char tail[3];
void gotoxy(int x, int y) //输出坐标
{
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void color(int b) //颜色函数
{
HANDLE hConsole = GetStdHandle((STD_OUTPUT_HANDLE)) ;
SetConsoleTextAttribute(hConsole,b) ;
}
int Block(char head[2]) //判断出界
{
if ((head[0] 1) || (head[0] N) || (head[1] 1) || (head[1] N))
return 1;
return 0;
}
int Eat(char snake[2]) //吃了苹果
{
if ((snake[0] == apple[0]) (snake[1] == apple[1]))
{
apple[0] = apple[1] = apple[2] = 0;
gotoxy(N+44,10);
color(13);
printf("%d",score[0]*10);
color(11);
return 1;
}
return 0;
}
void Draw(char **snake, int len) //蛇移动
{
if (apple[2])
{
gotoxy(apple[1] * 2, apple[0]);
color(12);
printf("●");
color(11);
}
gotoxy(tail[1] * 2, tail[0]);
if (tail[2])
{
color(num);
printf("★");
color(num);
}
else
printf("■");
gotoxy(snake[0][1] * 2, snake[0][0]);
color(num);
printf("★");
color(num);
putchar('\n');
}
char** Move(char **snake, char dirx, int *len) //控制方向
{
int i, full = Eat(snake[0]);
memcpy(tail, snake[(*len)-1], 2);
for (i = (*len) - 1; i 0; --i)
memcpy(snake[i], snake[i-1], 2);
switch (dirx)
{
case 'w': case 'W': --snake[0][0]; break;
case 's': case 'S': ++snake[0][0]; break;
case 'a': case 'A': --snake[0][1]; break;
case 'd': case 'D': ++snake[0][1]; break;
default: ;
}
if (full)
{
snake = (char **)realloc(snake, sizeof(char *) * ((*len) + 1));
snake[(*len)] = (char *)malloc(sizeof(char) * 2);
memcpy(snake[(*len)], tail, 2);
++(*len);
++score[0];
if(score[3] 16)
++score[3];
tail[2] = 1;
}
else
tail[2] = 0;
return snake;
}
void init(char plate[N+2][N+2], char ***snake_x, int *len) //初始化
{
int i, j;
char **snake = NULL;
*len = 3;
score[0] = score[3] =3;
snake = (char **)realloc(snake, sizeof(char *) * (*len));
for (i = 0; i *len; ++i)
snake[i] = (char *)malloc(sizeof(char) * 2);
for (i = 0; i 3; ++i)
{
snake[i][0] = N/2 + 1;
snake[i][1] = N/2 + 1 + i;
}
for (i = 1; i = N; ++i)
for (j = 1; j = N; ++j)
plate[i][j] = 1;
apple[0] = rand()%N + 1; apple[1] = rand()%N + 1;
apple[2] = 1;
for (i = 0; i N + 2; ++i)
{
gotoxy(0, i);
for (j = 0; j N + 2; ++j)
{
switch (plate[i][j])
{
case 0:
color(12);printf("□");color(11); continue;
case 1: printf("■"); continue;
default: ;
}
}
putchar('\n');
}
for (i = 0; i (*len); ++i)
{
gotoxy(snake[i][1] * 2, snake[i][0]);
printf("★");
}
putchar('\n');
*snake_x = snake;
}
void Manual()
{
gotoxy(N+30,2);
color(10);
printf("按 W S A D 移动方向");
gotoxy(N+30,4);
printf("按 space 键暂停");
gotoxy(N+30,8);
color(11);
printf("历史最高分为: ");
color(12);
gotoxy(N+44,8);
printf("%d",score[1]*10);
color(11);
gotoxy(N+30,12);
printf("你现在得分为: 0");
}
int File_in() //取记录的分数
{
FILE *fp;
if((fp = fopen("C:\\tcs.txt","a+")) == NULL)
{
gotoxy(N+18, N+2);
printf("文件不能打开\n");
exit(0);
}
if((score[1] = fgetc(fp)) != EOF);
else
score[1] = 0;
return 0;
}
int File_out() //存数据
{
FILE *fp;
if(score[1] score[0])
{gotoxy(10,10);
color(12);
puts("闯关失败 加油耶");
gotoxy(0,N+2);
return 0;
}
if((fp = fopen("C:\\tcs.txt","w+")) == NULL)
{
printf("文件不能打开\n");
exit(0);
}
if(fputc(--score[0],fp)==EOF)
printf("输出失败\n");
gotoxy(10,10);
color(12);
puts("恭喜您打破记录");
gotoxy(0,N+2);
return 0;
}
void Free(char **snake, int len) //释放空间
{
int i;
for (i = 0; i len; ++i)
free(snake[i]);
free(snake);
}
int main(void)
{
int len;
char ch = 'g';
char a[N+2][N+2] = {{0}};
char **snake;
srand((unsigned)time(NULL));
color(11);
File_in();
init(a, snake, len);
Manual();
while (ch != 0x1B) // 按 ESC 结束
{
Draw(snake, len);
if (!apple[2]) {
apple[0] = rand()%N + 1;
apple[1] = rand()%N + 1;
apple[2] = 1;
num++;
if(num8)
num=0;
}
Sleep(200-score[3]*10);
setbuf(stdin, NULL);
if (kbhit())
{
gotoxy(0, N+2);
ch = getche();
}
snake = Move(snake, ch, len);
if (Block(snake[0])==1)
{
gotoxy(N+2, N+2);
puts("你输了");
File_out();
Free(snake, len);
getche();
exit(0);
}
}
Free(snake, len);
exit(0);
}
贪吃蛇c语言代码
#includestdio.h
#includestdlib.h
#includeWindows.h
#includeconio.h
#includetime.h
char gamemap[20][40];//游戏地图大小 20*40
int score=0;//当前分数
//记录蛇的结点
int x[800];//每个结点的行编号
int y[800];//每个结点的列编号
int len = 0;//蛇的长度
//记录水果信息
int fx=0;//食物的横坐标
int fy=0;//食物的纵坐标
int fcount=0;//食物的数目
//主要函数操作
void createfood();//生成食物
void PrintgameMap(int x[],int y[]);//画游戏地图
void move(int x[],int y[]);//移动蛇
int main()
{
srand(time(NULL));
//初始化蛇头和身体的位置,默认刚开始蛇长为2
x[len] = 9;
y[len] = 9;
len++;
x[len] = 9;
y[len] = 8;
len++;
createfood();
PrintgameMap(x,y);
move(x,y);
return 0;
}
void createfood()
{
if(0==fcount)
{
int tfx=rand()%18+1;
int tfy=rand()%38+1;
int i,j;
int have=0;//为0表示食物不是食物的一部分
for(i=0;ilen;i++)
{
for(j=0;jlen;j++)
{
if(x[i]==fxy[j]==fy)
{
have=1;
break;
}
else
{
have=0;
}
}
if(1==have)//若为蛇的一部分,执行下一次循环
{
continue;
}
else//否则生成新的水果
{
fcount++;
fx=tfx;
fy=tfy;
break;
}
}
}
}
//游戏地图
void PrintgameMap(int x[],int y[])
{
int snake = 0,food=0;
int i, j;
//画游戏地图,并画出蛇的初始位置
for (i = 0; i 20; i++)
{
for (j = 0; j 40; j++)
{
if (i == 0 j = 1 j = 38)
{
gamemap[i][j] = '=';
}
else if (i == 19 j = 1 j = 38)
{
gamemap[i][j] = '=';
}
else if (j == 0 || j == 39)
{
gamemap[i][j] = '#';
}
else
{
gamemap[i][j] = ' ';
}
//判断蛇是否在当前位置
int k;
for ( k = 0; k len; k++)
{
if (i == x[k]j == y[k])
{
snake = 1;
break;
}
else
{
snake = 0;
}
}
{
if(fcountfx==ify==j)
{
food=1;
}
else
{
food=0;
}
}
//若蛇在当前位置
if (1==snake )
{
printf("*");
}
else if(1==food)
{
printf("f");
}
//若蛇不在当前位置并且当前位置没有水果
else
{
printf("%c", gamemap[i][j]);
}
}
printf("\n");
}
printf("score:%d",score);
}
//移动
void move(int x[],int y[])
{
char s;
s=getch();
int move=0,beat=0;
while (1)
{
int cx[800];
int cy[800];
memcpy(cx, x, sizeof(int)*len);
memcpy(cy, y, sizeof(int)*len);
//头
if (s=='w')
{
x[0]--;
move=1;
if(x[0]=0)
{
printf("Game over\n");
break;
}
}
else if (s=='s')
{
x[0]++;
move=1;
if(x[0]=19)
{
printf("Game over\n");
break;
}
}
else if (s=='a')
{
y[0] --;
move=1;
if(y[0]=0)
{
printf("Game over\n");
break;
}
}
else if (s=='d')
{
y[0]++;
move=1;
if(y[0]=39)
{
printf("Game over\n");
break;
}
}
//身体
int i;
for ( i = 1; i len; i++)
{
x[i] = cx[i - 1];
y[i] = cy[i - 1];
}
for(i=1;ilen;i++)//要是咬到了自己
{
if(x[0]==x[i]y[0]==y[i])
{
beat=1;
}
else
{
beat=0;
}
}
if(1==beat)
{
printf("Game over\n");
break;
}
if(1==move)
{
if(fcountx[0]==fxy[0]==fy)//如果吃到了果子
{
//拷贝当前蛇头地址到第二个结点
memcpy(x+1,cx,sizeof(int)*len);
memcpy(y+1,cy,sizeof(int)*len);
len++;
fcount--;
fx=0;
fy=0;
score++;
createfood();
}
Sleep(70);
system("cls");
PrintgameMap( x, y);
}
else
continue;
if(kbhit())//判断是否按下按键
{
s=getch();
}
}
}
求贪吃蛇C语言代码
// 2.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#includestdio.h
#includeconio.h
#includetime.h
#includewindows.h
#includestdlib.h
int length=1;//蛇的当前长度,初始值为1
int line[100][2];//蛇的走的路线
int head[2]={40,12};//蛇头
int food[2];//食物的位置
char direction;//蛇运动方向
int x_min=1,x_max=77, y_min=2, y_max=23;//设置蛇的运动区域
int tail_before[2]={40,12};//上一个状态的蛇尾
char direction_before='s';//上一个状态蛇的运动方向
int live_death=1;//死活状态,0死,1活
int eat_flag=0;//吃食物与否的状态。0没吃 1吃了
int max=0;
int delay;//移动延迟时间
void gotoxy(int x, int y)//x为列坐标,y为行坐标
{
COORD pos = {x,y};
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hOut, pos);
}
void hidden()//隐藏光标
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cci;
GetConsoleCursorInfo(hOut,cci);
cci.bVisible=0;//赋1为显示,赋0为隐藏
SetConsoleCursorInfo(hOut,cci);
}
void update_score()
{
gotoxy(2,1);
printf("我的分数:%d",length);
gotoxy(42,1);
printf("最高记录:%d",max);
}
void create_window()
{
gotoxy(0,0);
printf("╔══════════════════╦═══════════════════╗");
printf("║ ║ ║");
printf("╠══════════════════╩═══════════════════╣");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("║ ║");
printf("╚══════════════════════════════════════╝");
}
void update_line()
{
int i;
if(eat_flag==0)//吃了食物就不用记住上一个状态的蛇尾,否则会被消掉
{
tail_before[0]=line[0][0];//记住上一个状态的蛇尾
tail_before[1]=line[0][1];
for(i=0;ilength-1;i++)//更新蛇头以后部分
{
line[i][0]=line[i+1][0];
line[i][1]=line[i+1][1];
}
line[length-1][0]=head[0];//更新蛇头
line[length-1][1]=head[1];
}
}
void initial()
{
FILE *fp;
gotoxy(head[0],head[1]);
printf("蛇");
line[0][0]=head[0];//把蛇头装入路线
line[0][1]=head[1];
if((fp=fopen("highest","r"))==NULL)
{
fp=fopen("highest","w");
fprintf(fp,"%d",0);
max=0;
fclose(fp);
}//第一次使用时,初始化奖最高分为0
else
{
fp=fopen("highest","r");
fscanf(fp,"%d",max);
}
update_score();
}
void createfood()
{
int flag,i;
srand((unsigned)time(NULL));
for(;;)
{
for(;;)
{
food[0]=rand()%(x_max+1);
if(food[0]%2==0 food[0]x_min)
break;
}//产生一个偶数横坐标
for(;;)
{
food[1]=rand()%(y_max);
if(food[1]y_min)
break;
}
for(i=0,flag=0;ilength;i++)//判断产生的食物是否在蛇身上,在flag=1,否则为0
if(food[0]==line[i][0] food[1]==line[i][1])
{ flag=1; break; }
if(flag==0)// 食物不在蛇身上 结束循环
break;
}
gotoxy(food[0],food[1]);
printf("蛇");
}
void show_snake()
{
gotoxy(head[0],head[1]);
printf("蛇");
if(eat_flag==0)//没吃食物时消去蛇尾
{
gotoxy(tail_before[0],tail_before[1]);
printf(" ");//消除蛇尾
}
else
eat_flag=0;//吃了食物就回到没吃状态
}
char different_direction(char dir)
{
switch(dir)
{
case 'a': return 'd';
case 'd': return 'a';
case 'w': return 's';
case 's': return 'w';
}
return 0;
}
void get_direction()
{
direction_before=direction;//记住蛇上一个状态的运动方向
while(kbhit()!=0) //调试
direction=getch();
if( direction_before == different_direction(direction) || (direction!='a' direction!='s' direction!='d' direction!='w') ) //新方向和原方向相反,或获得的方向不是wasd时,保持原方向
direction=direction_before;
switch(direction)
{
case 'a': head[0]-=2; break;
case 'd': head[0]+=2; break;
case 'w': head[1]--; break;
case 's': head[1]++; break;
}
}
void live_state()//判断蛇的生存状态
{
FILE *fp;
int i,flag;
for(i=0,flag=0;ilength-1;i++)//判断是否自己咬到自己
if( head[0]==line[i][0] head[1]==line[i][1])
{
flag=1;
break;
}
if(head[0]=x_min || head[0]=x_max || head[1]=y_min || head[1]=y_max || flag==1)
{
system("cls");
create_window();
update_score();
gotoxy(35,12);
printf("游戏结束!\n");
Sleep(500);
live_death=0;
fp=fopen("highest","w");
fprintf(fp,"%d",max);//保存最高分
}
}
void eat()
{
if(head[0]==food[0]head[1]==food[1])
{
length++;
line[length-1][0]=head[0];//更新蛇头
line[length-1][1]=head[1];
eat_flag=1;
createfood();
if(lengthmax)
max=length;
update_score();
if(delay100)
delay-=30;//加速
}
}
void main()
{
int x=0,y=0;
// int i;
hidden();//隐藏光标
create_window();
initial();
createfood();
for(direction='s',delay=600;;)
{
get_direction();
eat();
update_line();
live_state();//判断生死状态
if(live_death==1)
{
show_snake();
}
else
break;
Sleep(delay);
}
}
c语言贪吃蛇源代码怎么用?
C语言贪吃蛇源代码必须经过相应的C/C++编译器编译成EXE文件后才能运行。
由于我们通常使用的操作系统是Windows系统,而在该系统下最长用的C/C++编译器是VC++编译器,目前在大专院校常用的版本还是VC++6.0
下面就以VC++6.0来说明编译过程:
1.在VC++6.0中通过“File”菜单下的 “Open”子菜单打开贪吃蛇代码
2.在VC++6.0中通过“Build”菜单下的 “Compile xxxx.xx”子菜单编译贪吃蛇代码
3.在VC++6.0中通过“Build”菜单下的 “Execute xxxx.exe”子菜单运行贪吃蛇程序
附:在VC++6环境下可运行的C/C++贪吃蛇源代码(无版权,自己编写,欢迎任意修改拷贝)
/*
C/C++贪吃蛇游戏,zjlj,2015.3.16
*/
#define DEBUG 0 //当程序在调试阶段时 DEBUG为 1
#includeiostream
#includewindows.h
#includetime.h
#includeconio.h
using namespace std;
void readini(FILE **fphead, int *score, char *argv[]) //创建或打开一个和运行文件对应的ini文件,读取最高纪录
{
char filename[200],*pfilename;
int flag=-1,i;
strcpy(filename,argv[0]);
for(i=0;filename[i]!='\0';i++)
{
if ('.'==filename[i])flag=1;
}
if(1==flag)
{
filename[i-1]='i';
filename[i-2]='n';
filename[i-3]='i';
}
else
{
filename[i]='.';
filename[i+1]='i';
filename[i+2]='n';
filename[i+3]='i';
filename[i+4]='\0';
}
for(;filename[i]!='\\'i=0;i--)pfilename=filename[i];
if ( (*fphead=fopen(pfilename, "rb+"))==NULL)
{
if ( (*fphead=fopen(pfilename, "wb+"))==NULL)
{
printf("无法创建或打开\"%s\"文件\n",pfilename);
system("pause");
exit(0);
}
}
else
{
fread(score,sizeof(int),1,*fphead);
}
}
void writeini(FILE **fphead, int *score, char *argv[]) //打开一个和运行文件对应的ini文件,写入最高纪录
{
char filename[200],*pfilename;
int flag=-1,i;
strcpy(filename,argv[0]);
for(i=0;filename[i]!='\0';i++)
{
if ('.'==filename[i])flag=1;
}
if(1==flag)
{
filename[i-1]='i';
filename[i-2]='n';
filename[i-3]='i';
}
else
{
filename[i]='.';
filename[i+1]='i';
filename[i+2]='n';
filename[i+3]='i';
filename[i+4]='\0';
}
for(;filename[i]!='\\'i=0;i--)pfilename=filename[i];
if ( (*fphead=fopen(pfilename, "wb+"))==NULL)
{
printf("无法写入\"%s\"文件,磁盘写保护!\n",pfilename);
system("pause");
exit(0);
}
else
{
rewind(*fphead);
fwrite(score,sizeof(int),1,*fphead);
fclose(*fphead);
}
}
void gotoxy(int x,int y)//光标定位,光标定位函数SetConsoleCursorPosition是左上角位置是0,0然后向左向下延伸
{
COORD pos;
pos.X=2*y;
pos.Y=x;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
}
void color(int a)//颜色函数
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);
}
void Refresh(int q[][22], int grade, int gamespeed, int length,int score) // 输出贪吃蛇棋盘
{
int i,j;
for(i=0;i22;i++)
{
for(j=0;j22;j++)
{
if(q[i][j]==0)//输出棋盘空白
{
gotoxy(i,j);
color(11);
cout"■";
}
if(q[i][j]==1||q[i][j]==2)//输出棋盘墙壁
{
gotoxy(i,j);
color(11);
cout"□";
}
if(q[i][j]==3)//输出蛇头
{
gotoxy(i,j);
color(14);
cout"★";
}
if(q[i][j]==4)//输出蛇身
{
gotoxy(i,j);
color(12);
cout"◆";
}
if(q[i][j]==5)//输出果子
{
gotoxy(i,j);
color(12);
cout"●";
}
}
if(i==0) cout "\t***********************";
if(i==1) cout "\t等级为:" grade;//显示等级
if(i==3) cout "\t自动前进时间";
if(i==4) cout "\t间隔为:" gamespeed "ms";//显示时间
if(i==6) cout "\t历史最高分为:" score "分";
if(i==7) cout "\t你现在得分为:" (length+(grade-1)*8)*10 "分";
if(i==8) cout "\t**********************";
if(i==9) cout "\t游戏说明:";
if(i==10) cout "\t(1)用小键盘方向键控制";
if(i==11) cout "\t蛇头运动方向;";
if(i==12) cout "\t(2)蛇每吃一个果子蛇身";
if(i==13) cout "\t增加一节;";
if(i==14) cout "\t(3)蛇咬到自己或碰到墙";
if(i==15) cout "\t壁游戏结束。";
if(i==18) cout "\t**********************";
if(i==19) cout "\tC/C++语言作业:";
if(i==20) cout "\tzjlj,2015.03.16 ";
}
}
int main(int argc, char *argv[]){
int tcsQipan[22][22]; // 贪吃蛇棋盘是一个二维数组(如22*22,包括墙壁)
int i,j,score,directiontemp;
FILE *fpini;//*fpini 信息文件
readini(fpini, score, argv);//读取ini文件的最高纪录
if (score0)//最高成绩小于零设置为零,初建文件会是负数
score=0;
while(1)
{
for(i=1;i=20;i++)
for(j=1;j=20;j++)
tcsQipan[i][j]=0; //贪吃蛇棋盘相应坐标标上中间空白部分的标志0
for(i=0;i=21;i++)
tcsQipan[0][i] = tcsQipan[21][i] = 1; //贪吃蛇棋盘相应坐标标上上下墙壁的标志1
for(i=1;i=20;i++)
tcsQipan[i][0] = tcsQipan[i][21] = 2; //贪吃蛇棋盘相应坐标标上左右墙壁的标志2
int tcsZuobiao[2][500]; //蛇的坐标数组
for(i=0; i4; i++)
{
tcsZuobiao[0][i] = 1;//蛇身和蛇头的x坐标
tcsZuobiao[1][i] = i + 1;//蛇身和蛇头的y坐标
}
int head = 3,tail = 0;//标示蛇头和蛇尾的数组偏移量
for(i=1;i=3;i++)
tcsQipan[1][i]=4; //蛇身
tcsQipan[1][4]=3; //蛇头
int x1, y1; // 随机出果子
srand(time(0));//设置随机种子
do
{
x1=rand()%20+1;
y1=rand()%20+1;
}
while(tcsQipan[x1][y1]!=0);//如果不是在空白处重新出果子
tcsQipan[x1][y1]=5;//贪吃蛇棋盘相应坐标标上果子的标志5
color(12);
cout"\n\n\t\t\t\t贪吃蛇游戏即将开始 !"endl;//准备开始
long start,starttemp;
int grade = 1, length = 4; //设置初始等级和蛇的初始长度
int gamespeed = 500; //设置初始前进时间间隔
for(i=3;i=0;i--)
{
start=clock();
while(clock()-start=1000);
system("cls");
if(i0)
cout "\n\n\t\t\t\t进入倒计时:" i endl; //倒计时显示
else
Refresh(tcsQipan,grade,gamespeed,length,score); //初始棋盘显示
}
int timeover=1,otherkey=1;//初始化超时时间和按键判断参数
char direction = 77; // 设置初始情况下,向右运动
int x=tcsZuobiao[0][head],y=tcsZuobiao[1][head];//保存蛇头坐标到x,y变量
while(1)//运行一局游戏
{
start = clock();
while((timeover=((starttemp=clock())-start=gamespeed))!kbhit());//如果有键按下或时间超过自动前进时间间隔则终止循环
if(direction==72||direction==80||direction==75 ||direction==77)
directiontemp=direction;//保留上一次方向按键
//starttemp=gamespeed+start-starttemp;//保留停留时间
if(timeover)
{
#if (DEBUG==1)
direction = getch();//调试代码
#else
if((direction =getch())==-32)
direction = getch();
#endif
}
#if (DEBUG==1)//调试代码
start=clock();
while(clock()-start=2000);
gotoxy(24,4);
cout "\t按键ASCII代码"(int)direction" "endl;
#endif
if(!(direction==72||direction==80||direction==75 ||direction==77))
{
otherkey=0;// 按键非方向键,otherkey设置为0
}
else
{
otherkey=1;// 按键为方向键,otherkey设置为1
}
if(direction==72 directiontemp==80)//忽略反方向按键
{
direction=32;
otherkey=0;
//start = clock();
//while(clock()-start=starttemp);
}
else if(direction==80 directiontemp==72)
{
direction=32;//设置按键为非方向键
otherkey=0;// 按键为非方向键,otherkey设置为0
// start = clock();
//while(clock()-start=starttemp);//补偿等待时间
}
else if(direction==75 directiontemp==77)
{
direction=32;
otherkey=0;
//start = clock();
//while(clock()-start=starttemp);
}
else if(direction==77 directiontemp==75)
{
direction=32;
otherkey=0;
//start = clock();
//while(clock()-start=starttemp);
}
switch(direction)//判断方向键
{
case 72: x= tcsZuobiao[0][head]-1; y= tcsZuobiao[1][head];break; // 向上
case 80: x= tcsZuobiao[0][head]+1; y= tcsZuobiao[1][head];break; // 向下
case 75: x= tcsZuobiao[0][head]; y= tcsZuobiao[1][head]-1;break; // 向左
case 77: x= tcsZuobiao[0][head]; y= tcsZuobiao[1][head]+1;break; // 向右
default: break;
}
if(x==0 || x==21 ||y==0 || y==21) // 蛇头碰到墙壁,结束本局游戏
{
gotoxy(22,12);
cout "\t游戏已结束!" endl;
if(score=(length+(grade-1)*8)*10)//判断是否破记录
{
gotoxy(10,7);
color(12);
cout "闯关失败 加油耶!" endl;
fclose(fpini);//关闭ini文件
}
else
{
gotoxy(10,7);
color(12);
cout "恭喜您打破记录" endl;
score=(length+(grade-1)*8)*10;
writeini(fpini, score, argv);//写入ini文件的最高纪录
}
gotoxy(23,12);
cout "按回车键重新开始,按ESC退出游戏" endl;//显示的提示
break;//退出该局游戏
}
if(tcsQipan[x][y]!=0!(x==x1y==y1)tcsQipan[x][y]!=3) // 蛇头碰到蛇身,结束本局游戏
{
gotoxy(22,12);
cout "\t游戏已结束!" endl;
if(score=(length+(grade-1)*8)*10)//判断是否破记录
{
gotoxy(10,7);
color(12);
cout "闯关失败 加油耶!" endl;
fclose(fpini);//关闭ini文件
}
else
{
gotoxy(10,7);
color(12);
cout "恭喜您打破记录" endl;
score=(length+(grade-1)*8)*10;
writeini(fpini, score, argv);//写入ini文件的最高纪录
}
gotoxy(23,12);
cout "按回车键重新开始,按ESC退出游戏" endl;//显示的提示
break;//退出该局游戏
}
/*
游戏运行时的核心算法开始
*/
if(x==x1 y==y1) // 吃果子,长度加1
{
length ++;
if(length=8)//长度大于等于8重新计算长度,等级加1
{
length -= 8;//重新计算长度
grade ++;//等级加1
if(gamespeed50)//控制最快速度为50
gamespeed = 550 - grade * 50; // 改变自动前进时间间隔
}
tcsQipan[x][y]= 3;//贪吃蛇棋盘相应坐标现在蛇头标志改为蛇头标志3
tcsQipan[tcsZuobiao[0][head]][tcsZuobiao[1][head]] = 4;//贪吃蛇棋盘相应坐标原来蛇头标志改为蛇身标志4
head = (head+1)%400;//防止数组越界
tcsZuobiao[0][head] = x;//蛇头的x坐标
tcsZuobiao[1][head] = y;//蛇头的y坐标
do//随机出果子
{
x1=rand()%20+1;
y1=rand()%20+1;
}
while(tcsQipan[x1][y1]!=0);//如果不是在空白处重新出果子
tcsQipan[x1][y1]=5;//贪吃蛇棋盘相应坐标标上果子的标志5
gotoxy(22,12);
cout "\t游戏进行中!" endl;
Refresh(tcsQipan,grade,gamespeed,length,score);
}
else // 不吃果子
{
if(otherkey)
{
tcsQipan [tcsZuobiao[0][tail]][tcsZuobiao[1][tail]]=0;
tail=(tail+1)%400;//防止数组越界
tcsQipan [tcsZuobiao[0][head]][tcsZuobiao[1][head]]=4;
head=(head+1)%400;//防止数组越界
tcsZuobiao[0][head]=x;//蛇头的x坐标
tcsZuobiao[1][head]=y;//蛇头的y坐标
tcsQipan[tcsZuobiao[0][head]][tcsZuobiao[1][head]]=3;
gotoxy(22,12);
cout "\t游戏进行中!" endl;
Refresh(tcsQipan,grade,gamespeed,length,score);
}
else
{
gotoxy(22,12);
cout "\t游戏暂停中!" endl;
}
}
/*
游戏运行时的核心算法结束
*/
}
while(1)
{
while(!kbhit());
if((direction =getch())==13)//按回车键开始下一局
break;
if(direction ==27)//按ESC退出游戏
exit(0);
}
system("cls");//清除屏幕重新开始
}
return 0;
}
贪吃蛇c源代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于贪吃蛇c语言项目源代码、贪吃蛇c源代码的信息别忘了在本站进行查找喔。
版权说明:如非注明,本站文章均为 AH站长 原创,转载请注明出处和附带本文链接;
- 上一篇:qqc源代码服务器端(腾讯源代码)
- 下一篇:简单游戏编程代码(简单游戏编程源代码)
相关推荐
- 04-25b2b2c源代码(什么是B2B2C)[20240425更新]
- 04-25个人管理系统手机版源代码(管理app源码)[20240425更新]
- 04-25动态网站源代码(动态网站源代码能爬下来吗)[20240425更新]
- 04-25springmvc源代码(springMVC源码)[20240425更新]
- 04-25手机系统源代码获取(如何用手机查看源代码)[20240425更新]
- 04-25e语言小程序代码大全(小程序示例代码)[20240425更新]
- 04-25C语言学生信息插入代码(添加学生信息c语言)[20240425更新]
- 04-25站内搜索引擎源代码(内部搜索引擎)[20240425更新]
- 04-25神兽游戏源代码(神兽网络游戏)[20240425更新]
- 04-25da14680源代码(da14580 开发板)[20240425更新]
取消回复欢迎 你 发表评论:
- 标签列表
- 最近发表
- 友情链接