帮我写一个贪吃蛇的程序
#include <iostream>
#include <vector>
using namespace std;
//定义结构体,表示贪吃蛇的每个部分的坐标
struct SnakeNode{
int x; //x坐标
int y; //y坐标
};
//定义一个vector,用来存储贪吃蛇的每一部分的坐标
vector<SnakeNode> snake;
//定义食物的位置,默认在(0,0)处
SnakeNode food = {0, 0};
//定义一个函数,用来生成新的食物位置
void GenerateFood(){
food.x = rand()%10;
food.y = rand()%10;
}
//定义一个函数,用来检测是否吃到了食物
bool CheckFood(){
if(snake[0].x == food.x && snake[0].y == food.y){
return true; } else { return false; } }
// 定义一个函数,用来检测是否发生了“死亡” bool CheckDeath(){ for(int i=1 ; i<snake.size() ; i++){ if(snake[i].x == snake[0].x && snake[i].y == snake[0].y){ return true; } } return false; } int main(){ while(true){ GenerateFood(); while(!CheckFood() && !CheckDeath()){ cout<<"请选择方向: w/s/a/d"<<endl; char dir ; cin>>dir ; switch (dir) { case 'w': snake[0].x-- ; break ; case 's': snake[0].x++ ; break ; case 'a': snake[0].y--
创作工场
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。
点击这里>>使用🔥专业版,更聪明、更完整、更原创!