貪吃蛇編程
㈠ 求用c語言編寫的貪吃蛇程序
#include <stdio.h>
#include <graphics.h>
#include <stdlib.h>
#include <dos.h> /*引用的庫函數*/
#define LEFT 0x4b00
#define RIGHT 0x4d00
#define DOWN 0x5000
#define UP 0x4800
#define ESC 0x011b/*宏定義鍵名*/
#define N 200
int i,key;
int level;/*游戲等級*/
int score=0;/*得分*/
int gamespeed;/*游戲速度*/
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 Choicelevle(void);/*選擇游戲等級*/
void Init(void);/*圖形驅動*/
void Close(void);/*圖形結束*/
void DRAW(void);/*游戲區域*/
void GameOver(void);/*結束游戲*/
void GamePlay(void);/*玩游戲具體過程*/
void PrScore(void);/*輸出成績*/
/*主函數*/
void main(void)
{
Init();/*圖形驅動*/
Choicelevle();/*選擇游戲等級*/
DRAW();/*游戲區域*/
GamePlay();/*玩游戲具體過程*/
Close();/*圖形結束*/
}
/*圖形驅動*/
void Init(void)
{
int gd=DETECT,gm;
initgraph(&gd,&gm,"\\turboc2"); /*初始化圖形系統*/
cleardevice(); /*清除圖形界面*/
}
/*選擇游戲等級*/
void Choicelevle(void)
{char name[20];
setcolor(YELLOW);
settextstyle(0,0,6);
outtextxy(150,150,"Snake");
setcolor(GREEN);
settextstyle(0,0,1);
outtextxy(200,250,"please put in your English name:");
outtextxy(200,270,"Choice levle from 1-9.");
outtextxy(300,320,"name:yangzilong");/*製作人姓名*/
outtextxy(300,350,"number:0902060226");/*製作人學號*/
outtextxy(300,380,"class:computer science 0602");/*製作人班級*/
getch();
printf("please putin your name:");
gets(name);
printf("please choice levle:");
scanf("%d",&level);
gamespeed=100000-400*level-300*level*level;
if(level>9||level<1)
{cleardevice(); /*清除圖形界面*/
setcolor(YELLOW); /*設置字體顏色*/
settextstyle(0,0,2); /*設置字體類型*/
outtextxy(150,200,"level input error"); /*顯示文本*/
getch();
level=1;
}
}
void DRAW(void)
{cleardevice(); /*清屏*/
setcolor(2);
setlinestyle(SOLID_LINE,0,THICK_WIDTH);/*設置線型*/
rectangle(45,45,465,325);
}
/*玩游戲具體過程*/
void GamePlay(void)
{setcolor(5);
setlinestyle(SOLID_LINE,0,THICK_WIDTH);/*設置線型*/
randomize();/*隨機數發生器*/
food.yes=1;/*1表示需要出現新食物,0表示已經存在食物*/
snake.life=0;/*活著*/
snake.direction=1;/*方嚮往右*/
snake.x[0]=320;snake.y[0]=240;/*蛇頭*/
snake.x[1]=330;snake.y[1]=240; /*蛇的第二節位置*/
snake.node=3;/*節數*/
PrScore();/*輸出得分*/
while(1)/*可以重復玩游戲,壓ESC鍵結束*/
{
while(!kbhit())/*在沒有按鍵的情況下,蛇自己移動身體*/
{
if(food.yes==1)/*需要出現新食物*/
{
food.x=rand()%360+70;
food.y=rand()%250+60;
while(food.x%10!=0)/*食物隨機出現後必須讓食物能夠在整格內,這樣才可以讓蛇吃到*/
food.x++;
while(food.y%10!=0)
food.y++;
food.yes=0;/*畫面上有食物了*/
}
if(food.yes==0)/*畫面上有食物了就要顯示*/
{
setcolor(GREEN);
rectangle(food.x,food.y,food.x+10,food.y-10);
}
for(i=snake.node-1;i>0;i--)/*蛇的每個環節往前移動*/
{
snake.x[i]=snake.x[i-1];
snake.y[i]=snake.y[i-1];
}
/*1,2,3,4表示右,左,上,下四個方向,通過這個控制來移動蛇頭*/
switch(snake.direction)
{
case 1: snake.x[0]+=10;break;
case 2: snake.x[0]-=10;break;
case 3: snake.y[0]-=10;break;
case 4: snake.y[0]+=10;break;
}
for(i=3;i<snake.node;i++)/*從蛇的第四節開始判斷是否撞到自己了,因為蛇頭為兩節,第三節不可能拐過來*/
{
if(snake.x[i]==snake.x[0]&&snake.y[i]==snake.y[0])
{
GameOver();/*顯示失敗*/
snake.life=1; /*蛇死*/
break;
}
}
/*如果蛇頭碰到牆壁,蛇頭從對面牆出來*/
if(snake.x[0]<50)
{snake.x[0]=450;/*如果蛇頭越過左邊界,則從右邊界進入*/
snake.y[0]=snake.y[0];/*縱坐標不變*/
for(i=snake.node-1;i>0;i--)
{snake.x[i]=snake.x[i-1];
snake.y[i]=snake.y[i-1]; /*蛇的其他節數向前推進*/
}
{
setfillstyle(SOLID_FILL,0); /*設置填充模式和顏色,0表示黑色*/
bar(50,55,455,315);/*bar是表示填充的范圍的函數*/
}
}
else
if(snake.x[0]>450)
{snake.x[0]=50;/*如果蛇頭越過右邊界,則蛇頭從左邊界進入*/
snake.y[0]=snake.y[0];/*縱坐標不變*/
for(i=snake.node-1;i>0;i--)
{snake.x[i]=snake.x[i-1];
snake.y[i]=snake.y[i-1]; /*蛇的其他節數向前推進*/
}
{
setfillstyle(SOLID_FILL,0); /*設置填充模式和顏色,0表示黑色*/
bar(50,55,455,315);/*bar是表示填充的范圍的函數*/
}
}
else
if(snake.y[0]<60)
{snake.y[0]=320;/*如果蛇頭越過上邊界,則從下邊界進入*/
snake.x[0]=snake.x[0];/*橫坐標不變*/
for(i=snake.node-1;i>0;i--)
{snake.x[i]=snake.x[i-1];
snake.y[i]=snake.y[i-1]; /*蛇的其他節數向前推進*/
}
{
setfillstyle(SOLID_FILL,0); /*設置填充模式和顏色,0表示黑色*/
bar(50,55,455,315);/*bar是表示填充的范圍的函數*/
}
}
else
if(snake.y[0]>320)
{snake.y[0]=60;/*如果蛇頭越過下邊界,則從上邊界進入*/
snake.x[0]=snake.x[0];/*橫坐標不變*/
for(i=snake.node-1;i>0;i--)
{snake.x[i]=snake.x[i-1];
snake.y[i]=snake.y[i-1]; /*蛇的其他節數向前推進*/
}
{
setfillstyle(SOLID_FILL,0); /*設置填充模式和顏色,0表示黑色*/
bar(50,55,455,315);/*bar是表示填充的范圍的函數*/
}
}
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; /*每吃掉一食物,得分累加10分*/
if(score%100==0)
{level++;gamespeed=100000-400*level-300*level*level;/*每吃掉10食物提升一級,速度加快*/
PrScore();/*輸出新得分*/
setcolor(YELLOW); /*設置字體顏色*/
settextstyle(0,0,4); /*設置字體類型*/
outtextxy(150,200,"LEVEL UP"); /*顯示文本*/
if(level==10)
{level=1,gamespeed=100000-400*level-300*level*level;}
delay(6000000);
delay(6000000);
delay(6000000);
delay(6000000);
delay(6000000);
delay(6000000);
delay(6000000);
bar(50,55,455,315);/*bar是表示填充的范圍的函數*/
}
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;
else
if(key==UP&&snake.direction!=4)
/*判斷是否往相反的方向移動*/
snake.direction=3;
else
if(key==RIGHT&&snake.direction!=2)
snake.direction=1;
else
if(key==LEFT&&snake.direction!=1)
snake.direction=2;
else
if(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 str1[20];/*設置字元型數組*/
setfillstyle(SOLID_FILL,0);
bar(50,15,390,35); /*填充矩形框*/
setcolor(6); /*設置文本顏色*/
settextstyle(0,0,2); /*設置數組顯示位置*/
sprintf(str1,"score %d level %d",score,level);/*顯示數組內容*/
outtextxy(55,20,str1);
setcolor(YELLOW); /*設置字體顏色*/
settextstyle(0,0,2); /*設置字體類型*/
outtextxy(250,400,"EXIT=ESC ");/*顯示文本*/
}
void Close(void)
{
closegraph();
}
㈡ 求貪吃蛇的C++程序代碼
#include<graphics.h>
#include<stdlib.h>
#include<dos.h>
#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(); /*隨機數發生器*/
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) /*可以重復游戲*/
{
while(!kbhit()) /*在沒有按鍵的情況下蛇自己移動*/
{
if(food.yes==1) /*需要食物*/
{
food.x=rand()%400+60;
food.y=rand()%350+60; /*使用rand函數隨機產生食物坐標*/
while(food.x%10!=0)
food.x++;
while(food.y%10!=0)
food.y++; /*判斷食物是否出現在整格里*/
food.yes=0; /*現在有食物了*/
}
if(food.yes==0) /*有食物了就要顯示出來*/
{
setcolor(GREEN);
rectangle(food.x,food.y,food.x+10,food.y-10);
}
for(i=snake.node-1;i>0;i--) /*貪吃蛇的移動演算法*/
{
snake.x[i]=snake.x[i-1];
snake.y[i]=snake.y[i-1]; /*貪吃蛇的身體移動演算法*/
}
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);
DELAY(ch);
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);
}
if(snake.life==1)
break;
key=bioskey(0); /*接受按鍵*/
if(key==ESC)
break;
else
if(key==UP&&snake.direction!=4)/*判斷是否改變方向*/
snake.direction=3;
else
if(key==RIGHT&&snake.direction!=2)
snake.direction=1;
else
if(key==LEFT&&snake.direction!=1)
snake.direction=2;
else
if(key==DOWN&&snake.direction!=3)
snake.direction=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();
}
㈢ 貪吃蛇編程
這里有我以前敲過的貪吃蛇,不介意可以參考一下,(ps:需要建一了application而不是console application)
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <time.h>
#define speed 200
#define left 100
#define top 50
#define right 500
#define bottom 350
struct snake
{
POINT pos;
snake *front,*next;
};
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);
bool InitWindow(HINSTANCE,int);
void items(HDC,int,int);
void MoveSnake(int);
void remove();
void destroy();
void inf(int,int,int,int);
void inf(const char*,int,int,int,int);
void inf(const char*,int,int,int);
bool is_fail();
void eat();
void wall();
void show_fruit();
UINT ShowMode;
PAINTSTRUCT ps;
bool onoff;
HFONT hf;
char judge[20];
int dir;
HDC hdc;
HWND hwnd;
HBRUSH BlackBrush,MainBrush,NULLBrush;
HPEN MainPen,BlackPen;
snake *head,*tail,*temp;
POINT fruit;
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
)
{
onoff=1;
int i;
dir=-2;
tail=NULL;
InitWindow(hInstance,nCmdShow);
for(i=0;i<5;i++)
{
if(!tail)
{
head=new snake;
tail=head;
head->pos.x=300+i*10;
head->pos.y=200;
items(hdc,head->pos.x,head->pos.y);
}
else
{
tail->next=new snake;
tail->next->front=tail;
tail=tail->next;
tail->pos.x=300+i*10;
tail->pos.y=200;
tail->next=NULL;
items(hdc,tail->pos.x,tail->pos.y);
}
}
hf=CreateFont(20,0,0,0,400,0,0,0,GB2312_CHARSET,
OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH|FF_DONTCARE,"華文行楷");
SelectObject(hdc,hf);
SetBkColor(hdc,RGB(124,146,131));
SelectObject(hdc,MainBrush);
wall();
show_fruit();
inf("得分:",260,0,0);
MSG msg;
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
destroy();
return 0;
}
LRESULT CALLBACK WndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
static int seed=15;
switch(msg)
{
case WM_TIMER:
MoveSnake(dir);
if(!is_fail())
{
KillTimer(hwnd,1);
MessageBox(hwnd,"you are lost","caption",0);
}
eat();
break;
case WM_PAINT:
hdc=BeginPaint(hwnd,&ps);
wall();
EndPaint(hwnd,&ps);
hdc=GetDC(hwnd);
case WM_KEYDOWN:
switch(wParam)
{
case VK_UP:dir=(dir!=1?-1:dir);break;
case VK_DOWN:dir=(dir!=-1?1:dir);break;
case VK_RIGHT:dir=(dir!=-2?2:dir);break;
case VK_LEFT:dir=(dir!=2?-2:dir);break;
}
break;
case WM_CLOSE:
if(MessageBox(hwnd,"確定退出?","caption",MB_YESNO)==IDYES)
DestroyWindow(hwnd);
break;
case WM_DESTROY:
ReleaseDC(hwnd,hdc);
KillTimer(hwnd,1);
PostQuitMessage(0);
break;
default:return DefWindowProc(hwnd,msg,wParam,lParam);
}
return 1;
}
bool InitWindow(HINSTANCE hInstance,int nCmdShow)
{
WNDCLASS wc;
wc.style=CS_HREDRAW | CS_VREDRAW;
wc.lpszClassName="test";
wc.lpszMenuName=NULL;
wc.cbClsExtra=0;
wc.cbWndExtra=0;
wc.hbrBackground=CreateSolidBrush(RGB(124,146,131));
wc.hIcon=NULL;
wc.hCursor=LoadCursor(NULL,IDC_ARROW);
wc.hInstance=hInstance;
wc.lpfnWndProc=WndProc;
MainBrush=CreateSolidBrush(RGB(124,146,131));
BlackBrush=(HBRUSH)GetStockObject(BLACK_BRUSH);
NULLBrush=(HBRUSH)GetStockObject(NULL_BRUSH);
MainPen=CreatePen(PS_SOLID,1,RGB(124,146,131));
BlackPen=CreatePen(PS_SOLID,1,RGB(0,0,0));
if(!RegisterClass(&wc)) return false;
hwnd=CreateWindow("test","貪吃蛇",WS_SYSMENU,400,150,616,400,NULL,NULL,hInstance,NULL);
hdc=BeginPaint(hwnd,&ps);
if(!hwnd) return false;
ShowWindow(hwnd,SW_SHOWNORMAL);
UpdateWindow(hwnd);
SetTimer(hwnd,1,speed,NULL);
return true;
}
void items(HDC hdc,int x,int y)
{
SelectObject(hdc,BlackPen);
SelectObject(hdc,NULLBrush);
Rectangle(hdc,x,y,x+10,y+10);
SelectObject(hdc,BlackBrush);
Rectangle(hdc,x+2,y+2,x+8,y+8);
// DeleteObject(BlackPen);
// DeleteObject(BlackBrush);
}
void MoveSnake(int dir)
{
static int i=0;
remove();
tail=tail->front;
delete tail->next;
tail->next=NULL;
temp=new snake;
temp->next=head;
head->front=temp;
temp->pos.x=head->pos.x+(dir/2)*10;
temp->pos.y=head->pos.y+(dir%2)*10;
head=temp;
i++;
items(hdc,head->pos.x,head->pos.y);
}
void remove()
{
SelectObject(hdc,MainBrush);
SelectObject(hdc,MainPen);
Rectangle(hdc,tail->pos.x,tail->pos.y,tail->pos.x+10,tail->pos.y+10);
// DeleteObject(MainBrush);
// DeleteObject(MainPen);
}
void destroy()
{
while(head->next)
{
head=head->next;
delete head->front;
}
delete tail;
}
void inf(int x,int y,int px,int py)
{
inf("",x,y,px,py);
}
void inf(const char*str,int x,int y,int scores)
{
sprintf(judge,"%s%d",str,scores);
TextOut(hdc,x,y,judge,strlen(judge));
}
void inf(const char*str,int x,int y,int px,int py)
{
sprintf(judge,"%s(%d,%d) ",str,px,py);
TextOut(hdc,x,y,judge,strlen(judge));
}
bool is_fail()
{
temp=head;
int px=head->pos.x,py=head->pos.y;
if(px<left||px>=right||py<top||py>=bottom)
return 0;
while(temp->next)
{
temp=temp->next;
if(px==temp->pos.x&&py==temp->pos.y)
return 0;
}
return 1;
}
void show_fruit()
{
srand((UINT)time(NULL));
fruit.x=10*((rand()%(right-left-10))/10)+left;
fruit.y=10*((rand()%(bottom-top-10))/10)+top;
items(hdc,fruit.x,fruit.y);
}
void eat()
{
inf("食物:",0,25,fruit.x,fruit.y);
inf("蛇頭:",0,0,head->pos.x,head->pos.y);
static int scores=0;
if(head->pos.x==fruit.x&&head->pos.y==fruit.y)
{
scores++;
inf("得分:",260,0,scores);
KillTimer(hwnd,1);
temp=new snake;
temp->next=head;
head->front=temp;
temp->pos.x=head->pos.x+(dir/2)*10;
temp->pos.y=head->pos.y+(dir%2)*10;
head=temp;
items(hdc,head->pos.x,head->pos.y);
SetTimer(hwnd,1,speed,NULL);
show_fruit();
}
}
void wall()
{
SelectObject(hdc,MainBrush);
Rectangle(hdc,left-1,top-1,right+1,bottom+1);
// DeleteObject(MainBrush);
}
㈣ C語言的貪吃蛇源代碼
#include <bits/stdc++.h>
#include <windows.h>
#include <conio.h>
using namespace std;
void gotoxy(int x,int y) {COORD pos={x,y}; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);}//游標定位
class Food {//食物類
private: int m_x; int m_y;
public:
void randfood() {//隨機產生一個食物
srand((int)time(NULL));//利用時間添加隨機數種子,需要ctime頭文件
L1:{m_x=rand()%(85)+2;//2~86
m_y=rand()%(25)+2;//2~26
if(m_x%2) goto L1;//如果食物的x坐標不是偶數則重新確定食物的坐標
gotoxy(m_x,m_y);//在確認好的位置輸出食物
cout << "★";}}
int getFoodm_x() {return m_x;}//返回食物的x坐標
int getFoodm_y() {return m_y;}};//返回食物的y坐標
class Snake {
private:
struct Snakecoor {int x; int y;};//定義一個蛇的坐標機構
vector<Snakecoor> snakecoor;//將坐標存入vector容器中
//判斷並改變前進方向的函數
void degdir(Snakecoor&nexthead) {//定義新的蛇頭變數
static char key='d';//靜態變數防止改變移動方向後重新改回來
if(_kbhit()) {
char temp=_getch();//定義一個臨時變數儲存鍵盤輸入的值
switch(temp) {//如果臨時變數的值為wasd中的一個,則賦值給key
default: break;//default是預設情況,只有任何條件都不匹配的情況下才會執行 必須寫在前面!不然蛇無法轉向
case'w': case'a': case's': case'd':
//如果temp的方向和key的方向不相反則賦值 因為兩次移動方向不能相反 將蛇設置為初始向右走
if(key=='w' && temp!='s' || key=='s' && temp!='w' || key=='a' && temp!='d' || key=='d' && temp!='a') key=temp;}}
switch (key) {//根據key的值來確定蛇的移動方向
case'd': nexthead.x=snakecoor.front().x+2; nexthead.y=snakecoor.front().y; break;
//新的蛇頭的頭部等於容器內第一個數據(舊蛇頭)x坐標+2 因為蛇頭占兩個坐標,移動一次加2
case'a': nexthead.x=snakecoor.front().x-2; nexthead.y=snakecoor.front().y; break;
case'w': nexthead.x=snakecoor.front().x; nexthead.y=snakecoor.front().y-1; break;
//因為控制台的x長度是y的一半,所以用兩個x做蛇頭,需要的坐標是二倍
case's': nexthead.x=snakecoor.front().x; nexthead.y=snakecoor.front().y+1;}}
//游戲結束時設計一個界面輸出「游戲結束」以及分數
void finmatt(const int score) {
system("cls"); gotoxy(40, 14);//清屏然後輸出
cout << "游戲結束"; gotoxy(40, 16);
cout << "得分:" << score; gotoxy(0, 26);
exit(0);}//exit為C++的退出函數 exit(0)表示程序正常退出,非0表示非正常退出
void finishgame(const int score) {//游戲結束
if(snakecoor[0].x>=88 || snakecoor[0].x<0 || snakecoor[0].y>=28 || snakecoor[0].y<0) finmatt(score);//撞牆
for(int i=1;i<snakecoor.size();i++) if(snakecoor[0].x==snakecoor[i].x && snakecoor[0].y==snakecoor[i].y) finmatt(score);}//撞到自身
public://構造初始化蛇的位置
Snake() { Snakecoor temp;//臨時結構變數用於創建蛇
for(int i=5;i>=0;i--) {//反向創建初始蛇身,初始蛇頭朝右
temp.x=16+(i<<1); temp.y=8;//偶數 在蛇頭左移生成蛇身
snakecoor.push_back(temp);}}//在蛇尾尾插入臨時變數
void move(Food&food, int& score) {//蛇運動的函數
Snakecoor nexthead;//新蛇頭變數
degdir(nexthead);//判斷和改變蛇前進的方向
snakecoor.insert(snakecoor.begin(), nexthead);//將蛇頭插入容器的頭部
gotoxy(0, 0); cout << "得分:" << score;//每次移動都在左上角刷新得分
gotoxy(0, 2); cout << "蛇的長度為:" << snakecoor.size();//長度用來測試
finishgame(score);//判斷游戲結束,輸出分數
//吃到食物蛇的變化
if(snakecoor[0].x==food.getFoodm_x() && snakecoor[0].y==food.getFoodm_y()) {//蛇頭與食物重合
gotoxy(snakecoor[0].x, snakecoor[0].y); cout << "●";//吃到食物時這次蛇沒有移動,所以蛇會卡頓一下
gotoxy(snakecoor[1].x, snakecoor[1].y); cout << "■";//重新輸出一下蛇頭和第一節蛇身讓蛇不卡頓
score++; food.randfood(); return;}//吃到食物得分+1,如果蛇頭坐標和食物坐標重合則重新產生一個食物並直接結束本次移動
for(int i=0;i<snakecoor.size();i++) {//遍歷容器,判斷食物與蛇身是否重合並輸出整條蛇
gotoxy(snakecoor[i].x, snakecoor[i].y);
if (!i) cout << "●"; else cout << "■";//頭部輸出圓形否則輸出方塊
if (snakecoor[i].x==food.getFoodm_x() && snakecoor[i].y==food.getFoodm_y())food.randfood();}//如果食物刷新到了蛇身上,則重新產生一個
gotoxy(snakecoor.back().x,snakecoor.back().y);cout << " ";snakecoor.pop_back();}};
//數據與畫面是分開,的在容器尾部的地方輸出空格 清除畫面上的蛇尾,刪除容器中最後一個數據 清除數據上的蛇尾
void HideCursor() {CONSOLE_CURSOR_INFO cursor_info={1,0};SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cursor_info);}//隱藏游標
int main() {system("mode con cols=88 lines=28"); system("title 貪吃蛇"); HideCursor();//游標隱藏,設置控制台窗口大小、標題
int score=0; Food food; food.randfood(); Snake snake;//得分變數,食物對象,開局隨機產生一個食物,蛇對象
while(true) {snake.move(food, score);Sleep(150);}return 0;}//蛇移動,游戲速度
㈤ c#編程貪吃蛇
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;
namespaceSnakeGame
{
publicpartialclassfrmSnake:Form
{
publicPointFoodLct=newPoint();//緩存食物的坐標
publicintsnakeLen=6;
publicconstintSnakeMaxLength=500;
publicPoint[]snakeArr=newPoint[SnakeMaxLength];
publicintsnakeDrt=2;
publicboolpanDuan=true;
publicfrmSnake()
{
InitializeComponent();
inttemp=0;
for(inti=snakeLen-1;i>=0;i--)
{
snakeArr[i].X=temp;snakeArr[i].Y=0;
temp+=15;
}
}
/*
前言
說到貪吃蛇,大家可能小時候都玩過,小菜最近在整理Winfrom的學習系列,那我覺得有興趣才會有學習,就從這個小游戲講起吧。
其實我剛開始學習編程的時候,感覺寫個貪吃蛇的程序會很難,因為涉及到畫圖什麼的,其實現在來看,實現很簡單。
實現貪吃蛇首先有幾個元素:
蛇
食物
然後有幾個行為:
吃食物和吃不到食物
撞牆和撞自己
說到這有點oo的意思啊,這篇就不啰嗦,只是簡單實現,下篇會優化下。
其實整個貪吃蛇的難點就在於畫圖,可能用其他語言實現有點復雜,但是強大的.net提供了GDI+繪圖機制,實現起來就很方便了,其次就是細節的處理,比如坐標的定位,蛇的行走路線等。
我們簡單一點來看,食物可以看成一個小方格,蛇是有N個小方格組成,那我們就可以用GDI+這樣實現:
///<summary>
///畫一個小方塊
///</summary>
publicvoidDrawShape(intx,inty)
{
Graphicsg=this.CreateGraphics();
Penpen=newPen(Color.Blue,2);
g.DrawRectangle(pen,x,y,15,15);
g.FillRectangle(Brushes.Green,x,y,15,15);
}
///<summary>
///畫一個食物
///</summary>
publicvoidDrawFood(intx,inty)
{
Graphicsg=this.CreateGraphics();
Penpen=newPen(Color.Red,2);
SolidBrushbrush=newSolidBrush(Color.Green);
g.DrawRectangle(pen,x,y,15,15);
g.FillRectangle(brush,x,y,15,15);
}
Graphics這個類我就不多說,大家可以看看MSDN上介紹的用法,上面是畫蛇的最小單元-方格,和一個食物方格,蛇的方格大小是15*15,邊框顏色是Blue,填充色是Green;食物方格的大小是15*15,邊框顏色是Red,填充色是Green。
畫好了基本元素,那下面就是用基本元素來表現蛇了,可以用Point數組來存儲蛇的坐標,也就是每個方格的坐標,我們先看下代碼:
///<summary>
///設置Point數組坐標
///</summary>
publicvoidForward(intdrt)
{
Pointtemp=snakeArr[0];
for(inti=snakeLen-1;i>0;i--)
{
snakeArr[i].X=snakeArr[i-1].X;
snakeArr[i].Y=snakeArr[i-1].Y;
}
switch(drt)
{
case1:
snakeArr[0].X=temp.X;
snakeArr[0].Y=temp.Y-15;
break;//上
case2:
snakeArr[0].X=temp.X+15;
snakeArr[0].Y=temp.Y;
break;//右
case3:
snakeArr[0].X=temp.X;
snakeArr[0].Y=temp.Y+15;
break;//下
case4:
snakeArr[0].X=temp.X-15;
snakeArr[0].Y=temp.Y;
break;//左
}
}
drt參數是鍵盤上上下左右鍵對應的數字,snakeLen是數組的長度也就是方格的個數,上面那個for循環主要的作用是把前一個數組的坐標賦值給下一個,就像是毛毛蟲爬行一樣,後一節會按照前一節的路線來爬,下面那個switch的作用是,設置蛇頭的行進路線。
再下面就是判斷蛇是否吃到食物、是否撞到牆和撞到自己,因為蛇和食物都是用坐標存儲的,所以只要判斷蛇頭坐標是否等於食物坐標就可以了:
///<summary>
///判斷是否吃到食物
///</summary>
publicboolEatedFoot(PointFoodLct)
{
if(snakeArr[0].X==FoodLct.X&&snakeArr[0].Y==FoodLct.Y)
{
if(snakeLen<SnakeMaxLength)
{
snakeLen++;
snakeArr[snakeLen].X=snakeArr[snakeLen-1].X;
snakeArr[snakeLen].Y=snakeArr[snakeLen-1].Y;
}
returntrue;
}
else
returnfalse;
}
///<summary>
///判斷是否撞到自己
///</summary>
()
{
returnthis.CheckInSnakeBody(this.snakeArr[0].X,this.snakeArr[0].Y,1);
}
///<summary>
///檢查輸入的坐標是否在蛇的身上
///</summary>
publicboolCheckInSnakeBody(intx,inty,intsnkHead)
{
for(inti=snkHead;i<snakeLen;i++)
{
if(x==this.snakeArr[i].X&&y==this.snakeArr[i].Y)
{
returntrue;
}
}returnfalse;
}
///<summary>
///判斷是否撞牆
///</summary>
///<returns></returns>
publicboolCheckSnakeBodyInFrm()
{
if(this.snakeArr[0].X>=594||this.snakeArr[0].Y>=399-32||this.snakeArr[0].X<0||this.snakeArr[0].Y<0)
returntrue;
else
returnfalse;
}*/
/*實現上面的幾個步驟,簡單版的貪吃蛇基本上就完成了,再加上一個timer控制項,這樣蛇就會「動」起來了,就這么簡單。
完整代碼:*/
///<summary>
///畫一個小方塊
///</summary>
publicvoidDrawShape(intx,inty)
{
Graphicsg=this.CreateGraphics();
Penpen=newPen(Color.Blue,2);
g.DrawRectangle(pen,x,y,15,15);
g.FillRectangle(Brushes.Green,x,y,15,15);
}
///<summary>
///畫一個食物
///</summary>
publicvoidDrawFood(intx,inty)
{
Graphicsg=this.CreateGraphics();
Penpen=newPen(Color.Red,2);
SolidBrushbrush=newSolidBrush(Color.Green);
g.DrawRectangle(pen,x,y,15,15);
g.FillRectangle(brush,x,y,15,15);
}
///<summary>
///設置Point數組坐標
///</summary>
publicvoidForward(intdrt)
{
Pointtemp=snakeArr[0];
for(inti=snakeLen-1;i>0;i--)
{
snakeArr[i].X=snakeArr[i-1].X;
snakeArr[i].Y=snakeArr[i-1].Y;
}
switch(drt)
{
case1:snakeArr[0].X=temp.X;snakeArr[0].Y=temp.Y-15;break;//上
case2:snakeArr[0].X=temp.X+15;snakeArr[0].Y=temp.Y;break;//右
case3:snakeArr[0].X=temp.X;snakeArr[0].Y=temp.Y+15;break;//下
case4:snakeArr[0].X=temp.X-15;snakeArr[0].Y=temp.Y;break;//左
}
}
///<summary>
///時間事件///</summary>
privatevoidtimer1_Tick(objectsender,EventArgse)
{
Graphicsg=this.CreateGraphics();
g.Clear(Color.DarkKhaki);//清除整個畫面
Forward(snakeDrt);
for(inti=0;i<snakeLen;i++)
{
DrawShape(snakeArr[i].X,snakeArr[i].Y);
}
if(panDuan)
{
ShowFood();//DrawFood(FoodLct.X,FoodLct.Y);
panDuan=false;
}
if(EatedFoot(FoodLct))
{
ShowFood();
DrawFood(FoodLct.X,FoodLct.Y);
}
else
{
DrawFood(FoodLct.X,FoodLct.Y);
}
if(CheckSnakeHeadInSnakeBody()||CheckSnakeBodyInFrm())
{
this.timer1.Enabled=false;
MessageBox.Show("游戲結束!");
}
}
///<summary>
///按下方向鍵
///</summary>
privatevoidfrmSnake_KeyDown(objectsender,KeyEventArgse)
{
if(e.KeyCode==Keys.Up)snakeDrt=1;
elseif(e.KeyCode==Keys.Down)
snakeDrt=3;
elseif(e.KeyCode==Keys.Right)
snakeDrt=2;
elseif(e.KeyCode==Keys.Left)
snakeDrt=4;
}
///<summary>
///判斷是否撞到自己
///</summary>
()
{
returnthis.CheckInSnakeBody(this.snakeArr[0].X,this.snakeArr[0].Y,1);
}
///<summary>
///檢查輸入的坐標是否在蛇的身上
///</summary>
publicboolCheckInSnakeBody(intx,inty,intsnkHead)
{
for(inti=snkHead;i<snakeLen;i++)
{
if(x==this.snakeArr[i].X&&y==this.snakeArr[i].Y)
{
returntrue;
}
}
returnfalse;
}
///<summary>
///判斷是否撞牆
///</summary>
///<returns></returns>
publicboolCheckSnakeBodyInFrm()
{
if(this.snakeArr[0].X>=594||this.snakeArr[0].Y>=399-32||this.snakeArr[0].X<0||this.snakeArr[0].Y<0)
returntrue;
else
returnfalse;
}
///<summary>
///隨機顯示食物
///</summary>
publicvoidShowFood()
{
Randomrmd=newRandom();
intx,y;x=rmd.Next(0,this.Width/15)*15;
y=rmd.Next(0,this.Height/15)*15;
//while(this.CheckInSnakeBody(x,y,1))
//{
//x=rmd.Next(0,32)*15;
//y=32+rmd.Next(0,30)*15;
//}
FoodLct.X=x;
FoodLct.Y=y;
}
///<summary>
///判斷是否吃到食物
///</summary>
publicboolEatedFoot(PointFoodLct)
{
if(snakeArr[0].X==FoodLct.X&&snakeArr[0].Y==FoodLct.Y)
{
if(snakeLen<SnakeMaxLength)
{
snakeLen++;
snakeArr[snakeLen].X=snakeArr[snakeLen-1].X;
snakeArr[snakeLen].Y=snakeArr[snakeLen-1].Y;
}returntrue;
}
else
returnfalse;
}
}
}
㈥ c語言 貪吃蛇 程序
基本思路:
蛇每吃一個食物蛇身子就增加一格,用UP, DOWN, LEFT, RIGHT控制蛇頭的運動,而蛇身子跟著蛇頭走,每後一格蛇身子下一步走到上一格蛇身子的位置,以此類推。
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#define BEG_X 2
#define BEG_Y 1
#define WID 20
#define HEI 20
HANDLE hout;
typedef enum {UP, DOWN, LEFT, RIGHT} DIR;
typedef struct Snake_body
{
COORD pos;//蛇身的位置
struct Snake_body *next;//下一個蛇身
struct Snake_body *prev;//前一個蛇身
}SNAKE, *PSNAKE;
PSNAKE head = NULL;//蛇頭
PSNAKE tail = NULL;//蛇尾
//畫游戲邊框的函數
void DrawBorder()
{
int i, j;
COORD pos = {BEG_X, BEG_Y};
for(i = 0; i < HEI; ++i)
{
SetConsoleCursorPosition(hout, pos);
for(j = 0; j < WID; ++j)
{
if(i == 0)//第一行
{
if(j == 0)
printf("┏");
else if(j == WID - 1)
printf("┓");
else
printf("━");
}
else if(i == HEI - 1)//最後一行
{
if(j == 0)
printf("┗");
else if(j == WID - 1)
printf("┛");
else
printf("━");
}
else if(j == 0 || j == WID - 1)//第一列或最後一列
printf("┃");
else
printf(" ");
}
++pos.Y;
}
}
//添加蛇身的函數
void AddBody(COORD pos)
{
PSNAKE pnew = (PSNAKE)calloc(1, sizeof(SNAKE));
pnew->pos = pos;
if(!head)
{
head = tail = pnew;
}
else
{
pnew->next = head;//新創建蛇身的next指向原先的蛇頭
head->prev = pnew;//原先的蛇頭的prev指向新創建的蛇身
head = pnew;//把新創建的蛇身作為新的蛇頭
}
SetConsoleCursorPosition(hout, head->pos);
printf("◎");
}
//蛇身移動的函數
void MoveBody(DIR dir)
{
PSNAKE ptmp;
COORD pos = head->pos;
switch(dir)
{
case UP:
if(head->pos.Y > BEG_Y + 1)
--pos.Y;
else
return;
break;
case DOWN:
if(head->pos.Y < BEG_Y + HEI - 2)
++pos.Y;
else
return;
break;
case LEFT:
if(head->pos.X > BEG_X + 2)
pos.X -= 2;
else
return;
break;
case RIGHT:
if(head->pos.X < BEG_X + (WID - 2) * 2)
pos.X += 2;
else
return;
break;
}
AddBody(pos);//添加了一個新的蛇頭
ptmp = tail;//保存當前的蛇尾
tail = tail->prev;
if(tail)
tail->next = NULL;
SetConsoleCursorPosition(hout, ptmp->pos);
printf(" ");
free(ptmp);
}
int main()
{
int ctrl;
DIR dir = RIGHT;//初始蛇的方向是向右的
COORD pos = {BEG_X + 2, BEG_Y + HEI / 2};
system("color 0E");
system("mode con cols=90 lines=30");
hout = GetStdHandle(STD_OUTPUT_HANDLE);
printf(" ------------貪吃蛇的移動------------");
DrawBorder();
//自定義幾個蛇的身體
AddBody(pos);
pos.X += 2;
AddBody(pos);
pos.X += 2;
AddBody(pos);
pos.X += 2;
AddBody(pos);
pos.X += 2;
AddBody(pos);
pos.X += 2;
AddBody(pos);
pos.X += 2;
AddBody(pos);
//控制蛇的移動
while(ctrl = getch())
{
switch(ctrl)
{
case 'w':
if(dir == DOWN)
continue;
dir = UP;
break;
case 's':
if(dir == UP)
continue;
dir = DOWN;
break;
case 'a':
if(dir == RIGHT)
continue;
dir = LEFT;
break;
case 'd':
if(dir == LEFT)
continue;
dir = RIGHT;
break;
case 'q':
return 0;
}
MoveBody(dir);
}
return 0;
}
(6)貪吃蛇編程擴展閱讀:
實現邏輯
1,可以設置游標,就能實現制定位置列印製定符號。
2,涉及一個結構體,包含兩個元素坐標元素和一個結構體指針。
3,結構體串聯形成鏈表,遍歷獲取成員坐標,列印符號得到蛇身。
4,不斷的加頭,去尾,重新遍歷坐標,再列印形成蛇的移動。
5,食物產生的位置判定,不能越界,也不能與蛇身體重合。
6,蛇的轉向判定,一條規則,不允許倒退。
7,轉向的實現,跟行進方向決定新的關節坐標(當前頭的上下左右)
8,死亡檢測,是否頭節點坐標是否與牆壁重合,是否與身體其他關節重合。
9,加速減速,設置刷新休眠時間實現。
㈦ 貪吃蛇plc編程思路
貪吃蛇變成了自助的,這你應該找找貪吃蛇的業績上關於編程方面的。
㈧ 用C語言編寫貪吃蛇游戲的程序
回答:Mr.emily
大師
6月3日
16:45
#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
0x011b
int
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;
}snake;
void
Init();
void
Close();
void
DrawK();
void
GamePlay();
void
GameOver();
void
PrScore();
void
main()
{
Init();
DrawK();
GamePlay();
Close();
}
void
Init()
{int
gd=DETECT,gm;
initgraph(&gd,&gm,"F:\\tuoboc2");/*此處為turboc的路徑,讀者可以根據自己的電腦而改*/
cleardevice();
}
void
DrawK()
{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()
{randomize();
food.yes=1;
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)
{while(!kbhit())
{
if(food.yes==1)
{food.x=rand()%400+60;
food.y=rand()%350+60;
while(food.x%10!=0)
food.x++;
while(food.y%10!=0)
food.y++;
food.yes=0;
}
if(food.yes==0)
{setcolor(GREEN);
rectangle(food.x,food.y,food.x+10,food.y-10);
}
for(i=snake.node-1;i>0;i--)
{snake.x[i]=snake.x[i-1];
snake.y[i]=snake.y[i-1];
}
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);
}
if(snake.life==1)
break;
key=bioskey(0);
if(key==Esc)
break;
else
if(key==UP&&snake.direction!=4)
snake.direction=3;
else
if(key==RIGHT&&snake.direction!=2)
snake.direction=1;
else
if(key==LEFT&&snake.direction!=1)
snake.direction=2;
else
if(key==DOWN&&snake.direction!=3)
snake.direction=4;
}
}
void
GameOver()
{
cleardevice();
PrScore();
setcolor(RED);
settextstyle(3,0,4);
outtextxy(100,100,"Mengmeng,i
love
you!");
getch();
}
void
PrScore()
{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()
{
getch();
closegraph();
}
Mr.emily
㈨ 簡單貪吃蛇C語言程序
#include <graphics.h>
#include <stdlib.h>
#include <dos.h>
#define LEFT 0x4b00
#define RIGHT 0x4d00
#define DOWN 0x5000
#define UP 0x4800
#define ESC 0x011b
#define N 200/*蛇的最大長度*/
#define M 3 /*食物數量*/
#define F 2 /*毒花數量*/
int i,j,key;
int k=0;
int a=0;
int map[20][20];/*障礙地圖*/
int score=200;/*得分*/
int gamespeed;/*游戲速度自己調整*/
int level=1; /*游戲級別*/
struct Food
{
int x;/*食物的橫坐標*/
int y;/*食物的縱坐標*/
int yes;/*判斷是否要出現食物的變數*/
}food[M];/*食物的結構體*/
struct Flower
{
int x;
int y;
int yes;
}flower[F]; /*毒花的結構體*/
struct Lucky
{
int x;
int y;
int yes;
}lucky;/*救命稻草結構體*/
struct Snake
{
int x[N];
int y[N];
int node;/*蛇的節數*/
int direction;/*蛇移動方向*/
int life;/* 蛇的生命,0死亡*/
}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),右下角坐標為(595,460)的圍牆*/
void DrawK(void)
{
setcolor(RED);
rectangle(50,40,595,460);
}
/*玩游戲具體過程*/
void GamePlay(void)
{
int ii,jj;
randomize();
for(i=0;i<M;i++)/*隨機數發生器*/
food[i].yes=1;/*1表示需要出現新食物,0表示已經存在食物*/
for(i=0;i<F;i++)
flower[i].yes=1;
snake.life=25;
snake.direction=1;/*方嚮往右*/
snake.x[0]=110;snake.y[0]=60;
snake.x[1]=100;snake.y[1]=60;/*蛇頭*/
snake.node=2;/*節數*/
PrScore();/*輸出得分*/
while(1)/*可以重復玩游戲,壓ESC鍵結束*/
{
while(!kbhit())/*在沒有按鍵的情況下,蛇自己移動身體*/
{
/*畫地圖*/
setcolor(RED);
for(i=0;i<20;i++)
for(j=0;j<20;j++)
{
if(map[i][j])
rectangle(200+j*10-5,100+i*10-5,210+j*10-5,110+i*10-5);
}
for(i=0;i<M;i++)
{
if(food[i].yes==1)/*需要出現新食物*/
{
food[i].x=rand()%400+60;
food[i].y=rand()%350+60;
while(food[i].x%10!=0)/*食物隨機出現後必須讓食物能夠在整格內,這樣才可以讓蛇吃到*/
food[i].x++;
while(food[i].y%10!=0)
food[i].y++;
for(ii=0;ii<20;ii++)
for(jj=0;jj<20;jj++)
if(map[ii][jj]){
while(food[i].x==200+jj*10&&food[i].y==100+ii*10)
food[i].x+=10; } /*不讓食物在內牆上出現*/
food[i].yes=0;/*畫面上有食物了*/
}
if(food[i].yes==0)/*畫面上有食物了就要顯示*/
{
setcolor(GREEN);
circle(food[i].x,food[i].y,4);
}
}
for(i=0;i<F;i++)
{
if(flower[i].yes==1)
{
flower[i].x=rand()%400+60;
flower[i].y=rand()%350+60;
while(flower[i].x%10!=0)
flower[i].x++;
while(flower[i].y%10!=0)
flower[i].y++;
for(ii=0;ii<20;ii++)
for(jj=0;jj<20;jj++)
if(map[ii][jj])
{
if(flower[i].x==200+jj*10&&flower[i].y==100+ii*10)
flower[i].x+=10; /*不讓毒花在內牆上出現*/
}
for(ii=0;ii<M;ii++)
{
while(flower[i].x==food[ii].x&&flower[i].y==food[ii].y)
flower[i].x+=10;/*不讓毒花與食物重合*/
}
flower[i].yes=0; /*畫面上有毒花了*/
}
if(flower[i].yes==0) /*畫面上有毒花了就要顯示*/
{
setcolor(WHITE); /*毒花為白色*/
circle(flower[i].x,flower[i].y,4);
}
}
if(level>=3&&a==0)
{
for(ii=0;ii<20;ii++)
for(jj=0;jj<20;jj++)
{
if(ii==0||ii==9||ii==19)
map[ii][jj]=1;
}
a=1;
}
if(level>=3&&snake.life<=5&&k==0)
lucky.yes=1;
if(lucky.yes==1)
{
lucky.x=rand()%400+60;
lucky.y=rand()%350+60;
while(lucky.x%10!=0)
lucky.x++;
while(lucky.y%10!=0)
lucky.y++;
for(ii=0;ii<20;ii++)
for(jj=0;jj<20;jj++)
if(map[ii][jj])
{
while(lucky.x==200+jj*10&&lucky.y==100+ii*10)
lucky.x+=10; /*不讓救命稻草在內牆上出現*/
}
for(ii=0;ii<M;ii++)
{
while(lucky.x==food[ii].x&&lucky.y==food[ii].y)
lucky.x+=10;/*不讓救命稻草與食物重合*/
}
for(ii=0;ii<F;ii++)
{
while(lucky.x==flower[ii].x&&lucky.y==flower[ii].y)
lucky.x+=10;/*不讓救命稻草與毒花重合*/
}
lucky.yes=0;
k=1;
}
if(lucky.yes==0&&k==1)
{
setcolor(RED); /*救命稻草為紅色*/
circle(lucky.x,lucky.y,4);
}
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=0;
break;
}
}
if(snake.x[0]<55||snake.x[0]>595||snake.y[0]<45||
snake.y[0]>455)/*蛇是否撞到外牆壁*/
{
GameOver();/*本次游戲結束*/
snake.life=0; /*蛇死*/
}
for(i=0;i<20;i++)
{
for(j=0;j<20;j++)
{
if(map[i][j])
{
if(snake.x[0]==(200+j*10)&&snake.y[0]==(100+i*10)) /*蛇是否撞到內牆壁*/
{
snake.life--;/*生命值減1*/
score-=10;
setcolor(0);
rectangle(200+j*10-5,100+i*10-5,210+j*10-5,110+i*10-5);/*去掉被撞掉的磚塊*/
map[i][j]=0;/*清地圖*/
PrScore();
}
}
}
}
if(snake.life==0)/*以上三種判斷,如果蛇死就跳出內循環,重新開始*/
break;
for(i=0;i<M;i++)
{
if(snake.x[0]==food[i].x&&snake.y[0]==food[i].y)/*吃到食物以後*
{
setcolor(0);/*把畫面上的食物東西去掉*/
circle(food[i].x,food[i].y,4);
snake.x[snake.node]=-20;snake.y[snake.node]=-20;
/*新的一節先放在看不見的位置,下次循環就取前一節的位置*/
snake.node++;/*蛇的身體長一節*/
food[i].yes=1;/*畫面上需要出現新的食物*/
score+=10*level;
PrScore();/*輸出新得分*/
}
}
for(i=0;i<F;i++)
{
if(snake.x[0]==flower[i].x&&snake.y[0]==flower[i].y)/*吃到毒花後*/
{
setcolor(0);
circle(flower[i].x,flower[i].y,4);
snake.life--;
flower[i].yes=1;
score-=20;
PrScore();
}
}
if(snake.x[0]==lucky.x&&snake.y[0]==lucky.y)/*吃到救命稻草後*/
{
setcolor(0);
circle(lucky.x,lucky.y,4);
snake.life++;
score+=100;
PrScore();
k=0;
}
level=snake.node/10+1;
gamespeed=60000-level*5000;
for(i=0;i<snake.node;i++)
{
setcolor(i%15+1);
/*畫出彩蛇*/
circle(snake.x[i],snake.y[i],5);
}
delay(gamespeed);
setcolor(0);/*用黑色去除蛇的的最後一節*/
circle(snake.x[snake.node-1],snake.y[snake.node-1],5);
} /*endwhile(!kbhit)*/
if(snake.life==0)/*如果蛇死就跳出循環*/
break;
key=bioskey(0);/*接收按鍵*/
if(key==ESC)/*按ESC鍵退出*/
break;
else if(key==UP&&snake.direction!=4)
/*判斷是否往相反的方向移動*/
snake.direction=3;
else if(key==RIGHT&&snake.direction!=2)
snake.direction=1;
else if(key==LEFT&&snake.direction!=1)
snake.direction=2;
else if(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],str1[10];
char str2[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);
setfillstyle(SOLID_FILL,YELLOW);
bar(225,15,350,35);
setcolor(1);
sprintf(str1,"level:%d",level);
outtextxy(230,20,str1);
setfillstyle(SOLID_FILL,YELLOW);
bar(355,15,470,35);
setcolor(7);
sprintf(str2,"life:%d",snake.life);
outtextxy(360,20,str2);
}
/*圖形結束*/
void Close(void)
{
closegraph();
}
㈩ C語言程序設計貪吃蛇
5分太少了,更何況還要每行標出注釋,這就更不太可能了!不過估計你的分數自己也不多了,到我的網盤下載代碼吧,不是每行都有注釋,但注釋也算詳細了,只是文件調用存儲兩個函數沒有寫注釋,看看合適不?