Created
December 16, 2015 07:04
-
-
Save zbjxb/32a685f6e5057dba5051 to your computer and use it in GitHub Desktop.
控制台版贪吃蛇
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdlib.h> | |
#include <conio.h> | |
using namespace std; | |
enum eDirection { STOP, UP, LEFT, RIGHT, DOWN }; | |
eDirection dir; | |
bool gameOver; | |
const int width = 20; | |
const int height = 20; | |
int x, y, fruitX, fruitY, score; | |
int tailX[100], tailY[100]; | |
int nTail; | |
void Setup() | |
{ | |
gameOver = false; | |
x = width / 2; | |
y = height / 2; | |
fruitX = rand() % width; | |
fruitY = rand() % height; | |
score = 0; | |
dir = STOP; | |
nTail = 1; | |
tailX[0]=x; | |
tailY[0]=y; | |
} | |
void Draw() | |
{ | |
system("cls"); // system("clear") | |
for(int i = 0; i < width+2; i++) | |
cout << "#"; | |
cout << endl; | |
for(int i = 0; i < height; i++) { | |
for(int j = 0; j < width; j++) { | |
if(j == 0) | |
cout << "#"; | |
if (j==tailX[0] && i==tailY[0]) { | |
cout << "O"; | |
} | |
else if(j == fruitX && i == fruitY) | |
cout << "F"; | |
else { | |
bool hasBlock = false; | |
for (int m=1;m<nTail;m++) { | |
if (j==tailX[m] && i==tailY[m]) { | |
hasBlock = true; | |
cout << "o"; | |
break; | |
} | |
} | |
if (!hasBlock) | |
cout << " "; | |
} | |
if(j == width - 1) | |
cout << "#"; | |
} | |
cout << endl; | |
} | |
for(int i = 0; i < width+2; i++) | |
cout << "#"; | |
cout << endl; | |
cout << score << endl; | |
} | |
void Input() | |
{ | |
if(_kbhit()) { | |
switch(_getch()) { | |
case 'w': | |
dir = UP; | |
break; | |
case 'a': | |
dir = LEFT; | |
break; | |
case 's': | |
dir = DOWN; | |
break; | |
case 'd': | |
dir = RIGHT; | |
break; | |
case 'x': | |
gameOver = true; | |
break; | |
} | |
} | |
} | |
void Logic() | |
{ | |
int prevX=x, prevY=y; | |
int tmpX,tmpY; | |
switch(dir) { | |
case UP: | |
y--; | |
break; | |
case LEFT: | |
x--; | |
break; | |
case DOWN: | |
y++; | |
break; | |
case RIGHT: | |
x++; | |
break; | |
default: | |
break; | |
} | |
if(x <= 0 || x >= width - 1) | |
x = (x + width) % width; | |
if(y <= 0 || y >= height - 1) | |
y = (y + height) % height; | |
if (prevX!=x || prevY!=y) { | |
tmpX=tailX[nTail-1]; | |
tmpY=tailY[nTail-1]; | |
for (int i=nTail-1;i>0;i--) { | |
tailX[i]=tailX[i-1]; | |
tailY[i]=tailY[i-1]; | |
} | |
tailX[0]=x; | |
tailY[0]=y; | |
} | |
if(x == fruitX && y == fruitY) { | |
tailX[nTail]=tmpX; | |
tailY[nTail]=tmpY; | |
nTail++; | |
score += 10; | |
fruitX = rand() % width; | |
fruitY = rand() % height; | |
} | |
} | |
int main(int argc, char** argv) | |
{ | |
Setup(); | |
while(!gameOver) { | |
Draw(); | |
Input(); | |
Logic(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment