
//DEV C++ 通过
/
program by wlfryq 71693456@qqcom
/
#include <stdioh>
#include <stdlibh>
#include <conioh>
#include <windowsh>
#include <timeh>
#include <directh>
#include <stdboolh>
#define W 80 //屏幕宽度
#define H 37 //屏幕高度
#define SNAKE_ALL_LENGTH 200 //蛇身最长为
void CALLBACK TimerProc(
HWND hwnd,
UINT message,
UINT idTimer,
DWORD dwTime);
void start();
struct MYPOINT
{
int x;
int y;
} s[SNAKE_ALL_LENGTH] , head, end, food;
int max_count=0; //历史最高分,如果count>max_count, 则max_count=count
int old_max_count=0; //历史最高分,不会变动, 用于死亡时判断max_count是否大于old_max_count,如果大于,则写入文件
int count=0; //得分
int len=20; //当前蛇身长度
int direct=0; //方向: 0-向右, 1-向下, 2-向左, 3-向上
int speed=200; //速度:毫秒
bool isfood=false; //食物是否存在
int timerID;
bool stop=false; //暂停
char ini_path; //数据文件绝对路径
void setxy(int x, int y) //设置CMD窗口光标位置
{
COORD coord = {x, y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void hide_cursor() //隐藏CMD窗口光标
{
CONSOLE_CURSOR_INFO cci;
ccibVisible = FALSE;
ccidwSize = sizeof(cci);
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorInfo(handle, &cci);
}
void set_food() //设置食物坐标
{
if(isfood==true)
{
return;
}
int x,y,i;
bool flag=false;
while(1)
{
flag=false;
x=rand()%(W-14)+6;
y=rand()%(H-12)+6;
for(i=0;i<len;i++) //判断食物是否落在蛇身上
{
if(s[i]x==x && s[i]y==y)
{
flag=true;
break;
}
}
if(flag==true)
{
continue;
}
else
{
foodx=x;
foody=y;
break;
}
}
setxy(foodx,foody);
printf("");
isfood=true;
}
void check_board() //检测蛇身是否越界和相交
{
int i;
if(s[0]x>=W-3 || s[0]x<=2 || s[0]y>=H-1 || s[0]y<=2)
{
setxy(W/2-5,0);
printf("game over\n");
stop=true;
if(old_max_count<max_count)
{
char t[5]={'\0'};
sprintf(t,"%d",max_count);
WritePrivateProfileString("MAX_COUNT","max_count",t,ini_path);
}
}
for(i=1;i<len;i++)
{
if(s[i]x==s[0]x && s[i]y==s[0]y)
{
setxy(W/2-5,0);
printf("game over\n");
stop=true;
if(old_max_count<max_count)
{
char t[5]={'\0'};
sprintf(t,"%d",max_count);
WritePrivateProfileString("MAX_COUNT","max_count",t,ini_path);
}
break;
}
}
if(stop==true)
{
KillTimer(NULL,timerID);
int c;
while(1)
{
fflush(stdin);
c=_getch();
if(c=='n' || c=='N')
{
start();
}
else if(c=='q' || c=='Q')
{
exit(0);
}
else continue;
}
}
}
void printf_body(bool is_first) //打印蛇身
{
if(is_first==true) //如果是第一次打印蛇身
{
int i;
for(i=0;i<len;i++)
{
setxy(s[i]x,s[i]y);
printf("O");
}
}
else //如果不是第一次打印蛇身
{
setxy(endx,endy);
printf(" ");
setxy(s[0]x,s[0]y);
printf("O");
}
if(foodx==s[0]x && foody==s[0]y) //如果吃到食物
{
count++;
isfood=false; //重置食物
set_food();
len++;
KillTimer(NULL,timerID);
if(speed>100) speed-=10;
else if(speed>50) speed-=5;
else if(speed>30) speed-=2;
else if(speed>16) speed-=1;
else ;
setxy(0,0);
if(max_count<count) max_count=count;
printf(" speed : %d ms score : %d best score:%d ",speed,count,max_count);
timerID=SetTimer(NULL,001,speed,TimerProc);
}
}
void change_body_pos(int x, int y) //改变蛇身的坐标数据
{
endx=s[len-1]x;
endy=s[len-1]y;
int i;
for(i=len-1;i>0;i--)
{
s[i]x=s[i-1]x;
s[i]y=s[i-1]y;
}
s[0]x=x;
s[0]y=y;
}
void CALLBACK TimerProc(
HWND hwnd,
UINT message,
UINT idTimer,
DWORD dwTime)
{
switch(direct)
{
case 0:
headx++;
change_body_pos(headx,heady);
printf_body(false);
check_board();
break;
case 1:
heady++;
change_body_pos(headx,heady);
printf_body(false);
check_board();
break;
case 2:
headx--;
change_body_pos(headx,heady);
printf_body(false);
check_board();
break;
case 3:
heady--;
change_body_pos(headx,heady);
printf_body(false);
check_board();
break;
}
}
void start()
{
int i;
KillTimer(NULL,timerID);
count=0; //得分
len=20; //当前蛇身长度
direct=0; //方向: 0-向右, 1-向下, 2-向左, 3-向上
speed=200; //速度:毫秒
isfood=false; //食物是否存在
stop=false; //停止
system("cls");
setxy(1,4);
printf("┌─────────────────────────────────────┐\n");
for(i=0;i<33;i++)
{
printf(" │ │\n");
}
printf(" └─────────────────────────────────────┘");
headx=len-1+5;
heady=H/2;
for(i=0;i<len;i++)
{
s[i]x=headx-i;
s[i]y=heady;
}
setxy(0,0);
printf(" speed : %d:ms score : %d best score:%d ",speed,count,max_count);
printf_body(true);
set_food();
timerID=SetTimer(NULL,001,speed,TimerProc);
int c;
MSG msg;
while(GetMessage(&msg,NULL,0,0))
{
if(stop==true) break;
if(_kbhit()) //如果按下的是方向键或功能键, _getch()要调用两次,第一次返回0XE0或0
{
fflush(stdin);
c=_getch(); //上: 72 下:80 左:75 右:77
if(c==0XE0 || c==0)
{
c=_getch();
if(c==72 && direct!=1 && direct!=3)
{
direct=3;
}
else if(c==80 && direct!=1 && direct!=3)
{
direct=1;
}
else if(c==75 && direct!=0 && direct!=2)
{
direct=2;
}
else if(c==77 && direct!=0 && direct!=2)
{
direct=0;
}
}
else if(c==' ')
{
setxy(W/2-10,0);
system("pause");
setxy(W/2-10,0);
printf(" ");
}
}
if(msgmessage==WM_TIMER)
{
DispatchMessage(&msg);
}
}
}
int main()
{
ini_path=(char)malloc(sizeof(char)50);
srand((unsigned)time(0));
getcwd(ini_path,50);//取得当前程序绝对路径
ini_path=strcat(ini_path,"snakedat");
max_count=GetPrivateProfileInt("MAX_COUNT","max_count",0,ini_path);
old_max_count=max_count;
char cmd[50];
sprintf(cmd,"mode con cols=%d lines=%d\0",W,H);
system(cmd);//改变CMD窗口大小
hide_cursor();
start();
return 0;
}
/ C语言
program by wlfryq 71693456@qqcom
/
#include <stdioh>
#include <stdlibh>
#include <conioh>
#include <windowsh>
#include <timeh>
#include <directh>
#include <stdboolh>
#define W 80 //屏幕宽度
#define H 37 //屏幕高度
#define SNAKE_ALL_LENGTH 200 //蛇身最长为
void CALLBACK TimerProc(
HWND hwnd,
UINT message,
UINT idTimer,
DWORD dwTime);
void start();
struct MYPOINT
{
int x;
int y;
} s[SNAKE_ALL_LENGTH] , head, end, food;
int max_count=0; //历史最高分,如果count>max_count, 则max_count=count
int old_max_count=0; //历史最高分,不会变动, 用于死亡时判断max_count是否大于old_max_count,如果大于,则写入文件
int count=0; //得分
int len=20; //当前蛇身长度
int direct=0; //方向: 0-向右, 1-向下, 2-向左, 3-向上
int speed=200; //速度:毫秒
bool isfood=false; //食物是否存在
int timerID;
bool stop=false; //暂停
char ini_path; //数据文件绝对路径
void setxy(int x, int y) //设置CMD窗口光标位置
{
COORD coord = {x, y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void hide_cursor() //隐藏CMD窗口光标
{
CONSOLE_CURSOR_INFO cci;
ccibVisible = FALSE;
ccidwSize = sizeof(cci);
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorInfo(handle, &cci);
}
void set_food() //设置食物坐标
{
if(isfood==true)
{
return;
}
int x,y,i;
bool flag=false;
while(1)
{
flag=false;
x=rand()%(W-14)+6;
y=rand()%(H-12)+6;
for(i=0;i<len;i++) //判断食物是否落在蛇身上
{
if(s[i]x==x && s[i]y==y)
{
flag=true;
break;
}
}
if(flag==true)
{
continue;
}
else
{
foodx=x;
foody=y;
break;
}
}
setxy(foodx,foody);
printf("");
isfood=true;
}
void check_board() //检测蛇身是否越界和相交
{
int i;
if(s[0]x>=W-3 || s[0]x<=2 || s[0]y>=H-1 || s[0]y<=2)
{
setxy(W/2-5,0);
printf("game over\n");
stop=true;
if(old_max_count<max_count)
{
char t[5]={'\0'};
sprintf(t,"%d",max_count);
WritePrivateProfileString("MAX_COUNT","max_count",t,ini_path);
}
}
for(i=1;i<len;i++)
{
if(s[i]x==s[0]x && s[i]y==s[0]y)
{
setxy(W/2-5,0);
printf("game over\n");
stop=true;
if(old_max_count<max_count)
{
char t[5]={'\0'};
sprintf(t,"%d",max_count);
WritePrivateProfileString("MAX_COUNT","max_count",t,ini_path);
}
break;
}
}
if(stop==true)
{
KillTimer(NULL,timerID);
int c;
while(1)
{
fflush(stdin);
c=_getch();
if(c=='n' || c=='N')
{
start();
}
else if(c=='q' || c=='Q')
{
exit(0);
}
else continue;
}
}
}
void printf_body(bool is_first) //打印蛇身
{
if(is_first==true) //如果是第一次打印蛇身
{
int i;
for(i=0;i<len;i++)
{
setxy(s[i]x,s[i]y);
printf("O");
}
}
else //如果不是第一次打印蛇身
{
setxy(endx,endy);
printf(" ");
setxy(s[0]x,s[0]y);
printf("O");
}
if(foodx==s[0]x && foody==s[0]y) //如果吃到食物
{
count++;
isfood=false; //重置食物
set_food();
len++;
KillTimer(NULL,timerID);
if(speed>100) speed-=10;
else if(speed>50) speed-=5;
else if(speed>30) speed-=2;
else if(speed>16) speed-=1;
else ;
setxy(0,0);
if(max_count<count) max_count=count;
printf(" speed : %d ms score : %d best score:%d ",speed,count,max_count);
timerID=SetTimer(NULL,001,speed,TimerProc);
}
}
void change_body_pos(int x, int y) //改变蛇身的坐标数据
{
endx=s[len-1]x;
endy=s[len-1]y;
int i;
for(i=len-1;i>0;i--)
{
s[i]x=s[i-1]x;
s[i]y=s[i-1]y;
}
s[0]x=x;
s[0]y=y;
}
void CALLBACK TimerProc(
HWND hwnd,
UINT message,
UINT idTimer,
DWORD dwTime)
{
switch(direct)
{
case 0:
headx++;
change_body_pos(headx,heady);
printf_body(false);
check_board();
break;
case 1:
heady++;
change_body_pos(headx,heady);
printf_body(false);
check_board();
break;
case 2:
headx--;
change_body_pos(headx,heady);
printf_body(false);
check_board();
break;
case 3:
heady--;
change_body_pos(headx,heady);
printf_body(false);
check_board();
break;
}
}
void start()
{
int i;
KillTimer(NULL,timerID);
count=0; //得分
len=20; //当前蛇身长度
direct=0; //方向: 0-向右, 1-向下, 2-向左, 3-向上
speed=200; //速度:毫秒
isfood=false; //食物是否存在
stop=false; //停止
system("cls");
setxy(1,4);
printf("┌─────────────────────────────────────┐\n");
for(i=0;i<33;i++)
{
printf(" │ │\n");
}
printf(" └─────────────────────────────────────┘");
headx=len-1+5;
heady=H/2;
for(i=0;i<len;i++)
{
s[i]x=headx-i;
s[i]y=heady;
}
setxy(0,0);
printf(" speed : %d:ms score : %d best score:%d ",speed,count,max_count);
printf_body(true);
set_food();
timerID=SetTimer(NULL,001,speed,TimerProc);
int c;
MSG msg;
while(GetMessage(&msg,NULL,0,0))
{
if(stop==true) break;
if(_kbhit()) //如果按下的是方向键或功能键, _getch()要调用两次,第一次返回0XE0或0
{
fflush(stdin);
c=_getch(); //上: 72 下:80 左:75 右:77
if(c==0XE0 || c==0)
{
c=_getch();
if(c==72 && direct!=1 && direct!=3)
{
direct=3;
}
else if(c==80 && direct!=1 && direct!=3)
{
direct=1;
}
else if(c==75 && direct!=0 && direct!=2)
{
direct=2;
}
else if(c==77 && direct!=0 && direct!=2)
{
direct=0;
}
}
else if(c==' ')
{
setxy(W/2-10,0);
system("pause");
setxy(W/2-10,0);
printf(" ");
}
}
if(msgmessage==WM_TIMER)
{
DispatchMessage(&msg);
}
}
}
int main()
{
ini_path=(char)malloc(sizeof(char)50);
srand((unsigned)time(0));
getcwd(ini_path,50);//取得当前程序绝对路径
ini_path=strcat(ini_path,"snakedat");
max_count=GetPrivateProfileInt("MAX_COUNT","max_count",0,ini_path);
old_max_count=max_count;
char cmd[50];
sprintf(cmd,"mode con cols=%d lines=%d\0",W,H);
system(cmd);//改变CMD窗口大小
hide_cursor();
start();
return 0;
}
C语言贪吃蛇源代码必须经过相应的C/C++编译器编译成EXE文件后才能运行。
由于我们通常使用的 *** 作系统是Windows系统,而在该系统下最长用的C/C++编译器是VC++编译器,目前在大专院校常用的版本还是VC++60
下面就以VC++60来说明编译过程:
1在VC++60中通过“File”菜单下的 “Open”子菜单打开贪吃蛇代码
2在VC++60中通过“Build”菜单下的 “Compile xxxxxx”子菜单编译贪吃蛇代码
3在VC++60中通过“Build”菜单下的 “Execute xxxxexe”子菜单运行贪吃蛇程序
附:在VC++6环境下可运行的C/C++贪吃蛇源代码(无版权,自己编写,欢迎任意修改拷贝)
/C/C++贪吃蛇游戏,zjlj,2015316
/
#define DEBUG 0 //当程序在调试阶段时 DEBUG为 1
#include<iostream>
#include<windowsh>
#include<timeh>
#include<conioh>
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;
posX=2y;
posY=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;i<22;i++)
{
for(j=0;j<22;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,20150316 ";
}
}
int main(int argc, char argv[]){
int tcsQipan[22][22]; // 贪吃蛇棋盘是一个二维数组(如2222,包括墙壁)
int i,j,score,directiontemp;
FILE fpini;//fpini 信息文件
readini(&fpini, &score, argv);//读取ini文件的最高纪录
if (score<0)//最高成绩小于零设置为零,初建文件会是负数
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; i<4; 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(i>0)
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==x1&&y==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(gamespeed>50)//控制最快速度为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;
}
#include<stdioh>
#include<stdlibh>
#include<Windowsh>
#include<conioh>
#include<timeh>
char gamemap[20][40];//游戏地图大小 2040
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;i<len;i++)
{
for(j=0;j<len;j++)
{
if(x[i]==fx&&y[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(fcount&&fx==i&&fy==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;i<len;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(fcount&&x[0]==fx&&y[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();
}
}
}
import javaawtColor;
import javaawtGraphics;
import javaawtGraphics2D;
import javaawtRectangle;
import javaawteventKeyAdapter;
import javaawteventKeyEvent;
import javaawtimageBufferedImage;
import javautilArrayList;
import javautilList;
import javaxswingJFrame;
public class InterFace extends JFrame {
/
WIDTH:宽
HEIGHT:高
SLEEPTIME:可以看作蛇运动的速度
L = 1,R = 2, U = 3, D = 4 左右上下代码
/
public static final int WIDTH = 800, HEIGHT = 600, SLEEPTIME = 200, L = 1,R = 2, U = 3, D = 4;
BufferedImage offersetImage= new BufferedImage(WIDTH, HEIGHT,BufferedImageTYPE_3BYTE_BGR);;
Rectangle rect = new Rectangle(20, 40, 15 50, 15 35);
Snake snake;
Node node;
public InterFace() {
//创建"蛇"对象
snake = new Snake(this);
//创建"食物"对象
createNode();
thissetBounds(100, 100, WIDTH, HEIGHT);
//添加键盘监听器
thisaddKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent arg0) {
Systemoutprintln(arg0getKeyCode());
switch (arg0getKeyCode()) {
//映射上下左右4个键位
case KeyEventVK_LEFT:
snakedir = L;
break;
case KeyEventVK_RIGHT:
snakedir = R;
break;
case KeyEventVK_UP:
snakedir = U;
break;
case KeyEventVK_DOWN:
snakedir = D;
}
}
});
thissetTitle("贪吃蛇 01 By : Easy");
thissetDefaultCloseOperation(EXIT_ON_CLOSE);
thissetVisible(true);
//启动线程,开始执行
new Thread(new ThreadUpadte())start();
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) offersetImagegetGraphics();
g2dsetColor(Colorwhite);
g2dfillRect(0, 0, WIDTH, HEIGHT);
g2dsetColor(Colorblack);
g2ddrawRect(rectx, recty, rectwidth, rectheight);
//如果蛇碰撞(吃)到食物,则创建新食物
if (snakehit(node)) {
createNode();
}
snakedraw(g2d);
nodedraw(g2d);
gdrawImage(offersetImage, 0, 0, null);
}
class ThreadUpadte implements Runnable {
public void run() {
//无限重绘画面
while (true) {
try {
Threadsleep(SLEEPTIME);
repaint(); //
} catch (InterruptedException e) {
eprintStackTrace();
}
}
}
}
/
创建食物
/
public void createNode() {
//随机食物的出现位置
int x = (int) (Mathrandom() 650) + 50,y = (int) (Mathrandom() 500) + 50;
Color color = Colorblue;
node = new Node(x, y, color);
}
public static void main(String args[]) {
new InterFace();
}
}
/
节点类(包括食物和蛇的身躯组成节点)
/
class Node {
int x, y, width = 15, height = 15;
Color color;
public Node(int x, int y, Color color) {
this(x, y);
thiscolor = color;
}
public Node(int x, int y) {
thisx = x;
thisy = y;
thiscolor = colorblack;
}
public void draw(Graphics2D g2d) {
g2dsetColor(color);
g2ddrawRect(x, y, width, height);
}
public Rectangle getRect() {
return new Rectangle(x, y, width, height);
}
}
/
蛇
/
class Snake {
public List<Node> nodes = new ArrayList<Node>();
InterFace interFace;
int dir=InterFaceR;
public Snake(InterFace interFace) {
thisinterFace = interFace;
nodesadd(new Node(20 + 150, 40 + 150));
addNode();
}
/
是否碰撞到食物
@return true 是 false 否
/
public boolean hit(Node node) {
//遍历整个蛇体是否与食物碰撞
for (int i = 0; i < nodessize(); i++) {
if (nodesget(i)getRect()intersects(nodegetRect())) {
addNode();
return true;
}
}
return false;
}
public void draw(Graphics2D g2d) {
for (int i = 0; i < nodessize(); i++) {
nodesget(i)draw(g2d);
}
move();
}
public void move() {
nodesremove((nodessize() - 1));
addNode();
}
public synchronized void addNode() {
Node nodeTempNode = nodesget(0);
//如果方向
switch (dir) {
case InterFaceL:
//判断是否会撞墙
if (nodeTempNodex <= 20) {
nodeTempNode = new Node(20 + 15 50, nodeTempNodey);
}
nodesadd(0, new Node(nodeTempNodex - nodeTempNodewidth,
nodeTempNodey));
break;
case InterFaceR:
//判断是否会撞墙
if (nodeTempNodex >= 20 + 15 50 - nodeTempNodewidth) {
nodeTempNode = new Node(20 - nodeTempNodewidth, nodeTempNodey);
}
nodesadd(0, new Node(nodeTempNodex + nodeTempNodewidth,
nodeTempNodey));
break;
case InterFaceU:
//判断是否会撞墙
if (nodeTempNodey <= 40) {
nodeTempNode = new Node(nodeTempNodex, 40 + 15 35);
}
nodesadd(0, new Node(nodeTempNodex, nodeTempNodey - nodeTempNodeheight));
break;
case InterFaceD:
//判断是否会撞墙
if (nodeTempNodey >= 40 + 15 35 - nodeTempNodeheight) {
nodeTempNode = new Node(nodeTempNodex,40 - nodeTempNodeheight);
}
nodesadd(0, new Node(nodeTempNodex, nodeTempNodey + nodeTempNodeheight));
break;
}
}
#include<graphicsh>
#include<stdlibh>
#include<dosh>
#define LEFT 0x4b00
#define RIGHT 0x4d00
#define DOWN 0x5000
#define UP 0x4800
#define ESC 0x011b
int i,key;
int score=0;
int gamespeed=32000;
struct Food /食物的结构体/
{
int x; /食物的横坐标/
int y; /食物的纵坐标/
int yes; /食物是否出现的变量/
}food;
struct Snack /蛇的结构体/
{
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 PrScore(void); /分数输出函数/
DELAY(char ch)/调节游戏速度/
{
if(ch=='3')
{
delay(gamespeed); /delay是延迟函数/
delay(gamespeed);
}
else if(ch=='2')
{
delay(gamespeed);
}
}
Menu()/游戏开始菜单/
{
char ch;
printf("Please choose the gamespeed:\n");
printf("1-Fast 2-Normal 3-Slow\n");
printf("\nPlease Press The numbers\n");
do
{ch=getch();}
while(ch!='1'&&ch!='2'&&ch!='3');
clrscr();
return(ch);
}
/主函数/
void main(void)
{
int ch;
ch=Menu();
Init();
DrawK();
GamePlay(ch);
Close();
}
void Init(void)
{
int gd=DETECT,gm;
initgraph(&gd,&gm,"c:\\tc");
cleardevice();
}
void DrawK(void)
{
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(char ch)
{
randomize(); /随机数发生器/
foodyes=1; /1代表要出现食物,0表示以存在食物/
snakelife=0;
snakedirection=1;
snakex[0]=100;snakey[0]=100;
snakex[1]=110;snakey[1]=100;
snakenode=2;
PrScore();
while(1) /可以重复游戏/
{
while(!kbhit()) /在没有按键的情况下蛇自己移动/
{
if(foodyes==1) /需要食物/
{
foodx=rand()%400+60;
foody=rand()%350+60; /使用rand函数随机产生食物坐标/
while(foodx%10!=0)
foodx++;
while(foody%10!=0)
foody++; /判断食物是否出现在整格里/
foodyes=0; /现在有食物了/
}
if(foodyes==0) /有食物了就要显示出来/
{
setcolor(GREEN);
rectangle(foodx,foody,foodx+10,foody-10);
}
for(i=snakenode-1;i>0;i--) /贪吃蛇的移动算法/
{
snakex[i]=snakex[i-1];
snakey[i]=snakey[i-1]; /贪吃蛇的身体移动算法/
}
switch(snakedirection) /贪吃蛇的头部移动算法,以此来控制移动/
{
case 1:snakex[0]+=10;break;
case 2:snakex[0]-=10;break;
case 3:snakey[0]-=10;break;
case 4:snakey[0]+=10;break;
}
for(i=3;i<snakenode;i++) /判断是否头部与身体相撞/
{
if(snakex[i]==snakex[0]&&snakey[i]==snakey[0])
{
GameOver();
snakelife=1;
break;
}
}
/下面是判断是否撞到墙壁/
if(snakex[0]<55||snakex[0]>595||snakey[0]<55||snakey[0]>455)
{
GameOver();
snakelife=1;
}
if(snakelife==1) /如果死亡就退出循环/
break;
if(snakex[0]==foodx&&snakey[0]==foody) /判断蛇是否吃到食物/
{
setcolor(0);
rectangle(foodx,foody,foodx+10,foody-10); /吃的食物后用黑色将食物擦去/
snakex[snakenode]=-20;snakey[snakenode]=-20; /现把增加的一节放到看不到的地方去/
snakenode++;
foodyes=1;
score+=10;
PrScore();
}
setcolor(4); /每次移动后将后面的身体擦去/
for(i=0;i<snakenode;i++)
rectangle(snakex[i],snakey[i],snakex[i]+10,snakey[i]-10);
delay(gamespeed);
DELAY(ch);
setcolor(0);
rectangle(snakex[snakenode-1],snakey[snakenode-1],snakex[snakenode-1]+10,snakey[snakenode-1]-10);
}
if(snakelife==1)
break;
key=bioskey(0); /接受按键/
if(key==ESC)
break;
else
if(key==UP&&snakedirection!=4)/判断是否改变方向/
snakedirection=3;
else
if(key==RIGHT&&snakedirection!=2)
snakedirection=1;
else
if(key==LEFT&&snakedirection!=1)
snakedirection=2;
else
if(key==DOWN&&snakedirection!=3)
snakedirection=4;
}
}
void GameOver(void)
{
cleardevice();
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,"scord:%d",score);
outtextxy(55,20,str);
}
void Close(void)
{
getch();
closegraph();
}
以上就是关于大专考试,C语言贪吃蛇程序编写,全部的内容,包括:大专考试,C语言贪吃蛇程序编写,、codeblocks 贪吃蛇c语言程序、c语言贪吃蛇源代码怎么用等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)