您的位置:首页 > 移动开发 > 微信开发

带有N多BUG的小程序——贪吃蛇

2015-11-25 20:18 791 查看
只考虑贪吃蛇的头和尾对象,对头尾做不同的动作分析。

//bug::1食物可能出现在蛇身上
//2不能穿墙或者遇到墙失败之类的、。
//3蛇身体相交时候,就乱了。

#include<iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int map[10][10] = { 0 };
int flag = 0;//为1 时候需要重新生成食物

class Point_head
{
int x;
int y;
public:
Point_head(int tx, int ty) :x(tx), y(ty){}
void run_right()
{
y += 1;
}
void run_left()
{
y -= 1;
}
void run_up()
{
x -= 1;
}
void run_down()
{
x += 1;
}
void put()
{
map[x][y] = 1;//1为蛇
}
bool judge()//判断是否碰到食物
{
if (map[x][y] == 2)
{
flag = 1;
return true;

}
else
return false;
}
};
class Point_tail
{
int x;
int y;
public:
Point_tail(int tx, int ty) :x(tx), y(ty){}
void move()//移动尾部对象
{
if (map[x][y-1] == 1)
y -= 1;
else if (map[x][y+1] == 1)
y += 1;
else if (map[x-1][y] == 1)
x -= 1;
else if (map[x+1][y] == 1)
x += 1;

}

void put()//尾部对象赋值
{
map[x][y] = 0;//1为蛇

}
};
//void init()
//{
//  map[5][5] = map[5][6] =map[5][7]= 1;
//  Point_head P1(5, 5);
//  Point_tail P2(5, 7);
//}
void print()
{
for (int i = 0; i != 10; i++)
{
for (int j = 0; j != 10; j++)
{
cout << map[i][j] << " ";
}
cout << endl;
}
}
int random()//生成0——9的随机数
{
srand((unsigned)time(NULL));
int num = rand() % 10;
while (num == 5||num==6||num==7)
num = rand() % 10;
return num;
}
int main()
{
cout << "贪吃蛇小游戏,0为空地,1为蛇,2为食物" << endl
<< "w向上,a向左,s向下,d向右" << endl;
map[5][5] = map[5][6] = map[5][7] = 1;
Point_head P1(5, 5);
Point_tail P2(5, 7);
map[random()][random()] = 2;//2为食物
print();
char dir;
while (cin >> dir)
{
switch (dir)
{
case 'a':P1.run_left();
if (P1.judge()){
P1.put();
}
else
{
P1.put(); P2.put();  P2.move();
}
break;
case 's':P1.run_down();
if (P1.judge()){
P1.put();
}
else
{
P1.put(); P2.put();  P2.move();
}break;
case 'd':P1.run_right();
if (P1.judge()){
P1.put();
}
else
{
P1.put(); P2.put();  P2.move();
}break;
case 'w':P1.run_up();
if (P1.judge()){
P1.put();
}
else
{
P1.put(); P2.put();  P2.move();
}break;
}

if (flag == 1)
{
map[random()][random()] = 2;//2为食物
flag = 0;
}
print();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: