#include <iostream>
#include <windows.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h> //使用當前時間做種子
enum dir {up,down,left,right}; //列舉型別enum dir //圍牆
class Fence
{
public:
void initFence();
void OutputF();
public:
char game[20][20];
} f; //定義物件 //畫框框
void Fence::lnitFence()
{
for (int i=0; i<20; i++)
for (int j=0; j<20; j++)
{
if (i==0||i==19||j==0||j==19)
game[i][j]='*';
else
game[i][j]=' ';
}
} //顯示框框
void Fence::OutputF()
{
for (int i=0; i<20; i++)
{
for (int j=0; j<20; j++)
cout<<game[i][j]<<'';
cout<<endl;
}
} //蛇結點
class SnakeNode
{
private:
int x,y;
SnakeNode *prior,*next;
public:
void add_head(int x,int y)
int get_x();
int get_y();
void delete_tail();
}
*head=NULL,*tail=NULL; //插入頭結點
void SnakeNode::add_head(int x,int y)
{
SnakeNode *q=new SnakeNode;
q->x=x;
q->y=y;
q->next=head;
q->prior=NULL;
if (head)
head->prior=q;
head=q;
if (!tail)
tail=head;
f.game[x][y]='*'; //f物件能夠在定義Fence類時定義。且Fnce類在SnakeNode類前定義
}
int SnkeNode::get_x()
{
return x;
}
int SnakeNode::get_y()
{
return y;
} //刪除尾結點
void SnakeNode::delete_tail()
{
SnakeNode *p=tail;
f.game[tail->get_x()][tail->get_y()]=' '; //把尾結點的座標表示的'*'置為空格;
if (tail==head)
tail=head=NULL;
else
{
tail=tail->prior;
tail=next=NULL;
}
delete p;
}
class move
{
public:
dir point; //列舉變數point:控制方向
int food_x;
int food_y;
public:
void moving();
void change_point(char); //改變方向;
void get_food();
};
void move::moving()
{
int a,b;
a=head->get_x(); //取得頭結點橫座標
b=head->get_y(); //取得頭結點縱座標
switch (point)
{
case up:
--a;
break;
case down:
++a;
break;
case left:
--b;
break;
case right:
++b;
break;
}
if (a==19||b==19||a==0||b==0||game[a][b]='*') //推斷是否撞牆
{
cout<<"gameover!!!"<<endl;
exit(0);
}
if (a==food_x&&b==food_y) //吃food
{
head->add_head(a,b);
get_food;
}
else
{
head->add_head(a,b); //插入頭結點
head->delete_tail(); //刪除尾結點
}
void move::change_point(char keydown)
{
switch (keydown)
{
case 'w':
point=up;
break;
case 's':
point=down;
break;
case 'a':
point=left;
break;
case 'd':
point=right;
break;
}
}
void move::get_food()
{
srand((unsigned int) time(NULL)); //做種子(程式執行時間)
food_x=rand()%18+1;
food-y=rand()%18+1;
f.game[food_x][food_y]='*';
}
}
int main()
{
cout<<"Using 'w,a,s,d'to control direction!!!\n\n\n"; //畫框框和小蛇;
move m;
f.lnitFence();
head->add_head(4,3);
head->add_head(4,4);
head->add_head(4,5);
m.get_food();
f.OutputF();
while (ture)
{
char keydown =getch(); //getch()返回
m.chan
ge_point(keydown);
while (!kbhit()) //推斷有沒有按鍵落下
{
system("cls"); //清屏函式;
m.moving();
f.OutputF();
sleep(200);
}
}
return 0;
}
錯誤顯示:
這是我在網上看到的。照著原圖花了半個多小時敲出來的程式碼,可問題還是一大堆。網上的東西果然不可信啊 這裡面好像大部分都是C語言,求有空的大神幫我改動成C++,找出錯誤並改正,謝謝啦;新手上路,請多多關照。。。