1. 程式人生 > >簡單的snake小遊戲

簡單的snake小遊戲

跟著視訊做了一個貪吃蛇的專案,主要是瞭解邏輯,發現還差得遠呢,繼續努力

# include<iostream>
# include<ctime>
# include<Windows.h>
# include<conio.h>
/*conio.h不是C標準庫中的標頭檔案,在C standard library,ISO C 和POSIX標準中均沒有定義。
conio是Console Input / Output(控制檯輸入輸出)的簡寫,其中定義了通過控制檯進行資料輸
入和資料輸出的函式,主要是一些使用者通過按鍵盤產生的對應操作,比如getch()函式等等。*/
using namespace std; const int width = 28; const int height = 14; int x, y, fruitx, fruity, score; bool gameOver; enum eDirection{STOP=0,LEFT,RIGHT,UP,DOWN}; eDirection dir; int xTail[50], yTail[50];//蛇尾部(除去頭部) int nTail = 0; void Setup(); void Draw(); void Input(); void Logic(); int main() { Setup(); while
(!gameOver) { Draw(); Input(); Logic(); Sleep(50); } cout << endl; system("pause"); return 0; } void Setup() { gameOver = false; dir = STOP; x = width / 2; y = height / 2; srand(time(0)); fruitx = rand() % width; fruity = rand() % height; score = 0
; } void Draw() { system("cls");//clear the screen for (int i = 0;i < width+2 ;i++)//寬為width+2 cout << "#"; cout << endl; for (int i = 0;i < height;i++)//出除去首尾兩列 { for (int j = 0;j < width;j++) { //####### //# # //# # //####### if (j == 0) cout << "#"; if (i == y&&j == x) cout << "O"; else if (i == fruity&&j == fruitx) cout << "F"; else { bool printBlank = true; for (int k = 0;k < nTail;k++) { if (xTail[k] == j&&yTail[k] == i) { printBlank = false; cout << "o"; } } if (printBlank) cout << " "; } if (j == width - 1) cout << "#"; } cout << endl; } for (int i = 0;i < width+2 ;i++) cout << "#"; cout << endl << "Score:" << score; cout << endl << "食物座標:" << "(" << fruitx << "," << fruity << ")" << endl; } void Input() { if (_kbhit()) { /* w a d s */ switch (_getche()) { case 'a': dir = LEFT; break; case 'd': dir = RIGHT; break; case 'w': dir = UP; break; case 's': dir = DOWN; break; case 'x': gameOver = true; break; default: break; } } } void Logic() { int prevX = xTail[0]; int prevY = yTail[0]; int prev2X, prev2Y; xTail[0] = x; yTail[0] = y; for (int i = 1;i < nTail;i++) { prev2X = xTail[i]; prev2Y = yTail[i]; xTail[i] = prevX; yTail[i] = prevY; prevX = prev2X; prevY = prev2Y; } switch (dir) { case LEFT: x--; break; case RIGHT: x++; break; case UP: y--; break; case DOWN: y++; break; default: break; } if (x <0 || x > width || y <0 || y >height) gameOver = true; if (fruitx == x&&fruity == y) { nTail++; score += 10; fruitx = rand() % width; fruity = rand() % height; } }

這裡寫圖片描述
這裡寫圖片描述