贪吃蛇代码~~自编~~~

这个是贪吃蛇的代码,没设置加速系统~~自己可以根据自己的需求加功能

#include<stdio.h>
#include<windows.h>
#include<time.h>
#include<stdlib.h>
#include<iostream>
#define MAX_SIZE 50
using namespace std;
void Loc(int x,int y);
void Welcome();    /*欢迎界面*/
void CreatMaps();  /*创建地图*/
void GameStart();  /*开始游戏的初始化*/
void Move_Snack(); /*蛇每次的移动*/
void Show_Snack(); /*将蛇打印出来*/
int life = 1;      /*命数为1*/
int Deny = 250;    /*一开始时间是X秒*/
int score= 0;      /*得分*/
int food=0;    /*食物个数*/
int food_x,food_y; /*食物的坐标*/
void Have_NoFood();/*无食物的移动*/
void Have_Food();  /*有食物的移动*/
void Make_Food();  /*投掷食物*/
void JudgeDeath();
struct UseMessage  /*用户信息结构体*/
{
    char ID[MAX_SIZE];
    char name[MAX_SIZE];
}User;
struct Body
{
    int x,y;
    struct Body *next;
};
struct Body* head;/*蛇头指针*/
char Dict='R';/*开始指向右边*/
int X,Y;
/*=================主函数============================*/
int main()
{
    system("title 贪吃蛇游戏-Make by:韩书楷");
    Welcome();
    CreatMaps();
    GameStart();
}
/*=================副函数============================*/
void Loc(int x,int y)
{
    COORD pos={x,y};
    HANDLE hout;
    hout=GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleCursorPosition(hout,pos);
}
/*利用Windows函数进行光标的定位*/
void Welcome()
{
    Loc(12,3);
    cout<<"非常感谢您对本人的支持,请输入你的ID和姓名进行游戏";
    Loc(25,7);
    cout<<"请输入ID:"; cin>>User.ID;
    Loc(25,10);
    cout<<"请输入姓名:";cin>>User.name;
    Sleep(500);
    Loc(25,14);
    cout<<"下面就开始您的贪吃蛇之旅吧!^_^";
    Sleep(1500);
    system("cls");
}
void CreatMaps()
{
    Loc(10,3);
    cout<<"Player:       "<<User.name<<"    的      贪       吃       蛇";
    int x=0,y=6;
    for(int i=0;i<=20;i++)
    {
        Loc(x+0,y+i);
        printf("□");
        Loc(x+60,y+i);
        printf("□");
    }
    for(int i=0;i<=60;i+=2)
    {
        Loc(x+i,y+0);
        printf("□");
        Loc(x+i,y+20);
        printf("□");
    }
}
void GameStart()
{
    struct Body *body1,*body2,*body3;
    head =(struct Body*)malloc(sizeof(struct Body));
    body1=(struct Body*)malloc(sizeof(struct Body));
    body2=(struct Body*)malloc(sizeof(struct Body));
    body3=(struct Body*)malloc(sizeof(struct Body));
     head ->next=body1;body1->next=body2;
     body2->next=body3;body3->next=NULL;
     head ->x=18;head ->y=10;
     body1->x=16;body1->y=10;
     body2->x=14;body2->y=10;
     body3->x=12;body3->y=10;
     Show_Snack();
    while(true) /*移动一次加一次时间*/
    {
        Loc(64,8); cout<<"Your Name:"<<User.name;
        Loc(64,10);cout<<"Your ID:"<<User.ID;
        Loc(64,12);cout<<"Your score:"<<score;
        Loc(64,14);cout<<"Control:"<<endl;
        Loc(64,16);cout<<"←↑↓→"<<endl;
        if(GetAsyncKeyState(VK_UP)&&Dict!='D')
            Dict='U';
        if(GetAsyncKeyState(VK_DOWN)&&Dict!='U')
            Dict='D';
        if(GetAsyncKeyState(VK_LEFT)&&Dict!='R')
            Dict='L';
        if(GetAsyncKeyState(VK_RIGHT)&&Dict!='L')
            Dict='R';
        Move_Snack();
        Show_Snack();
        Loc(0,0);
        JudgeDeath();
        if(food==0)/*如果没有食物了*/
        Make_Food();
        if(life==0)
        {
            system("cls");
            Loc(25,10);
            cout<<"Game Over~~~"<<"You Score is "<<score<<endl;
            Sleep(1000*3);
            break;
        }
        Sleep(Deny);
    }
}
void Make_Food()
{
    srand((unsigned int)time(NULL));
    food_x=rand()%58 + 1;
    food_y=rand()%18 + 7;
    if(food_x&1)/*如果是奇数的话成偶数坐标*/
    food_x+=1;
    Loc(food_x,food_y); printf("●");
    food=1;
}
void Move_Snack()
{
         if(Dict=='U') {X= 0; Y=-1;}
    else if(Dict=='D') {X= 0; Y= 1;}
    else if(Dict=='L') {X=-2; Y= 0;}
    else if(Dict=='R') {X= 2; Y= 0;}
    /*判断下一步的移动有没有食物*/
    int p,q;/*下一步的坐标*/
    p=(head->x)+X; q=(head->y)+Y;
    if(p==food_x&&q==food_y)
    {
        food=0;
        Have_Food();/*做一个有食物的移动*/
    }
    else
        Have_NoFood();/*否则就做一个正常的移动*/
}
void Have_Food()
{
    struct Body * body_m;/*定义一个临时的指针*/
    body_m=(struct Body*)malloc(sizeof(struct Body));
    body_m->x=(head->x)+X;
    body_m->y=(head->y)+Y;
    body_m->next=head;
    head=body_m;
    score+=10;
}
void Have_NoFood()
{
    struct Body * body_m;/*定义一个临时的指针*/
    struct Body * body_n;
    //body_n=(struct Body*)malloc(sizeof(struct Body));
    body_m=(struct Body*)malloc(sizeof(struct Body));
    body_m->x=(head->x)+X;
    body_m->y=(head->y)+Y;
    /*新蛇头的位置*/
    body_m->next=head;
    head=body_m;
    body_n=head;
    while((body_n->next)->next!=NULL)
    {
        body_n=body_n->next;
    }
    Loc((body_n->next)->x,(body_n->next)->y);
    printf("  ");
    free(body_n->next);
    body_n->next=NULL;
}
void Show_Snack()
{
    struct Body *body_m=(struct Body*)malloc(sizeof(struct Body));
    body_m=head;
    while(body_m!=NULL)
    {
        int m=body_m->x;
        int n=body_m->y;
        Loc(m,n);
        printf("□");
        Loc(0,0);
        body_m=body_m->next;
    }
}
void  JudgeDeath()
{
    struct Body *body_x=head;
    if((head->x)<=0||(head->x)>=60||(head->y)<=6||(head->y)>=26) /*如果越界*/
    {
        life=0;
        return ;
    }
    while(body_x->next!=NULL)
    {
        body_x=body_x->next;
        if(body_x->x==head->x&&body_x->y==head->y)
        {
            life = 0;
            break;
        }
    }
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的贪吃蛇代码实现,使用 Python 语言: ```python import pygame import random # 定义常量 WIDTH = 640 HEIGHT = 480 CELL_SIZE = 20 SPEED = 10 # 颜色 BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) # 初始化 Pygame pygame.init() # 设置窗口 window = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('贪吃蛇') # 定义蛇类 class Snake: def __init__(self): self.body = [(4, 3), (3, 3), (2, 3)] self.direction = 'right' def move(self): head = self.body[0] if self.direction == 'up': new_head = (head[0], head[1] - 1) elif self.direction == 'down': new_head = (head[0], head[1] + 1) elif self.direction == 'left': new_head = (head[0] - 1, head[1]) elif self.direction == 'right': new_head = (head[0] + 1, head[1]) self.body.insert(0, new_head) self.body.pop() def grow(self): tail = self.body[-1] self.body.append(tail) def is_collide(self): head = self.body[0] if head[0] < 0 or head[0] >= WIDTH / CELL_SIZE: return True if head[1] < 0 or head[1] >= HEIGHT / CELL_SIZE: return True for i in range(1, len(self.body)): if head == self.body[i]: return True return False def draw(self): for cell in self.body: rect = pygame.Rect(cell[0]*CELL_SIZE, cell[1]*CELL_SIZE, CELL_SIZE, CELL_SIZE) pygame.draw.rect(window, GREEN, rect) # 定义食物类 class Food: def __init__(self): self.position = (random.randint(0, WIDTH/CELL_SIZE-1), random.randint(0, HEIGHT/CELL_SIZE-1)) def draw(self): rect = pygame.Rect(self.position[0]*CELL_SIZE, self.position[1]*CELL_SIZE, CELL_SIZE, CELL_SIZE) pygame.draw.rect(window, RED, rect) # 创建蛇和食物 snake = Snake() food = Food() # 游戏循环 clock = pygame.time.Clock() running = True while running: # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and snake.direction != 'down': snake.direction = 'up' elif event.key == pygame.K_DOWN and snake.direction != 'up': snake.direction = 'down' elif event.key == pygame.K_LEFT and snake.direction != 'right': snake.direction = 'left' elif event.key == pygame.K_RIGHT and snake.direction != 'left': snake.direction = 'right' # 移动蛇和检测碰撞 snake.move() if snake.is_collide(): running = False # 检测是否吃到食物 if snake.body[0] == food.position: snake.grow() food = Food() # 绘制场景 window.fill(BLACK) snake.draw() food.draw() pygame.display.update() # 控制帧率 clock.tick(SPEED) # 退出 Pygame pygame.quit() exit() ``` 注意,这只是一个简单的实现,还有很多细节可以完善,比如增加蛇的长度、速度随着时间增加、死亡动画等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值