#include<bits/stdc++.h>
#include<windows.h>
#include<conio.h>
using namespace std;
const int WIDTH=80;
const int HEIGHT=20;
struct Snake
{
int x;
int y;
struct Snake *next;
};
struct Food
{
int x;
int y;
};
void drawScene(Snake *head,Food food)
{
system("cls");
for(int i=0;i<HEIGHT;i++)
{
for(int j=0;j<WIDTH;j++)
{
if(i==0||i==HEIGHT-1||j==0||j==WIDTH-1)
{
cout<<"#";
}
else
{
bool isSnake=false;
Snake *temp=head;
while(temp!=nullptr)
{
if(temp->x==j&&temp->y==i)
{
isSnake=true;
break;
}
temp=temp->next;
}
if(isSnake)
{
cout<<"O";
}
else if(j==food.x&&i==food.y)
{
cout<<"F";
}
else
{
cout<<" ";
}
}
}
cout<<endl;
}
}
void moveSnake(Snake *&head,int dx,int dy){
Snake *newHead=new Snake;
newHead->x=head->x+dx;
newHead->y=head->y+dy;
newHead->next=head;
head=newHead;
}
bool checkFood(Snake *head,Food food)
{
if(head->x==food.x&&head->y==food.y) return true;
else return false;
}
void freeSnake(Snake *head)
{
Snake *temp;
while(head!=nullptr)
{
temp=head;
head=head->next;
delete temp;
}
}
int main()
{
Snake *head=new Snake;
head->x=WIDTH/2;
head->y=HEIGHT/2;
head->next=nullptr;
Food food;
food.x=rand()%(WIDTH-4)+1;
food.y=rand()%(HEIGHT-4)+1;
int dx=1;
int dy=0;
bool gameOver=false;
while(!gameOver)
{
drawScene(head,food);
if(GetAsyncKeyState(VK_UP)&&dy!=1)
{
dx=0;
dy=-1;
}
else if(GetAsyncKeyState(VK_DOWN)&&dy!=-1)
{
dx=0;
dy=1;
}
else if(GetAsyncKeyState(VK_LEFT)&&dx!=1)
{
dx=-1;
dy=0;
}
else if(GetAsyncKeyState(VK_RIGHT)&&dx!=-1)
{
dx=1;
dy=0;
}
moveSnake(head,dx,dy);
if(checkFood(head,food))
{
food.x=rand()%(WIDTH-2)+1;
food.y=rand()%(HEIGHT-2)+1;
}
else
{
Snake *tail=head;
while(tail->next->next!=nullptr)
{
tail=tail->next;
}
Snake *temp=tail->next;
tail->next=nullptr;
delete temp;
}
if(head->x<=0||head->x>=WIDTH-1||head->y<=0||head->y>=HEIGHT-1)
{
gameOver=true;
}
}
freeSnake(head);
cout<<"游戏结束!";
return 0;
}剪贴板
剪贴板 gyqw8v10
剪贴板信息
剪贴板信息
- 收录
- 更新