当前位置:文档之家› 小游戏源代码

小游戏源代码

//贪吃蛇源代码
//yyy
#include "snake.h"
#include

//定义宽和高
#define WIDTH 20
#define HEIGHT 20

//地图
char map[WIDTH][HEIGHT];

//---------------

//蛇身
struct Snake
{
int x;
int y;
Snake* pnext;
};

//蛇头蛇尾
Snake *phead, *ptail;
int count;

//-------------------
void create_map()
{
for (int i=0; i{
for (int j=0; j{
if (i==0 || i==WIDTH-1 || j==0 || j==HEIGHT-1)
{
map[i][j] = 1;
}else
{
map[i][j] = 0;
}
}
}
}

//create
void show_map()
{
for (int i=0; i{
for (int j=0; j{
if (map[i][j] == 1)
{
std::cout << "*";
}else if (map[i][j] == 0)
{
std::cout<< " ";
}else if (map[i][j] == 2)
{
std::cout<< "@";
}
}
std::cout<< "\n";
}
}

void create_snake()
{
count = 0;
phead = new Snake;
++count;
ptail = new Snake;
++count;
phead->x = 10;
phead->y = 10;
phead->pnext = ptail;
ptail->x = 10;
ptail->y = 9;
ptail->pnext = NULL;
map[phead->x][phead->y]=1;
map[ptail->x][ptail->y]=1;
}

void create_food()
{
int i = rand()%19+1;
int j = rand()%19+1;
if (map[i][j] != 0)
{
create_food();
}else{
map[i][j] = 2;
}
}

void move_snake()
{
Snake* temp = phead;
Snake oldtail = *ptail;
char ch = 0;
int col,row,temp_col,temp_row;
int num = count;
col = temp->x;
row = temp->y;
std::cin>>ch;
map[phead->x][phead->y] = 0;
if (ch == 'w' || ch == 'W')
{
--phead->x;
}
else if(ch == 'a' || ch == 'A')
{
--phead->y;
}
else if(ch == 's' || ch == 'S')
{
++phead->x;
}
else if(ch == 'd' || ch == 'D')
{
++phead->y;
}
if (map[phead->x][phead->y] == 2)
{
}
map[phead->x][phead->y] = 1;
while (num-1)
{
temp_col = temp->pnext->x;
temp_row = temp->pnext->y;
temp->pnext->x = col;
temp->pnext->y = row;
map[col][row] = 1;
col = temp_col;
row = temp_row;
temp = temp->pnext;
--num;
}
map[oldtail.x][oldtail.y] = 0;
temp = NULL;
}
/*phead (9,10)*/
int main()
{
srand((unsigned)time( NULL ));
create_map();
create_snake();
create_food();
show_map();
while (1)
{
move_snake();
system("cls");
show_map();
}
return 0;
}

相关主题
文本预览
相关文档 最新文档