簡體   English   中英

C蛇游戲

[英]Snake game in c

我有一個蛇游戲項目,但是現在我需要找到一種方法來使尾巴跟隨頭部,並且我已經先使頭部成為頭部,但是我仍然對如何使尾巴跟隨頭部感到困惑,我知道我必須使尾巴跟隨頭部的先前坐標,但是我找不到辦法

這是我的代碼

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

int side;
char map[20][20];
int z=5,c=5; //the starting position of the head
int p=0;
void snake(char map[20][20],int ,int )
{
    if(p==0)
    {
        p++;
    for(int x=0;x<side;x++)
        {
            map[z][c]='X';

           printf("%s\n",map[x]);
        }
    }
    int hc,hb,t,r,j,u,i;
    hc=getch();
    hb=getch();
    if(hb==72)//up
    {
        z--;

    }
    else if(hb==77)//right
    {
        c++;

    }
    else if(hb==80)//down
    {   
        z++;
    }
    else if(hb==75)//left
    {
        c--;

    }
    map[z][c]='X';


    system("CLS");  
}

void square(){
        int x,y;

        for(x=0;x<side;x++){
                for(y=0;y<side;y++){

                        if(x==0||x==side-1||y==0||y==side-1){
                                map[x][y]='X';
                        }

                        else{
                                map[x][y]=' ';
                        }
                }
        }
        snake(map,x,y);
} 

void print(){
        for(int x=0;x<side;x++){
                printf("%s\n",map[x]);
        }
}

int main()
{

    printf("Input the large = ");
    scanf("%d",&side); 
    fflush(stdin);
    system("CLS");
    while(true)
    {
    square();
    print();
    }
    getchar();

}

在大多數此類游戲中,您實際上不必使尾巴跟隨頭部-您只需在前面添加新的X即可將頭部延長一步,而刪除尾部的最后一個X即可將其縮短一步。 這將問題簡化為只需要知道過去的坐標是什么,無論如何您都需要該坐標才能防止蛇穿過自己。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM