當前位置:首頁 » 操作系統 » c語言貪吃蛇游戲源碼

c語言貪吃蛇游戲源碼

發布時間: 2022-05-28 09:20:25

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語言貪吃蛇源代碼,一定要有注釋,不要有游標移動函數之類的(新手看不懂)。其它的沒有要求,不

貪吃蛇
#define N 200
#include
#include
#include
#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;/* 蛇的生命,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)
food.y++;
food.yes=0;/*畫面上有食物了*/
}
if(food.yes==0)/*畫面上有食物了就要顯示*/
{

③ c語言貪吃蛇源代碼怎麼用

C語言貪吃蛇源代碼必須經過相應的C/C++編譯器編譯成EXE文件後才能運行。

由於我們通常使用的操作系統是Windows系統,而在該系統下最長用的C/C++編譯器是VC++編譯器,目前在大專院校常用的版本還是VC++6.0

下面就以VC++6.0來說明編譯過程:

1.在VC++6.0中通過「File」菜單下的 「Open」子菜單打開貪吃蛇代碼

/*
C/C++貪吃蛇游戲,zjlj,2015.3.16
*/
#defineDEBUG0//當程序在調試階段時DEBUG為1
#include<iostream>
#include<windows.h>
#include<time.h>
#include<conio.h>
usingnamespacestd;
voidreadini(FILE**fphead,int*score,char*argv[])//創建或打開一個和運行文件對應的ini文件,讀取最高紀錄
{
charfilename[200],*pfilename;
intflag=-1,i;

strcpy(filename,argv[0]);
for(i=0;filename[i]!='';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]='';
}
for(;filename[i]!='\'&&i>=0;i--)pfilename=&filename[i];
if((*fphead=fopen(pfilename,"rb+"))==NULL)
{
if((*fphead=fopen(pfilename,"wb+"))==NULL)
{
printf("無法創建或打開"%s"文件 ",pfilename);
system("pause");
exit(0);
}
}
else
{
fread(score,sizeof(int),1,*fphead);
}
}
voidwriteini(FILE**fphead,int*score,char*argv[])//打開一個和運行文件對應的ini文件,寫入最高紀錄
{
charfilename[200],*pfilename;
intflag=-1,i;

strcpy(filename,argv[0]);
for(i=0;filename[i]!='';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]='';
}
for(;filename[i]!='\'&&i>=0;i--)pfilename=&filename[i];
if((*fphead=fopen(pfilename,"wb+"))==NULL)
{
printf("無法寫入"%s"文件,磁碟防寫! ",pfilename);
system("pause");
exit(0);
}
else
{
rewind(*fphead);
fwrite(score,sizeof(int),1,*fphead);
fclose(*fphead);
}
}
voidgotoxy(intx,inty)//游標定位,游標定位函數SetConsoleCursorPosition是左上角位置是0,0然後向左向下延伸
{
COORDpos;
pos.X=2*y;
pos.Y=x;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
}
voidcolor(inta)//顏色函數
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);
}

voidRefresh(intq[][22],intgrade,intgamespeed,intlength,intscore)//輸出貪吃蛇棋盤
{
inti,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<<" ***********************";
if(i==1)cout<<" 等級為:"<<grade;//顯示等級
if(i==3)cout<<" 自動前進時間";
if(i==4)cout<<" 間隔為:"<<gamespeed<<"ms";//顯示時間
if(i==6)cout<<" 歷史最高分為:"<<score<<"分";
if(i==7)cout<<" 你現在得分為:"<<(length+(grade-1)*8)*10<<"分";
if(i==8)cout<<" **********************";
if(i==9)cout<<" 游戲說明:";
if(i==10)cout<<" (1)用小鍵盤方向鍵控制";
if(i==11)cout<<" 蛇頭運動方向;";
if(i==12)cout<<" (2)蛇每吃一個果子蛇身";
if(i==13)cout<<" 增加一節;";
if(i==14)cout<<" (3)蛇咬到自己或碰到牆";
if(i==15)cout<<" 壁游戲結束。";
if(i==18)cout<<" **********************";
if(i==19)cout<<" C/C++語言作業:";
if(i==20)cout<<" zjlj,2015.03.16";
}
}

intmain(intargc,char*argv[]){
inttcsQipan[22][22];//貪吃蛇棋盤是一個二維數組(如22*22,包括牆壁)
inti,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
inttcsZuobiao[2][500];//蛇的坐標數組
for(i=0;i<4;i++)
{
tcsZuobiao[0][i]=1;//蛇身和蛇頭的x坐標
tcsZuobiao[1][i]=i+1;//蛇身和蛇頭的y坐標
}
inthead=3,tail=0;//標示蛇頭和蛇尾的數組偏移量
for(i=1;i<=3;i++)
tcsQipan[1][i]=4;//蛇身
tcsQipan[1][4]=3;//蛇頭
intx1,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<<" 貪吃蛇游戲即將開始!"<<endl;//准備開始
longstart,starttemp;
intgrade=1,length=4;//設置初始等級和蛇的初始長度
intgamespeed=500;//設置初始前進時間間隔
for(i=3;i>=0;i--)
{
start=clock();
while(clock()-start<=1000);
system("cls");
if(i>0)
cout<<" 進入倒計時:"<<i<<endl;//倒計時顯示
else
Refresh(tcsQipan,grade,gamespeed,length,score);//初始棋盤顯示
}
inttimeover=1,otherkey=1;//初始化超時時間和按鍵判斷參數
chardirection=77;//設置初始情況下,向右運動
intx=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<<" 按鍵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);
}
elseif(direction==80&&directiontemp==72)
{
direction=32;//設置按鍵為非方向鍵
otherkey=0;//按鍵為非方向鍵,otherkey設置為0
//start=clock();
//while(clock()-start<=starttemp);//補償等待時間
}
elseif(direction==75&&directiontemp==77)
{
direction=32;
otherkey=0;
//start=clock();
//while(clock()-start<=starttemp);
}
elseif(direction==77&&directiontemp==75)
{
direction=32;
otherkey=0;
//start=clock();
//while(clock()-start<=starttemp);
}


switch(direction)//判斷方向鍵
{
case72:x=tcsZuobiao[0][head]-1;y=tcsZuobiao[1][head];break;//向上
case80:x=tcsZuobiao[0][head]+1;y=tcsZuobiao[1][head];break;//向下
case75:x=tcsZuobiao[0][head];y=tcsZuobiao[1][head]-1;break;//向左
case77: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<<" 游戲已結束!"<<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<<" 游戲已結束!"<<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<<" 游戲進行中!"<<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<<" 游戲進行中!"<<endl;
Refresh(tcsQipan,grade,gamespeed,length,score);
}
else
{
gotoxy(22,12);
cout<<" 游戲暫停中!"<<endl;
}
}
/*
游戲運行時的核心演算法結束
*/
}
while(1)
{
while(!kbhit());
if((direction=getch())==13)//按回車鍵開始下一局
break;
if(direction==27)//按ESC退出遊戲
exit(0);
}
system("cls");//清除屏幕重新開始
}
return0;
}

④ 尋找貪吃蛇c++的代碼

貪吃蛇游戲C語言源代碼學習

源代碼下載地址為:www.clang.cc

閱讀學習了源代碼,並做了簡單的注釋和修改,裡面只用了鏈表數據結構,非常適合C語言入門者學習閱讀。

程序可在VS2013下編譯運行。

⑤ 貪吃蛇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 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;/* 蛇的生命,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)
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;
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];
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();
}

⑥ 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)c語言貪吃蛇游戲源碼擴展閱讀:

實現邏輯

1,可以設置游標,就能實現制定位置列印製定符號。

2,涉及一個結構體,包含兩個元素坐標元素和一個結構體指針。

3,結構體串聯形成鏈表,遍歷獲取成員坐標,列印符號得到蛇身。

4,不斷的加頭,去尾,重新遍歷坐標,再列印形成蛇的移動。

5,食物產生的位置判定,不能越界,也不能與蛇身體重合。

6,蛇的轉向判定,一條規則,不允許倒退。

7,轉向的實現,跟行進方向決定新的關節坐標(當前頭的上下左右)

8,死亡檢測,是否頭節點坐標是否與牆壁重合,是否與身體其他關節重合。

9,加速減速,設置刷新休眠時間實現。

⑦ 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;

}

(7)c語言貪吃蛇游戲源碼擴展閱讀:

實現邏輯

1,可以設置游標,就能實現制定位置列印製定符號。

2,涉及一個結構體,包含兩個元素坐標元素和一個結構體指針。

3,結構體串聯形成鏈表,遍歷獲取成員坐標,列印符號得到蛇身。

4,不斷的加頭,去尾,重新遍歷坐標,再列印形成蛇的移動。

5,食物產生的位置判定,不能越界,也不能與蛇身體重合。

6,蛇的轉向判定,一條規則,不允許倒退。

7,轉向的實現,跟行進方向決定新的關節坐標(當前頭的上下左右)

8,死亡檢測,是否頭節點坐標是否與牆壁重合,是否與身體其他關節重合。

9,加速減速,設置刷新休眠時間實現。

⑧ C語言 的 貪吃蛇 代碼 謝謝 大家啦。。。。。。。

你好,很榮幸回答你的問題,我這里是一個c的貪吃蛇源代碼,希望對你有幫助,不過運行這個時需要你的軟體包含驚蟄EasyX圖形函數,比如vc++6.0,如遇到問題問題可以聯系我,希望對你有幫助。
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#include <stdio.h>

#define LEFT 'a'
#define RIGHT 'd'
#define DOWN 's'
#define UP 'w'
#define ESC 27

#define N 200 /*蛇的最大長度*/

int i;
char key;
int score=0; /*得分*/
int gamespeed=100; /*游戲速度自己調整*/

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=9,gm=2;

initgraph(&gd,&gm," ");
cleardevice();
}

/*開始畫面,左上角坐標為(50,40),右下角坐標為(610,460)的圍牆*/
void DrawK(void)
{
/*setbkcolor(LIGHTGREEN);*/
setcolor(LIGHTCYAN);
setlinestyle(PS_SOLID,0,1); /*設置線型*/
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)
{
srand(time(NULL)); /*隨機數發生器*/
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)
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(BLACK); /*把畫面上的食物東西去*/
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(RED); /*畫出蛇*/

for(i=0;i<snake.node;i++)
rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10);
Sleep(gamespeed);
setcolor(BLACK); /*用黑色去除蛇的的最後*/
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=getch(); /*接收按鍵*/
if (key == ESC) break; /*按ESC鍵退出*/
switch(key)
{
case UP:
if(snake.direction!=4) /*判斷是否往相反的方向移動*/
snake.direction=3;
break;
case RIGHT:
if(snake.direction!=2)
snake.direction=1;
break;
case LEFT:
if(snake.direction!=1)
snake.direction=2;
break;
case DOWN:
if(snake.direction!=3)
snake.direction=4;
break;
}

}/*endwhile(1)*/
}

/*游戲結束*/
void GameOver(void)
{
cleardevice();
PrScore();
setcolor(RED);
setfont(56,0,"黑體");
outtextxy(200,200,"GAME OVER");
getch();
}

/*輸出成績*/
void PrScore(void)
{
char str[10];

setfillstyle(YELLOW);
bar(50,15,220,35);
setcolor(BROWN);
setfont(16,0,"宋體");
sprintf(str,"score:%d",score);
outtextxy(55,16,str);
}

/*圖形結束*/
void Close(void)
{
closegraph();
}

⑨ 誰有用c語言製作貪吃蛇的代碼,及使用方法,用VC打

/*
C/C++貪吃蛇游戲,zjlj,2015.3.16
*/
#define DEBUG 0 //當程序在調試階段時 DEBUG為 1
#include<iostream>
#include<windows.h>
#include<time.h>
#include<conio.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;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,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 (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;
}

熱點內容
安卓網頁怎麼截取 發布:2024-05-18 20:53:56 瀏覽:970
在配置更新的時候沒電關機怎麼辦 發布:2024-05-18 20:36:10 瀏覽:927
win7訪問win2000 發布:2024-05-18 20:27:41 瀏覽:388
青島人社局密碼多少 發布:2024-05-18 20:19:10 瀏覽:734
無法存儲呼叫轉移 發布:2024-05-18 20:18:30 瀏覽:126
資料庫的調優 發布:2024-05-18 20:18:29 瀏覽:346
sqlserver注冊表清理 發布:2024-05-18 20:13:14 瀏覽:991
linux刪除連接 發布:2024-05-18 20:06:56 瀏覽:822
linux搭建雲伺服器平台 發布:2024-05-18 19:52:21 瀏覽:402
安卓怎麼關閉美易訂閱 發布:2024-05-18 19:29:16 瀏覽:644