導航:首頁 > 編程語言 > 貪吃蛇編程思路

貪吃蛇編程思路

發布時間:2023-05-01 03:27:54

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

}

(1)貪吃蛇編程思路擴展閱讀:

實現邏輯

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

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

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

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

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

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

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

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

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

② 貪吃蛇 C語言 簡易程序設計

#include<graphics.h>
#include<stdlib.h>
#define N 200
#define up 0x4800
#define down 0x5000
#define left 0x4b00
#define right 0x4d00
#define esc 0x011b
#define Y 0x1579
#define n 0x316e
int gamespeed; /* 游戲速度 */
int i,key,color;
int score=0; /* 游戲分數 */
char cai48H[]={
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x04,0x00,0x18,0x00,0x00,0x00,0x0E,0x00,
0x1C,0x00,0x00,0x00,0x1C,0x00,0x1C,0x00,
0x00,0x00,0x20,0x00,0x38,0x00,0x00,0x00,
0x40,0x00,0x78,0x00,0x00,0x01,0x80,0x40,
0x70,0x00,0x00,0x03,0x80,0xC0,0xE0,0x00,
0x00,0x07,0x80,0x80,0xC0,0x00,0x00,0x0E,
0x11,0x81,0xC0,0x00,0x00,0x08,0x61,0x01,
0x80,0x00,0x00,0x00,0x23,0x03,0x04,0x00,
0x00,0x02,0x02,0x00,0x06,0x00,0x00,0x1E,
0x04,0x00,0x0F,0x00,0x00,0x1C,0x1F,0x80,
0x1E,0x00,0x00,0x08,0x3F,0x80,0x3C,0x00,
0x00,0x00,0xFF,0x80,0x38,0x00,0x00,0x03,
0xFF,0x80,0x78,0x00,0x00,0x0F,0xF8,0x00,
0xF0,0x00,0x00,0x7F,0xF0,0x00,0xE0,0x00,
0x03,0xFF,0xFC,0x01,0x80,0x00,0x03,0xC0,
0xFF,0x01,0x03,0x80,0x01,0x01,0xFF,0x00,
0x03,0x80,0x00,0x01,0x3F,0x00,0x07,0x80,
0x00,0x02,0x11,0x00,0x07,0x00,0x00,0x00,
0x10,0x00,0x07,0x00,0x00,0x00,0x10,0x00,
0x0E,0x00,0x00,0x08,0x10,0x00,0x1C,0x00,
0x00,0x30,0x10,0x00,0x18,0x00,0x00,0x70,
0x10,0x00,0x30,0x00,0x01,0xE0,0x10,0x00,
0x70,0x00,0x03,0x80,0x10,0x00,0x60,0x00,
0x00,0x00,0x30,0x00,0xE0,0x00,0x00,0x00,
0xF0,0x01,0xC0,0x00,0x00,0x00,0x70,0x03,
0xC0,0x00,0x00,0x00,0x10,0x07,0x80,0x00,
0x00,0x00,0x00,0x0F,0x00,0x00,0x00,0x00,
0x00,0x1E,0x00,0x00,0x00,0x00,0x00,0x3C,
0x00,0x00,0x00,0x00,0x00,0x70,0x00,0x00,
0x00,0x00,0x01,0xC0,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};

char she48H[]={
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,
0x00,0x00,0x00,0x00,0x00,0x0C,0x00,0x00,
0x00,0x00,0x00,0x0E,0x00,0x00,0x00,0x00,
0x00,0x0E,0x00,0x00,0x00,0x03,0x00,0x07,
0x00,0x00,0x00,0x02,0x00,0x03,0x00,0x00,
0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x02,
0x00,0x00,0xF8,0x00,0x00,0x02,0x00,0x07,
0x86,0x00,0x00,0x02,0x00,0x18,0x03,0x00,
0x00,0x02,0x00,0x00,0x07,0x80,0x00,0x03,
0xF0,0x00,0x07,0x80,0x00,0x0F,0xFC,0x00,
0x0C,0x00,0x00,0x7E,0x3F,0x80,0x00,0x00,
0x01,0xFE,0x1F,0x80,0x00,0x00,0x01,0xE2,
0x39,0x8C,0x00,0x00,0x00,0xC2,0x30,0x08,
0x00,0x00,0x00,0xC2,0x60,0x08,0x00,0x00,
0x00,0xC3,0xE0,0x08,0x60,0x00,0x00,0x7F,
0xE0,0x01,0xE0,0x00,0x00,0x3F,0x80,0x1F,
0xE0,0x00,0x00,0x1E,0x00,0x1F,0x80,0x00,
0x00,0x1E,0x00,0x1F,0x00,0x00,0x00,0x02,
0x38,0x1E,0x00,0x00,0x00,0x07,0xFC,0x1C,
0x00,0x20,0x00,0x07,0xFC,0x18,0x00,0x20,
0x00,0x1F,0x0C,0x10,0x00,0x20,0x00,0x7C,
0x04,0x10,0x00,0x60,0x01,0xF0,0x00,0x10,
0x00,0x60,0x01,0xE0,0x00,0x08,0x00,0xF0,
0x00,0x80,0x00,0x08,0x03,0xF0,0x00,0x00,
0x00,0x07,0xFF,0xF0,0x00,0x00,0x00,0x07,
0xFF,0xF0,0x00,0x00,0x00,0x03,0xFF,0xE0,
0x00,0x00,0x00,0x01,0xFF,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};
char tun48H[]={
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x0E,0x00,0x00,0x00,0x00,0x00,0x3E,
0x00,0x00,0x00,0x00,0x00,0x7F,0x00,0x00,
0x00,0x00,0x00,0xE0,0x00,0x00,0x00,0x00,
0x03,0xC0,0x00,0x00,0x00,0x00,0x1F,0x00,
0x00,0x00,0x00,0x00,0x7C,0x00,0x00,0x00,
0x00,0x01,0xF8,0x00,0x00,0x00,0x00,0x03,
0xF8,0x00,0x40,0x00,0x00,0x00,0x06,0x07,
0xC0,0x00,0x00,0x00,0x07,0xFF,0xE0,0x00,
0x00,0x00,0x07,0xFF,0xE0,0x00,0x00,0x00,
0x0F,0xFF,0x80,0x00,0x00,0x00,0x7F,0xF8,
0x00,0x00,0x00,0x1F,0xFF,0xF8,0x00,0x00,
0x00,0x1F,0xFF,0xF8,0x00,0x00,0x00,0x1F,
0xFC,0x3C,0x00,0x00,0x00,0x0F,0xF8,0x0E,
0x00,0x00,0x00,0x04,0x70,0x07,0x00,0x00,
0x00,0x00,0x60,0x03,0x80,0x00,0x00,0x00,
0xC0,0x00,0xC0,0x00,0x00,0x01,0x80,0x00,
0x30,0x00,0x00,0x01,0x00,0x3C,0x18,0x00,
0x00,0x02,0x03,0xFF,0x0C,0x00,0x00,0x0C,
0x7F,0xFF,0x8E,0x00,0x00,0x18,0xFF,0xFF,
0xC7,0x80,0x00,0x78,0xFE,0x07,0x87,0xE0,
0x01,0xF0,0x70,0x07,0x03,0xF8,0x07,0xE0,
0x70,0x0E,0x03,0xFE,0x00,0x00,0x38,0x1E,
0x01,0xFE,0x00,0x00,0x3F,0xFE,0x00,0x0C,
0x00,0x00,0x1F,0xFE,0x00,0x00,0x00,0x00,
0x1F,0xFE,0x00,0x00,0x00,0x00,0x0F,0xFE,
0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};
char dan48H[]={
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0xFC,0x00,0x00,0x00,0x00,0x07,0xFF,
0x00,0x00,0x00,0x00,0x7F,0xC0,0x80,0x00,
0x00,0x03,0xFF,0x80,0x40,0x00,0x00,0x01,
0xF1,0x80,0x40,0x00,0x00,0x01,0x81,0x80,
0xE0,0x00,0x00,0x00,0x01,0x93,0xF0,0x00,
0x00,0x00,0x01,0xFF,0xF0,0x00,0x00,0x00,
0x21,0xFF,0xF0,0x00,0x00,0x00,0x21,0xF8,
0x00,0x00,0x00,0x00,0x61,0xC0,0x00,0x00,
0x00,0x00,0x61,0x80,0x00,0x00,0x00,0x00,
0xF3,0x00,0x00,0x00,0x00,0x00,0xFF,0x00,
0x00,0x00,0x00,0x01,0xFF,0xC0,0x00,0x00,
0x00,0x03,0xFF,0xF8,0x00,0x00,0x00,0x02,
0x00,0xFC,0x00,0x00,0x00,0x04,0x02,0x1F,
0x00,0x00,0x00,0x08,0x03,0x01,0xC0,0x00,
0x00,0x38,0x03,0x00,0x7C,0x00,0x00,0xF8,
0x07,0xF8,0x3F,0xC0,0x01,0xF0,0x3F,0xFE,
0x3F,0xF8,0x03,0xC1,0xFF,0x0F,0x1F,0xF8,
0x00,0x01,0xE3,0x0F,0x0F,0xF0,0x00,0x01,
0xC3,0x0E,0x00,0x00,0x00,0x01,0x83,0xFC,
0x00,0x00,0x00,0x00,0xC7,0xF8,0x00,0x00,
0x00,0x00,0xFF,0xF8,0x00,0x00,0x00,0x00,
0x7F,0xF0,0x00,0x00,0x00,0x00,0x3F,0x03,
0x80,0x00,0x00,0x00,0x03,0x04,0x00,0x00,
0x00,0x00,0x03,0xF8,0x00,0x00,0x00,0x00,
0x1F,0xF8,0x20,0x00,0x00,0x00,0xFF,0xFF,
0xE0,0x00,0x00,0x07,0xFF,0x81,0xE0,0x00,
0x00,0x07,0xE0,0x00,0xE0,0x00,0x00,0x03,
0x00,0x00,0x60,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};

char zuo16H[]={
0x18,0xC0,0x18,0xC0,0x19,0x80,0x31,0xFE,
0x33,0xFE,0x76,0xC0,0xF0,0xFC,0xB0,0xFC,
0x30,0xC0,0x30,0xC0,0x30,0xFE,0x30,0xFE,
0x30,0xC0,0x30,0xC0,0x30,0xC0,0x00,0x00,
};
char zhe16H[]={
0x03,0x00,0x03,0x0C,0x1F,0xCC,0x1F,0xD8,
0x03,0x30,0xFF,0xFE,0xFF,0xFE,0x03,0x00,
0x0F,0xF8,0x3F,0xF8,0xEC,0x18,0xCF,0xF8,
0x0C,0x18,0x0F,0xF8,0x0F,0xF8,0x00,0x00,
};

char tian16H[]={
0x00,0x00,0x3F,0xFC,0x3F,0xFC,0x31,0x8C,
0x31,0x8C,0x31,0x8C,0x3F,0xFC,0x3F,0xFC,
0x31,0x8C,0x31,0x8C,0x31,0x8C,0x3F,0xFC,
0x3F,0xFC,0x30,0x0C,0x00,0x00,0x00,0x00,
};
char xue16H[]={
0x33,0x18,0x19,0x98,0x08,0xB0,0x7F,0xFC,
0x7F,0xFC,0x60,0x0C,0x1F,0xF0,0x1F,0xF0,
0x00,0xC0,0x7F,0xFC,0x7F,0xFC,0x01,0x80,
0x01,0x80,0x07,0x80,0x03,0x00,0x00,0x00,
};
char ke16H[]={
0x00,0x00,0x0C,0x18,0xFD,0x98,0xF8,0xD8,
0x18,0x58,0xFE,0x18,0xFE,0x98,0x18,0xD8,
0x3C,0x58,0x7E,0x1E,0xDB,0xFE,0x9B,0xF8,
0x18,0x18,0x18,0x18,0x18,0x18,0x00,0x00,
};

struct Food/*定義結構體存儲食物的屬性*/
{
int x; /* 食物的坐標 */
int y;
int yes; /* 值為0表示屏幕上沒有食物,值為1表示屏幕上有食物 */
int color; /* 食物顏色 */
}food;

struct Snake/*定義結構體存儲蛇的屬性*/
{
int x[N]; /* 每一節蛇的坐標 */
int y[N];
int color[N];/*存儲每一節蛇的顏色*/
int node; /* 蛇的節數 */
int direction; /* 蛇移動的方向 */
int life; /* 蛇的生命,如果為1,蛇死,游戲結束 */
}snake;

void init(void)/*圖形驅動*/
{
int driver=DETECT,mode=0;
registerbgidriver(EGAVGA_driver);
initgraph(&driver,&mode,"");
}

void drawmat(char *mat,int matsize,int x,int y,int color)/*漢字點陣*/
{
int i,j,k,m;
m=(matsize-1)/8+1;
for(j=0;j<matsize;j++)
for(i=0;i<m;i++)
for(k=0;k<8;k++)
if(mat[j*m+i]&(0x80>>k))
putpixel(x+i*8+k,y+j,color);
}

void showword(void)
{/* 調用漢字點陣輸出程序,顯示標題和作者信息 */
drawmat(cai48H,48,249,-4,7);
drawmat(she48H,48,329,-4,7);
drawmat(tun48H,48,409,-4,7);
drawmat(dan48H,48,489,-4,7);

drawmat(cai48H,48,250,-5,4);
drawmat(she48H,48,330,-5,4);
drawmat(tun48H,48,410,-5,4);
drawmat(dan48H,48,490,-5,4);
/*作者 田學科*/
drawmat(zuo16H,16,515,465,7);
drawmat(zhe16H,16,530,465,7);

drawmat(tian16H,16,550,465,7);
drawmat(xue16H,16,565,465,7);
drawmat(ke16H,16,580,465,7);
}

void draw(void)/*畫出四周的牆*/
{
if(color==15)
color=0;
setcolor(++color);
setlinestyle(SOLID_LINE,0,1);

for(i=30;i<=600;i+=10)
{
rectangle(i,40,i+10,49);
rectangle(i,451,i+10,460);
}
for(i=40;i<450;i+=10)
{
rectangle(30,i,39,i+10);
rectangle(601,i,610,i+10);
}
}

void prscore(void)
{/* 列印游戲分數 */
char str[10];
setfillstyle(SOLID_FILL,YELLOW);
bar(50,10,200,30);
setcolor(6);
settextstyle(0,0,2);
sprintf(str,"score:%d",score);
outtextxy(55,15,str);
}

void gameover(void)
{
cleardevice(); /* 清屏函數 */
for(i=0;i<snake.node;i++)/* 畫出蛇死時的位置 */
{
setcolor(snake.color[i]);
rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]+10);
}
prscore(); /* 顯示分數 */
draw();
showword();
settextstyle(0,0,6);
setcolor(7);
outtextxy(103,203,"GAME OVER");
setcolor(RED);
outtextxy(100,200,"GAME OVER");
}

void gameplay(void)/* 玩游戲的具體過程 */
{
int flag,flag1;
randomize();
prscore();
gamespeed=50000;
food.yes=0;/* food.yes=0表示屏幕上沒有食物 */
snake.life=1;/* snake.life=1表示蛇是活著的 */
snake.direction=4;/* 表示蛇的初始方向為向右 */
snake.node=2; /* 蛇的初始化為兩節 */
snake.color[0]=2; /*兩節蛇頭初始化為綠色*/
snake.color[1]=2;
snake.x[0]=100;snake.y[0]=100;
snake.x[1]=110;snake.y[1]=100;
food.color=random(15)+1;
while(1)
{
while(1)
{
if(food.yes==0) /* 如果蛇活著 */
{
while(1)
{
flag=1;
food.yes=1;
food.x=random(56)*10+40;
food.y=random(40)*10+50;
for(i=0;i<snake.node;i++)
{
if(food.x==snake.x[i]&&food.y==snake.y[i])
flag=0;
}
if(flag) break;
}
}
if(food.yes)
{
setcolor(food.color);
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.y[0]-=10;break;
case 2: snake.y[0]+=10;break;
case 3: snake.x[0]-=10;break;
case 4: snake.x[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]<40||snake.x[0]>590||snake.y[0]<50||snake.y[0]>440)
{
gameover();
snake.life=0;
}

if(snake.life==0)
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.color[snake.node]=food.color;
snake.node++;
food.yes=0;
food.color=random(15)+1;
score+=10;
prscore();
if(score%100==0&&score!=0)
{
for(i=0;i<snake.node;i++)/* 畫出蛇 */
{
setcolor(snake.color[i]);
rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]+10);
}
sound(200);
delay(50000);delay(50000);delay(50000);
delay(50000);delay(50000);delay(50000);
nosound();
gamespeed-=5000;
draw();
}
else
{
sound(500);
delay(500);
nosound();
}
}

for(i=0;i<snake.node;i++)/* 畫出蛇 */
{
setcolor(snake.color[i]);
rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]+10);
}

delay(gamespeed);
delay(gamespeed);
flag1=1;
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(kbhit()&&flag1==1)/*如果沒按有效鍵就重新開始循環*/
{
flag1=0;
key=bioskey(0);
if(key==esc)
exit(0);
else if(key==up&&snake.direction!=2)
snake.direction=1;
else if(key==down&&snake.direction!=1)
snake.direction=2;
else if(key==left&&snake.direction!=4)
snake.direction=3;
else if(key==right&&snake.direction!=3)
snake.direction=4;
}
}
if(snake.life==0)/*如果蛇死了就退出循環*/
break;
}
}

void main(void)
{
while(1)
{
color=0;
init();
cleardevice();
showword();
draw();
gameplay();
setcolor(15);
settextstyle(0,0,2);
outtextxy(200,400,"CONTINUE(Y/N)?");
while(1)
{
key=bioskey(0);
if(key==Y||key==n||key==esc)
break;
}
if(key==n||key==esc)
break;
}
closegraph();
}

③ scratch編程貪吃蛇教程

scratch編程貪吃蛇教程:

1、首先,我們新建一個項目文件。

2、我們點擊添加精靈按鈕。

3、在彈出的對話框中,我們選繪制角色。

8、選中橡皮擦,代碼編輯區寫入以下代碼。

貪食蛇是一款經典的休閑游戲。有PC和手機等多平台版本,既簡單又耐玩。

④ 用C語言編寫 貪吃蛇的思路什麼怎麼樣的

把你的郵箱給我,我把源程序發給你,或者你自己從網上下載,這個snake程序芹畝是NetBSD操作系統源代碼的一部分,要是你能發現Bug,我先恭喜你。首巧

/者首鍵* $NetBSD: snake.c,v 1.9 1997/10/12 01:49:28 lukem Exp $ */

/*
* Copyright (c) 1980, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above right
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproce the above right
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This proct includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote procts derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/

#include <sys/cdefs.h>
#ifndef lint
__COPYRIGHT("@(#) Copyright (c) 1980, 1993\n\
The Regents of the University of California. All rights reserved.\n");
#endif /* not lint */

#ifndef lint
#if 0
static char sccsid[] = "@(#)snake.c 8.2 (Berkeley) 1/7/94";
#else
__RCSID("$NetBSD: snake.c,v 1.9 1997/10/12 01:49:28 lukem Exp $");
#endif
#endif /* not lint */

/*
* snake - crt hack game.
*
* You move around the screen with arrow keys trying to pick up money
* without getting eaten by the snake. hjkl work as in vi in place of
* arrow keys. You can leave at the exit any time.
*
* compile as follows:
* cc -O snake.c move.c -o snake -lm -ltermlib
*/

#include <sys/param.h>

#include <errno.h>
#include <fcntl.h>
#include <pwd.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

#include "snake.h"
#include "pathnames.h"

#define PENALTY 10 /* % penalty for invoking spacewarp */

#define EOT '\004'
#define LF '\n'
#define DEL '\177'

#define ME 'I'
#define SNAKEHEAD 'S'
#define SNAKETAIL 's'
#define TREASURE '$'
#define GOAL '#'

#define BSIZE 80

struct point you;
struct point money;
struct point finish;
struct point snake[6];

int loot, penalty;
int long tl, tm = 0L;
int moves;
char stri[BSIZE];
char *p;
char ch, savec;
char *kl, *kr, *ku, *kd;
int fast = 1;
int repeat = 1;
time_t tv;
char *tn;

int main __P((int, char **));

int
main(argc, argv)
int argc;
char **argv;
{
extern char *optarg;
extern int optind;
int ch, i;

(void) time(&tv);
srandom((int) tv);

while ((ch = getopt(argc, argv, "l:w:")) != -1)
switch ((char) ch) {
#ifdef notdef
case 'd':
tv = atol(optarg);
break;
#endif
case 'w': /* width */
ccnt = atoi(optarg);
break;
case 'l': /* length */
lcnt = atoi(optarg);
break;
case '?':
default:
fputs("usage: snake [-d seed] [-w width] [-l length]\n", stderr);
exit(1);
}

penalty = loot = 0;
getcap();

i = MIN(lcnt, ccnt);
if (i < 4) {
cook();
pr("snake: screen too small for a fair game.\n");
exit(1);
}
/*
* chunk is the amount of money the user gets for each $.
* The formula below tries to be fair for various screen sizes.
* We only pay attention to the smaller of the 2 edges, since
* that seems to be the bottleneck.
* This formula is a hyperbola which includes the following points:
* (24, $25) (original scoring algorithm)
* (12, $40) (experimentally derived by the "feel")
* (48, $15) (a guess)
* This will give a 4x4 screen $99/shot. We don't allow anything
* smaller than 4x4 because there is a 3x3 game where you can win
* an infinite amount of money.
*/
if (i < 12)
i = 12; /* otherwise it isn't fair */
/*
* Compensate for border. This really changes the game since
* the screen is two squares smaller but we want the default
* to be $25, and the high scores on small screens were a bit
* much anyway.
*/
i += 2;
chunk = (675.0 / (i + 6)) + 2.5; /* min screen edge */

signal(SIGINT, stop);
putpad(TI); /* String to begin programs that use cm */
putpad(KS); /* Put terminal in keypad transmit mode */

snrand(&finish);
snrand(&you);
snrand(&money);
snrand(&snake[0]);

if (ospeed < 9600 || ((!CM) && (!TA)))
fast = 0;
for (i = 1; i < 6; i++)
chase(&snake[i], &snake[i - 1]);
setup();
mainloop();
/* NOTREACHED */
return (0);
}

/* Main command loop */
void
mainloop()
{
int j, k;

for (;;) {
int c, lastc, match;

lastc = 0;
move(&you);
fflush(stdout);
if (((c = getchar() & 0177) <= '9') && (c >= '0')) {
ungetc(c, stdin);
j = scanf("%d", &repeat);
c = getchar() & 0177;
} else {
if (c != '.')
repeat = 1;
}
if (c == '.') {
c = lastc;
}
if ((Klength > 0) &&
(c == *KL || c == *KR || c == *KU || c == *KD)) {
savec = c;
match = 0;
kl = KL;
kr = KR;
ku = KU;
kd = KD;
for (j = Klength; j > 0; j--) {
if (match != 1) {
match = 0;
if (*kl++ == c) {
ch = 'h';
match++;
}
if (*kr++ == c) {
ch = 'l';
match++;
}
if (*ku++ == c) {
ch = 'k';
match++;
}
if (*kd++ == c) {
ch = 'j';
match++;
}
if (match == 0) {
ungetc(c, stdin);
ch = savec;
/* Oops! This works if we
* figure it out on second
* character. */
break;
}
}
savec = c;
if (j != 1)
c = getchar() & 0177;
}
c = ch;
}
if (!fast)
flushi();
lastc = c;
switch (c) {
case CTRL('z'):
suspend();
continue;
case EOT:
case 'x':
case 0177: /* del or end of file */
ll();
length(moves);
logit("quit");
done();
case CTRL('l'):
setup();
winnings(cashvalue);
continue;
case 'p':
case 'd':
snap();
continue;
case 'w':
spacewarp(0);
continue;
case 'A':
repeat = you.col;
c = 'h';
break;
case 'H':
case 'S':
repeat = you.col - money.col;
c = 'h';
break;
case 'T':
repeat = you.line;
c = 'k';
break;
case 'K':
case 'E':
repeat = you.line - money.line;
c = 'k';
break;
case 'P':
repeat = ccnt - 1 - you.col;
c = 'l';
break;
case 'L':
case 'F':
repeat = money.col - you.col;
c = 'l';
break;
case 'B':
repeat = lcnt - 1 - you.line;
c = 'j';
break;
case 'J':
case 'C':
repeat = money.line - you.line;
c = 'j';
break;
}
for (k = 1; k <= repeat; k++) {
moves++;
switch (c) {
case 's':
case 'h':
case '\b':
if (you.col > 0) {
if ((fast) || (k == 1))
pchar(&you, ' ');
you.col--;
if ((fast) || (k == repeat) ||
(you.col == 0))
pchar(&you, ME);
}
break;
case 'f':
case 'l':
case ' ':
if (you.col < ccnt - 1) {
if ((fast) || (k == 1))
pchar(&you, ' ');
you.col++;
if ((fast) || (k == repeat) ||
(you.col == ccnt - 1))
pchar(&you, ME);
}
break;
case CTRL('p'):
case 'e':
case 'k':
case 'i':
if (you.line > 0) {
if ((fast) || (k == 1))
pchar(&you, ' ');
you.line--;
if ((fast) || (k == repeat) ||
(you.line == 0))
pchar(&you, ME);
}
break;
case CTRL('n'):
case 'c':
case 'j':
case LF:
case 'm':
if (you.line + 1 < lcnt) {
if ((fast) || (k == 1))
pchar(&you, ' ');
you.line++;
if ((fast) || (k == repeat) ||
(you.line == lcnt - 1))
pchar(&you, ME);
}
break;
}

if (same(&you, &money)) {
loot += 25;
if (k < repeat)
pchar(&you, ' ');
do {
snrand(&money);
} while ((money.col == finish.col &&
money.line == finish.line) ||
(money.col < 5 && money.line == 0) ||
(money.col == you.col &&
money.line == you.line));
pchar(&money, TREASURE);
winnings(cashvalue);
continue;
}
if (same(&you, &finish)) {
win(&finish);
ll();
cook();
pr("You have won with $%d.\n", cashvalue);
fflush(stdout);
logit("won");
post(cashvalue, 1);
length(moves);
done();
}
if (pushsnake())
break;
}
fflush(stdout);
}
}

/*
* setup the board
*/
void
setup()
{
int i;

clear();
pchar(&you, ME);
pchar(&finish, GOAL);
pchar(&money, TREASURE);
for (i = 1; i < 6; i++) {
pchar(&snake[i], SNAKETAIL);
}
pchar(&snake[0], SNAKEHEAD);
drawbox();
fflush(stdout);
}

void
drawbox()
{
int i;
struct point p;

p.line = -1;
for (i = 0; i < ccnt; i++) {
p.col = i;
pchar(&p, '-');
}
p.col = ccnt;
for (i = -1; i <= lcnt; i++) {
p.line = i;
pchar(&p, '|');
}
p.col = -1;
for (i = -1; i <= lcnt; i++) {
p.line = i;
pchar(&p, '|');
}
p.line = lcnt;
for (i = 0; i < ccnt; i++) {
p.col = i;
pchar(&p, '-');
}
}

void
snrand(sp)
struct point *sp;
{
struct point p;
int i;

for (;;) {
p.col = random() % ccnt;
p.line = random() % lcnt;

/* make sure it's not on top of something else */
if (p.line == 0 && p.col < 5)
continue;
if (same(&p, &you))
continue;
if (same(&p, &money))
continue;
if (same(&p, &finish))
continue;
for (i = 0; i < 5; i++)
if (same(&p, &snake[i]))
break;
if (i < 5)
continue;
break;
}
*sp = p;
}

int
post(iscore, flag)
int iscore, flag;
{
short score = iscore;
int rawscores;
short uid;
short oldbest = 0;
short allbwho = 0, allbscore = 0;
struct passwd *p;

/*
* Neg uid, 0, and 1 cannot have scores recorded.
*/
if ((uid = getuid()) <= 1) {
pr("No saved scores for uid %d.\n", uid);
return (1);
}
if ((rawscores = open(_PATH_RAWSCORES, O_RDWR | O_CREAT, 0644)) < 0) {
pr("No score file %s: %s.\n", _PATH_RAWSCORES,
strerror(errno));
return (1);
}
/* Figure out what happened in the past */
read(rawscores, &allbscore, sizeof(short));
read(rawscores, &allbwho, sizeof(short));
lseek(rawscores, uid * sizeof(short), 0);
read(rawscores, &oldbest, sizeof(short));
if (!flag)
return (score > oldbest ? 1 : 0);

/* Update this jokers best */
if (score > oldbest) {
lseek(rawscores, uid * sizeof(short), 0);
write(rawscores, &score, sizeof(short));
pr("You bettered your previous best of $%d\n", oldbest);
} else
pr("Your best to date is $%d\n", oldbest);

/* See if we have a new champ */
p = getpwuid(allbwho);
if (p == NULL || score > allbscore) {
lseek(rawscores, 0, 0);
write(rawscores, &score, sizeof(short));
write(rawscores, &uid, sizeof(short));
if (allbwho)
pr("You beat %s's old record of $%d!\n",
p->pw_name, allbscore);
else
pr("You set a new record!\n");
} else
pr("The highest is %s with $%d\n", p->pw_name, allbscore);
close(rawscores);
return (1);
}

/*
* Flush typeahead to keep from buffering a bunch of chars and then
* overshooting. This loses horribly at 9600 baud, but works nicely
* if the terminal gets behind.
*/
void
flushi()
{
tcflush(0, TCIFLUSH);
}

int mx[8] = {
0, 1, 1, 1, 0, -1, -1, -1
};
int my[8] = {
-1, -1, 0, 1, 1, 1, 0, -1
};
float absv[8] = {
1, 1.4, 1, 1.4, 1, 1.4, 1, 1.4
};
int oldw = 0;

void
chase(np, sp)
struct point *sp, *np;
{
/* this algorithm has bugs; otherwise the snake would get too good */
struct point d;
int w, i, wt[8];
double v1, v2, vp, max;
point(&d, you.col - sp->col, you.line - sp->line);
v1 = sqrt((double) (d.col * d.col + d.line * d.line));
w = 0;
max = 0;
for (i = 0; i < 8; i++) {
vp = d.col * mx[i] + d.line * my[i];
v2 = absv[i];
if (v1 > 0)
vp = ((double) vp) / (v1 * v2);
else
vp = 1.0;
if (vp > max) {
max = vp;
w = i;
}
}
for (i = 0; i < 8; i++) {
point(&d, sp->col + mx[i], sp->line + my[i]);
wt[i] = 0;
if (d.col < 0 || d.col >= ccnt || d.line < 0 || d.line >= lcnt)
continue;
/*
* Change to allow snake to eat you if you're on the money,
* otherwise, you can just crouch there until the snake goes
* away. Not positive it's right.
*
* if (d.line == 0 && d.col < 5) continue;
*/
if (same(&d, &money))
continue;
if (same(&d, &finish))
continue;
wt[i] = i == w ? loot / 10 : 1;
if (i == oldw)
wt[i] += loot / 20;
}
for (w = i = 0; i < 8; i++)
w += wt[i];
vp = ((rand() >> 6) & 01777) % w;
for (i = 0; i < 8; i++)
if (vp < wt[i])
break;
else
vp -= wt[i];
if (i == 8) {
pr("failure\n");
i = 0;
while (wt[i] == 0)
i++;
}
oldw = w = i;
point(np, sp->col + mx[w], sp->line + my[w]);
}

void
spacewarp(w)
int w;
{
struct point p;
int j;
char *str;

snrand(&you);
point(&p, COLUMNS / 2 - 8, LINES / 2 - 1);
if (p.col < 0)
p.col = 0;
if (p.line < 0)
p.line = 0;
if (w) {
str = "BONUS!!!";
loot = loot - penalty;
penalty = 0;
} else {
str = "SPACE WARP!!!";
penalty += loot / PENALTY;
}
for (j = 0; j < 3; j++) {
clear();
delay(5);
apr(&p, str);
delay(10);
}
setup();
winnings(cashvalue);
}

void
snap()
{
struct point p;

if (you.line < 3) {
pchar(point(&p, you.col, 0), '-');
}
if (you.line > lcnt - 4) {
pchar(point(&p, you.col, lcnt - 1), '_');
}
if (you.col < 10) {
pchar(point(&p, 0, you.line), '(');
}
if (you.col > ccnt - 10) {
pchar(point(&p, ccnt - 1, you.line), ')');
}
if (!stretch(&money))
if (!stretch(&finish))
delay(10);
if (you.line < 3) {
point(&p, you.col, 0);
chk(&p);
}
if (you.line > lcnt - 4) {
point(&p, you.col, lcnt - 1);
chk(&p);
}
if (you.col < 10) {
point(&p, 0, you.line);
chk(&p);
}
if (you.col > ccnt - 10) {
point(&p, ccnt - 1, you.line);
chk(&p);
}
fflush(stdout);
}

int
stretch(ps)
struct point *ps;
{
struct point p;

point(&p, you.col, you.line);
if (abs(ps->col - you.col) < 6) {
if (you.line < ps->line) {
for (p.line = you.line + 1; p.line <= ps->line;
p.line++)
pchar(&p, 'v');
delay(10);
for (; p.line > you.line; p.line--)
chk(&p);
} else {
for (p.line = you.line - 1; p.line >= ps->line;
p.line--)
pchar(&p, '^');
delay(10);
for (; p.line < you.line; p.line++)
chk(&p);
}
return (1);
} else
if (abs(ps->line - you.line) < 3) {
p.line = you.line;
if (you.col < ps->col) {
for (p.col = you.col + 1; p.col <= ps->col;
p.col++)
pchar(&p, '>');
delay(10);
for (; p.col > you.col; p.col--)
chk(&p);
} else {
for (p.col = you.col - 1; p.col >= ps->col;
p.col--)
pchar(&p, '<');
delay(10);
for (; p.col < you.col; p.col++)
chk(&p);
}
return (1);
}
return (0);
}

void
surround(ps)
struct point *ps;
{
struct point x;
int j;

if (ps->col == 0)
ps->col++;
if (ps->line == 0)
ps->line++;
if (ps->line == LINES - 1)
ps->line--;
if (ps->col == COLUMNS - 1)
ps->col--;
apr(point(&x, ps->col - 1, ps->line - 1), "/*\\\r* *\r\\*/");
for (j = 0; j < 20; j++) {
pchar(ps, '@');
delay(1);
pchar(ps, ' ');
delay(1);
}
if (post(cashvalue, 0)) {
apr(point(&x, ps->col - 1, ps->line - 1), " \ro.o\r\\_/");
delay(6);
apr(point(&x, ps->col - 1, ps->line - 1), " \ro.-\r\\_/");
delay(6);
}
apr(point(&x, ps->col - 1, ps->line - 1), " \ro.o\r\\_/");
}

void
win(ps)
struct point *ps;
{
struct point x;
int j, k;
int boxsize; /* actually diameter of box, not radius */

boxsize = fast ? 10 : 4;
point(&x, ps->col, ps->line);
for (j = 1; j < boxsize; j++) {
for (k = 0; k < j; k++) {
pchar(&x, '#');
x.line--;
}
for (k = 0; k < j; k++) {
pchar(&x, '#');
x.col++;
}
j++;
for (k = 0; k < j; k++) {
pchar(&x, '#');
x.line++;
}
for (k = 0; k < j; k++) {
pchar(&x, '#');
x.col--;
}
}
fflush(stdout);
}

int
pushsnake()
{
int i, bonus;
int issame = 0;

/*
* My manual says times doesn't return a value. Furthermore, the
* snake should get his turn every time no matter if the user is
* on a fast terminal with typematic keys or not.
* So I have taken the call to times out.
*/
for (i = 4; i >= 0; i--)
if (same(&snake[i], &snake[5]))
issame++;
if (!issame)
pchar(&snake[5], ' ');
for (i = 4; i >= 0; i--)
snake[i + 1] = snake[i];
chase(&snake[0], &snake[1]);
pchar(&snake[1], SNAKETAIL);
pchar(&snake[0], SNAKEHEAD);
for (i = 0; i < 6; i++) {
if (same(&snake[i], &you)) {
surround(&you);
i = (cashvalue) % 10;
bonus = ((rand() >> 8) & 0377) % 10;
ll();
pr("%d\n", bonus);
delay(30);
if (bonus == i) {
spacewarp(1);
logit("bonus");
flushi();
return (1);
}
if (loot >= penalty) {
pr("You and your $%d have been eaten\n",
cashvalue);
} else {
pr("The snake ate you. You owe $%d.\n",
-cashvalue);
}
logit("eaten");
length(moves);
done();
}
}
return (0);
}

int
chk(sp)
struct point *sp;
{
int j;

if (same(sp, &money)) {
pchar(sp, TREASURE);
return (2);
}
if (same(sp, &finish)) {
pchar(sp, GOAL);
return (3);
}
if (same(sp, &snake[0])) {
pchar(sp, SNAKEHEAD);
return (4);
}
for (j = 1; j < 6; j++) {
if (same(sp, &snake[j])) {
pchar(sp, SNAKETAIL);
return (4);
}
}
if ((sp->col < 4) && (sp->line == 0)) {
winnings(cashvalue);
if ((you.line == 0) && (you.col < 4))
pchar(&you, ME);
return (5);
}
if (same(sp, &you)) {
pchar(sp, ME);
return (1);
}
pchar(sp, ' ');
return (0);
}

void
winnings(won)
int won;
{
struct point p;

p.line = p.col = 1;
if (won > 0) {
move(&p);
pr("$%d", won);
}
}

void
stop(mmy)
int mmy;
{
signal(SIGINT, SIG_IGN);
ll();
length(moves);
done();
}

void
suspend()
{
ll();
cook();
kill(getpid(), SIGTSTP);
raw();
setup();
winnings(cashvalue);
}

void
length(num)
int num;
{
pr("You made %d moves.\n", num);
}

void
logit(msg)
const char *msg;
{
FILE *logfile;
time_t t;

if ((logfile = fopen(_PATH_LOGFILE, "a")) != NULL) {
time(&t);
fprintf(logfile, "%s $%d %dx%d %s %s",
getlogin(), cashvalue, lcnt, ccnt, msg, ctime(&t));
fclose(logfile);
}
}

⑤ scratch貪吃蛇製作教程

scratch貪吃蛇製作教程如下:

1、游戲工亮輪作過程。鍵盤主要控制貪吃蛇的頭部移動,尾巴是沿著軌跡移動就行。貪吃蛇的身體,是用程序畫筆模塊敬差信畫出來的。如果頭部吃到食物,就給游戲分數加分。

6、最終游戲效果:點擊「綠色旗子」開始游戲,按下鍵盤的方向鍵,控制貪吃蛇移動。

吃到食物時,變數「游戲分數」就會加1分。

⑥ 利用解釋型語言編寫的貪吃蛇程序什麼意思

用C語言來實現也是一個好玩的事情。這個游戲我寫完後放在知乎,竟然點贊的人數超級多。我覺得大家喜歡,一個方面是因為寫得簡單,大家都能看得懂,一個可擴展性還是非常強的。

我試了說一下這個代碼 核心的三個函數

menu();

setup();

draw();

menu用來設置菜單,也就是我們一運行看到的那個。setup用來設置參數,我們需要設置高度和寬度,還有分搜清橘數,食物的位置。draw也就是畫,也就是畫整個畫面。

還有一個枚舉類型 這個結構體用來設置蛇的幾個狀態,我覺得這個也是面向對象編程的一個思想,把蛇的狀態都封裝成一個枚舉類型。

typedef enum

{
STOP = 0,

LEFT,

RIGHT,

UP,

DOWN

}Direction;

還有

/*判斷貪吃蛇的長度*/

void logic()

這個函數,這個函數應該是整個貪吃蛇的精髓了,要理解代碼怎麼把蛇給連接起來。用了點巧妙的東西。

來看這裡面的關鍵代碼

/*把上一個位置記下*/

int lastX = tailX[0];

int lastY = tailY[0];

int last2X, last2Y;

/*重新獲取當前的位置*/

tailX[0]=x;

tailY[0]=y;

int i=0;

/*遍歷整條蛇的長度 把 0 的位置空出來正悶,其餘蛇的位置往後面的空間移動*/

for(i=1; i ntail;i++)

{
last2X = tailX[i];

last2Y = tailY[i];

tailX[i]=lastX;

tailY[i]=lastY;

lastX = last2X;

lastY = last2Y;

}

lastX lastY 用來存上一次的蛇頭的位置。後面的 for 循環,通過tail 蛇的長度,把蛇上個狀態給保存到數組tailX tailY裡面。

完整代碼

#include stdio.h

#include stdlib.h

#include stdbool.h

#include Windows.h

#include time.h

#include conio.h /*鍵盤輸入獲取*/

bool gameOver;

bool stop = false;

bool hit = false;

/*游戲的邊框大小*/

const int width = 50;

const int height = 20;

/*蛇的坐標,食物的坐標還有分數*/

int x,y,fruitX,fruitY,score;

/*蛇每個點的坐標*/

int tailX[200],tailY[200];

/*蛇的默認長度*/

int ntail=3;

typedef enum

{
STOP = 0,

LEFT,

RIGHT,

UP,

DOWN

}Direction;

Direction Dir;

/*開始菜單*/

void menu()

{
int a;

printf( ------------------------------------------------------------------\n

printf( | 貪吃蛇游戲 |\n

printf( | 1) 新游戲 |\n

printf( | 2) 開始邊界 |\n

printf( | 3) 退出遊戲 |\n

printf( ------------------------------------------------------------------\n

printf( ---- 請輸入你的選擇:

scanf( %d ,

}

/*初始化狀態*/

void setup()

{
gameOver = false;

/*根據當前時間設置「隨機數種子」*/

srand(time(NULL));

Dir = STOP;

/*貪吃蛇的位置,固定在中間*/

x= width/2;

y= height/2;

/*食物的位置,位置是隨機的*/

fruitX = rand()%width;

fruitY = rand()%height;

score = 0;

}

/*繪制界面世團*/

void draw()

{
if(stop == true)

{
return;

}

system( cls /*清除屏幕*/

printf( 分數:%d ,score);

printf( \n

/*第一行*/

int i;

for(i= 0 ;i width+1;i++)

{
printf( -

}

printf( \n

/*畫中間的畫面*/

int p;

for(p= 0 ;p height;p++)/*高度*/

{
int q;

for(q= 0 ;q width;q++)/*寬度*/

{
/*第一行最後已給字元*/

if(q==0 || q==width-1)

{
printf( |

}

if(p == fruitY q == fruitX)/*食物的隨機坐標*/

{
printf( O

}

else

{
int k=0;

bool print = false;

/*貪吃蛇的長度 默認長度是 3*/

for(k=0;k ntail;k++)

{
if(tailX[k]==q tailY[k]==p)

{
printf( *

print = true;

}

}

/*如果這個位置列印了 * 就不要列印空格了*/

if(!print)

{
printf(

}

}

}

printf( \n

}

/*最後一行*/

int j;

for(j= 0 ;j width+1;j++)

{
printf( -

}

}

/*按鍵輸入控制*/

void input()

{
if(_kbhit())

{
/*獲取鍵盤的輸入字元*/

switch(_getch())

{
case 4 :

case 75:/*左鍵*/

Dir = LEFT;

hit= true;

break;

case 8 :

case 72:/*上鍵*/

Dir = UP;

hit= true;

break;

case 6 :

case 77:/*右鍵*/

Dir = RIGHT;

hit= true;

break;

case 2 :

case 80:/*向下鍵盤鍵 */

Dir = DOWN;

hit= true;

break;

case x :

case 27:/*ESE*/

gameOver = true;

break;

case 32:/*空格 暫停鍵*/

stop = !stop;

break;

}

}

else if(!hit stop == false)/*如果沒有改變方向*/

{
x++;

}

}

/*判斷貪吃蛇的長度*/

void logic()

{
if(stop == true)

{
return;

}

/*把上一個位置記下*/

int lastX = tailX[0];

int lastY = tailY[0];

int last2X, last2Y;

/*重新獲取當前的位置*/

tailX[0]=x;

tailY[0]=y;

int i=0;

/*遍歷整條蛇的長度 把 0 的位置空出來,其餘蛇的位置往後面的空間移動*/

for(i=1; i ntail;i++)

{
last2X = tailX[i];

last2Y = tailY[i];

tailX[i]=lastX;

tailY[i]=lastY;

lastX = last2X;

lastY = last2Y;

}

/*根據方向來改變x y 的值*/

switch(Dir)

{
case UP:

y--;

break;

case DOWN:

y++;

break;

case LEFT:

x--;

break;

case RIGHT:

x++;

break;

}

if(x 0 || width x || y 0 || height y)

{
gameOver = true;

/*清除屏幕*/

system( cls

printf( ------------------------------------------------------------------\n

printf( | |\n

printf( | |\n

printf( | 游戲結束 |\n

printf( | |\n

printf( | |\n

printf( ------------------------------------------------------------------\n

}

if(x==fruitX y==fruitY)

{
/*吃了一個食物,蛇的長度增加1*/

ntail++;

score+=10;

/*更新下一個食物的位置*/

fruitX = rand()%width;

fruitY = rand()%height;

}

}

int main()

{
#if 0

while(1)

{
printf( %d\n ,_getch());

}

#endif

menu();

setup();

draw();

/*循環畫貪吃蛇的界面*/

while(!gameOver)

{
draw();

input();

logic();

Sleep(70);

}

return 0;

}

上面這段代碼直接在Dev C++上面應該是可以運行的,很多人在知乎上私信問我,為什麼我的貪吃蛇執行不了呢,可能就是平台不同,少了這個頭文件,少了那個頭文件,但是你為什麼不能跟我一樣,用Dev C++呢,輕量級,簡單。代碼的精髓是什麼?我認為精髓一定是思想,不是你寫了多少行代碼,用了什麼高端的IDE。

我自認為我的注釋已經寫得不錯了,所以就沒有什麼好說明的了吧,有不明白的把代碼過一下,至於屏幕刷新這個東西,如果只是用時間刷新就會閃屏,所以出現了一個雙緩存,把要顯示的東西送到一個buff裡面去,另一個buff用來顯示,這樣就可以保證不會出現閃屏。除了寫貪吃蛇,可以用這個方法寫其他小程序,挺有意思的。

在知乎上,發起了一個C語言 100 行代碼之內實現貪吃蛇的問題。我覺得很不錯,裡面很多同學的回復都非常贊,特別是葉大神的回復。

0142235ea7197f4e1d7ClTovj.png

學習C/C++編程知識,想要成為一個更加優秀的程序員,或者你學習C/C++的時候有難度,可以來UP主頁的C++編程學習圈,裡面不僅有學習視頻和文件資料,還有更多志同道合的朋友,歡迎初學者和想轉行的朋友,和大家一起交流成長會比自己琢磨更快哦! UP也上傳了一些C/C++學習的視頻教程和C語言基礎教程,有興趣的小夥伴可以看看~ 謝謝閱讀!

文章知識點與官方知識檔案匹配
C技能樹首頁概覽
115488 人正在系統學習中
點擊閱讀全文
打開CSDN APP,看更多技術內容

C語言之出圈游戲(詳解)
PTA7-5 出圈游戲 用指針實現以下功能:有n個人圍成一個圈,順序排號。從第1個人開始報數(從1到3報數),凡報到3的人退出圈子,問最後留下的是原來的第幾號。 (1)編程提示 每三個人離開,置為0;當數到最後一個人時,將指針重新指向第一個人;m表示離開的人數,當m=n-1時,說明只剩下一個人,循環結束。 輸入樣例: 10 輸出樣例: 4 上面是題目的要求。 本小白的思路是讓n個人形成一個一維數組,每次判斷該人是不是要離開, 如果離開,這就不添加到這個一維數組里,並記錄下來離開的人數,否則,就在數組里加上這
繼續訪問
9718 整數因子分解(優先做)
9718 整數因子分解(優先做)Description輸入格式輸出格式輸入樣例輸出樣例 時間限制:1000MS 代碼長度限制:10KB 提交次數:0 通過次數:0 題型: 編程題 語言: G++;GCC;VC Description 大於1的正整數 n 都可以分解為 n = x1 * x2 * … * xm, 每個xi為大於1的因子,即1<xi<=n 。 例如:當n=12時,共有8種不同的分解式: 12 = 12 12 = 62 12 = 43 12 = 34 12 = 322 12 =
繼續訪問
【C語言】鏈表——圈中游戲問題(數到3退出)
問題描述: 有n個人圍成一圈,從第1個人開始報數1、2、3,每報到3的人退出圈子。使用鏈表找出最後留下的人。
繼續訪問
套圈游戲c語言程序設計教程課後答案,概率統計習題帶答案
概率論與數理統計習題及題解沈志軍 盛子寧第一章 概率論的基本概念1.設事件B A ,及B A 的概率分別為q p ,及r ,試求)(),(),(B A P B A P AB P 及)(AB P2.若C B A ,,相互獨立,試證明:C B A ,,亦必相互獨立。3.試驗E 為擲2顆骰子觀察出現的點數。每種結果以),(21x x 記之,其中21,x x 分別表示第一顆、第二顆骰子的點數。設事件}10...
繼續訪問
c語言貪吃蛇設計意義,C語言貪吃蛇設計理念.pdf
基於C語言的 「貪吃蛇」游戲的設計與實現摘3.功能描述 本游戲主要實現以下幾種功能:「貪吃蛇」游戲貪 游 游吃 戲 戲蛇 顯 分的 ...
繼續訪問
熱門推薦 一個好玩的小游戲(純C語言編寫)
最近在看知乎是發現了一個這一個專欄 https://zhuanlan.hu.com/c2game 從中獲取的許多知識,本文中的游戲也是從裡面學到的,不過本人又自己加了一些功能。 這是一個類似於飛機大戰的游戲,不過目前代碼量比較小,所以看起來非常簡陋游戲界面如下 更新日誌,本人將原來的原來的代碼有進一步的優化了一下,之前是只有一個非常小的戰機現在更新後可以產生一個非常大的戰機(看起來也更
繼續訪問
如何用C語言實現圈叉游戲(-)
今天情人節,還是在學習C語言 自己寫了一遍發現自己寫的沒有書上的代碼更簡練 就把書上的代碼稍微修改了一下 下面看游戲界面 和昨天的米字棋差不多,有時間會結合米字旗的代碼做些修改
繼續訪問
C語言:圍圈報數游戲
游戲規則:有N個人圍成一圈,順序排號,從第一個人開始1到D報數,,凡報到D的人退出圈子(下場),問最後留下來的是原來的第幾號? 邏輯思想:用布爾數組記下每個人的上場狀態,1為上場,0為下場,開始游戲後每D個狀態為1的人將狀態改為0(即下場),重復下場動作N-1次後可知剩下一人,遍歷數組找出剩下的狀態為1的人即可。 代碼如下: #include<stdio.h> #define N 1000 //參與的總人數 #define D 3 //每D個人報數下場 int main() { /
繼續訪問

數圈圈
26個大寫字母裡面,有一部分字母是帶有圈的,比如A有1個圈,B有2個圈,C沒有圈, 給你一個帶有n個大寫字母組成的字元串,請問一共有多少個圈圈。 你可以將字母中完全封閉的一個區域當作一個圈 輸入描述: 第一行輸入一個整數t,代表有t組測試數據, 對於每組測試數據, 第一行輸入一個整數n代表字元串的長度, 第二行輸入一個長度為n的字元串S,保證只由大寫字母組成。 1<=t<=10 1<=n<=1*10^5 輸出描述: 對於每組測試數據,輸出一個整數代表這個字元串共有多少個圈圈。 並且對
繼續訪問
C語言圍圈游戲
玩游戲,一共 N( 1≤N≤1000 )個人圍成一圈,從某個人起順時針順序編號為 1 ~ N 號。 游戲只能有一個人贏,船長讓大家數數,從編號為 1 的人開始順時針報數,每輪從 1 報到 M 號( 1≤ M ),凡報到 M 的人視為出局,接著又從緊鄰的下一個人開始同樣的報數(緊鄰的下一個人又報 1 )。 依次輸入人數 N ,和報數規則的末數 M ,中間隔一個空格。輸出能贏的相應編號R。 #include<stdio.h> int main() {...
繼續訪問
圈中游戲
有n個人圍成一圈,從第1個人開始報數1、2、3,每報到3的人退出圈子。編程使用鏈表找出最後留下的人。 bug版本 #include <stdio.h> #include <stdlib.h> struct player { long num; struct player *next; }; typedef struct player NODE; NODE *create(int n) { NODE *head, *tail, *p; int i =
繼續訪問
c語言圈中的游戲,C語言實現掃雷游戲
本文將介紹如何用C語言多文件編程實現掃雷該示例掃雷程序可實現以下幾個功能:自定義雷數踩雷後會將所有雷顯示出來地圖大小易修改Mine_clearance.h#pragma once#define _CRT_SECURE_NO_WARNINGS#include#include#include#define ROW 11#define COL 11#define 踩雷 0#define 玩家勝利 1in...
繼續訪問

c語言程序設計求各位數之和,C語言for迴圈設計輸入一個正整數,求它的各位數字之和及位數 例如234的各位數之和為9 位數是3...
C語言for迴圈設計輸入一個正整數,求它的各位數字之和及位數 例如234的各位數之和為9 位數是3以下文字資料是由(歷史新知網www.lishixin.com)小編為大家搜集整理後發布的內容,讓我們趕快一起來看一下吧!C語言for迴圈設計輸入一個正整數,求它的各位數字之和及位數 例如234的各位數之和為9 位數是3同意二樓,但得改一下#includeint main(int argc, ch...
繼續訪問

c語言draw函數使用實例,使用函數實現兩個數的交換(C語言)
<>題目:使用函數實現兩個數的代碼<>常規思路:定義函數,調用函數,完成交換。你的代碼是否和下面一樣呢?#include #include void Swap(int a,int b) { int tmp = a; a =b; b = tmp; } int main() { int x = 10; int y = 20; Swap(x,y); printf("%d %d\n...
繼續訪問
圈中的游戲 c語言,圈叉棋小游戲的簡單實現代碼
該樓層疑似違規已被系統折疊隱藏此樓查看此樓#include int game[3][3]={0};void Show(int turn,int x,int y){int i=0,j=0;if(x>0 && y>0){if(turn%2){game[x-1][y-1]=1;}else{game[x-1][y-1]=-1;}}for(i=0;i<3;++i){for...
繼續訪問
c語言圈中的游戲,圈叉棋小游戲的簡單實現代碼
該樓層疑似違規已被系統折疊隱藏此樓查看此樓#include int game[3][3]={0};void Show(int turn,int x,int y){int i=0,j=0;if(x>0 && y>0){if(turn%2){game[x-1][y-1]=1;}else{game[x-1][y-1]=-1;}}for(i=0;i<3;++i){for...

java 編寫貪吃蛇游戲的大體思路是什麼

樓主沒有看到蛇移動的本質,蛇雖然是分成很多塊,但他們還是一個整體,每一塊的移動都和上一塊有關,所以不需要對每一塊都進行判斷。x0dx0a原理:x0dx0a把蛇身體的每一塊看成一個對象(對象存儲該塊的坐標和相關信息),作為節點存儲在線性鏈表中,再設置一個變數標志蛇的方向(通過按鍵可以改變)。一般人都是讓每一個節點等於他指向的下一個節點,並讓頭節點改變位置來實差局現轉彎和移動,這個演算法復雜度太高(O(n)),實際上只要做兩步操作,插入一個頭節點,刪除一個尾節點就可以了,新插入的頭節點位置根據蛇當前的方向決定 用一個數組將蛇頭的行徑記錄下來,然後第二段的下一個方格設置為蛇頭走過的方格,這樣子蛇走過的路徑都是前一段走過的,最後將跟著蛇頭走了,比如x0dx0a蛇身的路徑x0dx0a for(int i=snakeLength-1;i>0;i--){x0dx0arows[i]=rows[i-1];//依次將蛇前面一段走過行的路段賦值給蛇的下一段x0dx0acols[i]=cols[i-1];//依次將蛇前面一段走過列的路段賦值給蛇的下一段x0dx0a}x0dx0afor(int i=1;i

⑧ 如何用慧編程做貪吃蛇代碼

用慧編程做貪吃蛇代碼過程如下:
1、我們需要建立四個頭文件,然後分別設置蛇的狀態,上下左右,這是蛇能夠有方向可走的前提,然後我們再設置蛇身的節點,定義一個簡單的函數,這樣蛇的全身以及他的行走方向就弄完了。
2、貪吃蛇不能穿牆代碼。
3、第二步,一個函數這個函數的目的是貪吃蛇不能穿牆,很簡單的代碼分別設置長寬的最大位移,在內部范圍內設置為一即可通過,否則不能穿牆。貪吃蛇隨機生成一個食物。
4、設置一個隨機函數。這樣貪吃蛇代碼就做好了。
慧編程是一款面向STEAM教育領域的積木式和代碼編程軟體,基於圖形化編程開發。

⑨ c語言 貪吃蛇 程序

基本思路:

蛇每吃一個食物蛇身子就增加一格,用UP, DOWN, LEFT, RIGHT控制蛇頭的運動,而蛇身子跟著蛇頭走,每後一格蛇身子悉薯橋下一步走到上一格蛇身子的位置睜猛,以此類推。

#include <stdio.h>

#include <conio.h>

#include <windows.h>

#define BEG_X2

#define BEG_Y1

#define WID20

#define HEI20

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;

}

(9)貪吃蛇編程思路擴展閱讀:

實現邏輯

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

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

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

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

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

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

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

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

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

⑩ java貪吃蛇技術選型怎麼寫的

Java貪吃蛇技術選型一般需要考慮以下幾點:

閱讀全文

與貪吃蛇編程思路相關的資料

熱點內容
微信聊天界面源碼 瀏覽:24
seo競價推廣點擊價格演算法公式 瀏覽:319
框架結構可以加密嗎 瀏覽:218
python編譯器怎麼清除 瀏覽:73
linux全局socks代理 瀏覽:611
php微信抽獎 瀏覽:771
壓縮演算法嵌入式移植 瀏覽:531
php新手小例子 瀏覽:233
按照醫生的演算法一周是幾天 瀏覽:805
三次b樣條曲線演算法 瀏覽:924
java7特性 瀏覽:555
愛山東app小學報名怎麼知道報沒報上 瀏覽:458
android獲取wifi信號 瀏覽:133
娜拉美妝app怎麼使用 瀏覽:760
有了源碼要買伺服器嗎 瀏覽:365
app怎麼查看自己的存款利息 瀏覽:515
碧藍安卓與b站有什麼區別 瀏覽:342
php靜態塊 瀏覽:719
ftpmget命令 瀏覽:475
源碼時代怎樣 瀏覽:415