貪吃蛇實驗

2021-10-12 05:50:12 字數 3293 閱讀 3004

總的來說共分為三個部分:遊戲介面、食物、蛇。

遊戲介面很簡單,不多贅述。

食物要實現隨機出現在介面內。

蛇部分是重難點,要實現其移動、吃食物、身體的移動、碰撞檢測等等。

我運用了for迴圈來列印出整個遊戲介面,以下為**部分:

void

print_wall()

cout <<

" ";

for(

int i =

1; i <= n; i++

) cout <<

"-";

}

先要實現其隨機出現,即使用random函式;

且不能出現在牆上、蛇的身上。

以下為**段:

bool

print_food()

}if(e)break;}

locate

(food.x, food.y)

; cout <<

"$";

return

true

;}

設定乙個蛇的初始長度為3,列印蛇頭為「@」,蛇身為「 * 」。

以下為蛇部分**:

void

print_snake()

}

以及對蛇移動的操控,在鍵盤上按下「↑↓←→」鍵時,相應的蛇頭進行x、y值得加減,並蛇身隨著蛇頭進行移動。此處部分我運用了switch函式:

if

(kbhit()

)}}

相應的,遊戲中應實現對蛇撞牆或自撞的判斷,並結束遊戲:

bool

is_correct()

return

true

;}

#include

#include

#include

#include

#include

#include

#include

using

namespace std;

/*** 游標定位 ***/

handle hout =

getstdhandle

(std_output_handle)

;coord coord;

void

locate

(int x,

int y)

;/*** 隱藏游標 ***/

void

hide()

;setconsolecursorinfo

(hout,

&cursor_info);}

/*** 生成隨機數 ***/

double

random

(double start,

double end)

/*** 定義地圖的長寬,蛇的座標,長度,方向,食物的位置 ***/

int m, n;

struct node

snake[

1000];

int snake_length, dir;

node food;

int direct[4]

[2]=

,,,}

;/*** 輸出牆 ***/

void

print_wall()

cout <<

" ";

for(

int i =

1; i <= n; i++

) cout <<

"-";

}/*** 首次輸出蛇,其中snake[0]代表頭 ***/

void

print_snake()

}/*** 判斷是否撞牆或者自撞 ***/

bool

is_correct()

return

true;}

/*** 隨機生成並輸出食物位置 ***/

bool

print_food()

}if(e)break;}

locate

(food.x, food.y)

; cout <<

"$";

return

true;}

/*** 蛇的前進 ***/

bool

go_ahead()

/*** 輸出此時蛇狀態 ***/if(

!e)else

print_food()

;locate

(snake[0]

.x, snake[0]

.y);

cout <<

"@";

/*** 如果自撞 ***/if(

!is_correct()

)return

true;}

/*** 主函式 ***/

intmain()

int hard;

cin >> hard;

if(hard <=

0|| hard >

100)

/*** 資料全部初始化,包括蛇長,位置,方向 ***/

snake_length =5;

clock_t a, b;

char ch;

double hard_len;

for(

int i =

0; i <=

4; i++

) dir =3;

/*** 輸出初始地圖,蛇與食物 ***/

system

("cls");

hide()

;print_wall()

;print_food()

;print_snake()

;locate

(m +2,

0); cout <<

"now length: "

; cout <<

" speed"

while(1

)/*** 接受鍵盤輸入的上下左右,並以此改變方向 ***/if(

kbhit()

)}}/*** 前進 ***/if(

!go_ahead()

)break

;/*** 在最後輸出此時長度 ***/

locate

(m +2,

12); cout << snake_length;

}system

("pause");

return0;

}

貪吃蛇遊戲實驗報告

使用教材 c語言課程設計與遊戲開發實踐 一 實驗目的 熟悉實驗環境vc 或dev c 熟悉console的輸入和輸出 通過遊戲的需求,進一步掌握陣列的使用。二 實驗環境 dev c vc 三 實驗記錄 實驗思路 以實驗教材p87至p91頁的 為基礎,加入計分功能,計命功能,變速功能,遊戲成功和失敗出...

貪吃蛇遊戲

貪吃蛇遊戲 結構化程式設計 c語言程式設計 重要的的是結構化的程式設計思想 include include include include include include define field width 300 就做20個格仔的 define field height 300 define f...

貪吃蛇(改進)

該程式分成3個檔案 第乙個檔案 fang.cs using system using system.collections.generic using system.text using system.windows.forms using system.drawing namespace snak...