纯C语言实现经典小游戏——贪吃蛇(VS2017)

假期无聊第二季,用C语言实现简单经典小游戏——贪吃蛇。特别适合新手熟悉C语言。(完整程序在文章最后!!!)
主要涉及C语言知识点如下:
结构体,函数的定义及调用,指针变量,指针和数组,逻辑表达式,基本的选择和循环语句,头文件的编写等
可以说是麻雀虽小,五脏俱全,是新手练习C语言的绝佳小项目!
游戏界面如下:
这里写图片描述

基本思路:
蛇每吃一个食物蛇身子就增加一格,用WASD控制蛇头的运动,而蛇身子跟着蛇头走,每后一格蛇身子下一步走到上一格蛇身子的位置,以此类推。

程序主要变量如下:

#define M 20//整个图形界面的长和宽
#define N 60
    struct snake a[(M - 2)*(N - 2)];//蛇身数组
    int snake_x =4;//蛇身的XY坐标
    int snake_y =4;
    int X = 1;//控制蛇头的方向量
    int Y = 0;
    int food_x , food_y ;//食物的XY坐标
    int score = 0;//分数

食物的随机位置产生是通过两个随机数分别代表X,Y坐标实现的。

void food(int *x, int *y,int *fx,int *fy,int *s, struct snake *snake)
{
    int ffx, ffy;//上一次食物的XY坐标
    ffx = *fx;
    ffy = *fy;

    if (*x == *fx && *y == *fy)//如果吃到了食物,产生下一个食物
    { 
        do {
            *fx = 1 + rand() % (N - 3);
            *fy = 1 + rand() % (M - 3);
        } while (ffx == *fx && ffy == *fy);//保证与上次食物位置不同

        for (int i= (*s); i >= 0; i--)
        {
            if ((snake + *s)->snake_x == *fx && (snake + *s)->snake_y == *fy) {
                *fx = 1 + rand() % (N - 3);
                *fy = 1 + rand() % (M - 3);
            }
        }//大概率保证食物与蛇身子的位置不同(不能完全保证)
        (*s)++ ;                          //分数加一!!!!!!!
    }
}

用WASD控制蛇头的运动是通过改变蛇头的X,Y坐标实现的。

void control(int *x,int *y,int *X,int *Y)//xy是蛇头的坐标,XY是控制运动方向的量
{
    if (_kbhit())
    {
        switch (_getch())
        {
        case 'w' :
        case 'W' :
            if(interf[*y - 1][*x]!='@'){   //if语句保证蛇不能倒着走
                *X = 0; *Y = -1;
            }
            break;
        case 'd':
        case 'D':
            if(interf[*y][*x + 1] != '@'){
                *X = 1; *Y = 0;
            }
                break;
        case 's':
        case 'S':
            if (interf[*y + 1][*x] != '@') {
                *X = 0; *Y = 1;
            }
                break;
        case 'a':
        case 'A':
            if (interf[*y][*x - 1] != '@') {
                *X = -1; *Y = 0;
            }
                break;
        default:
            break;
        } 
    }
    *x = *x + *X;//改变一次位置
    *y = *y + *Y;
}

用定义蛇身子的结构体储存身子的XY坐标,然后定义蛇身子结构体数组存储每一节蛇身子。

struct snake
{
    int number;
    int snake_x;
    int snake_y;
    //struct snake *next;
};

struct snake a[(M - 2)*(N - 2)];


void build_snake(struct snake *snake,int s,int *sx,int *sy)//sx,sy蛇头的位置
{
    for (int i = s; i >= 0; i--)
    {
        if (i == 0) {
            (snake + i)->number = i;
            (snake + i)->snake_x = *sx;
            (snake + i)->snake_y = *sy;
        }else{
            (snake + i)->number = i;
            (snake + i)->snake_x = (snake + i - 1)->snake_x;
            (snake + i)->snake_y = (snake + i - 1)->snake_y;
        }
    }
}

有了蛇身子和食物的坐标位置,将它们一起存储在一个表示整个界面的二位数组,然后循环打印整个数组形成动画效果!

char interf[M][N];

void newinterface(struct snake *snake,  int fx, int fy,int s)
{
    int x, y;
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            if (i == 0 || i == M - 1)
                interf[i][j] = '-';
                //printf("-");
            else if (j == 0)
                interf[i][j] = '|';
                //printf("|");
            else if (j == N - 1)
                interf[i][j] = '|';
                //printf("|\n");
            else if (i == fy && j == fx)
                interf[i][j] = '$';
                //printf("$");
            else  
                interf[i][j] = ' ';
                //printf(" ");
        }
    }
    for (; s >= 0; s--)
    {
            x = (snake + s)->snake_x;
            y = (snake + s)->snake_y;
            interf[y][x] = '@';
    }   
}

完整程序代码!!!

文件 snakemain.cpp

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include "interface.h"
#include "snake.h"

int main(void)
{
    struct snake a[(M - 2)*(N - 2)];
    int snake_x =4;
    int snake_y =4;
    int X = 1;
    int Y = 0;
    int food_x , food_y ;
    int score = 0;

    do {
        food_x = 1 + rand() % (N - 3);
        food_y = 1 + rand() % (M - 3);
    } while (food_x == 4 && food_y == 4);

    for (;;)
    {
        system("cls");
        printf("\n                       贪吃蛇小游戏");
        printf("\n作者:xhyang 博客地址:http://blog.csdn.net/weixin_39449570\n");
        printf("按W控制向上运动,按D控制向右运动,按S控制向下运动,按A控制向左运动。\n");
        printf("得分:%d",score);
        printf("\n");

        control(&snake_x, &snake_y,&X,&Y);
        build_snake(a, score, &snake_x, &snake_y);
        death(snake_x, snake_y,score);
        newinterface(a, food_x, food_y, score);
        food(&snake_x, &snake_y, &food_x, &food_y,&score,a);
        draw();
        Sleep(140);
    }
    system("pause");
    return 0;
}
文件 snake.h

#ifndef SNAKE_H
#define SNAKE_H

struct snake
{
    int number;
    int snake_x;
    int snake_y;
    //struct snake *next;
};

void build_snake(struct snake *snake, int s, int *sx, int *sy);

#endif
文件 snake.cpp

#include <stdio.h>
#include <stdlib.h>
#include "snake.h"

void build_snake(struct snake *snake,int s,int *sx,int *sy)
{
    for (int i = s; i >= 0; i--)
    {
        if (i == 0) {
            (snake + i)->number = i;
            (snake + i)->snake_x = *sx;
            (snake + i)->snake_y = *sy;
        }else{
            (snake + i)->number = i;
            (snake + i)->snake_x = (snake + i - 1)->snake_x;
            (snake + i)->snake_y = (snake + i - 1)->snake_y;
        }
    }
}
文件 interface.h

#ifndef INTERFACE_H
#define INTERFACE_H

#define M 20
#define N 60

void control(int *x, int *y, int *X, int *Y);
void snake(int x, int y);
void newinterface(struct snake *snake, int fx, int fy, int s);
void food(int *x, int *y, int *fx, int *fy, int *s, struct snake *snake);
void draw(void);
void death(int x, int y, int s);

#endif
文件 interface.cpp
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include "interface.h"
#include "snake.h"

char interf[M][N];

void newinterface(struct snake *snake,  int fx, int fy,int s)
{
    int x, y;
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            if (i == 0 || i == M - 1)
                interf[i][j] = '-';
                //printf("-");
            else if (j == 0)
                interf[i][j] = '|';
                //printf("|");
            else if (j == N - 1)
                interf[i][j] = '|';
                //printf("|\n");
            else if (i == fy && j == fx)
                interf[i][j] = '$';
                //printf("$");
            else  
                interf[i][j] = ' ';
                //printf(" ");
        }
    }
    for (; s >= 0; s--)
    {
            x = (snake + s)->snake_x;
            y = (snake + s)->snake_y;
            interf[y][x] = '@';
    }   
}

void food(int *x, int *y,int *fx,int *fy,int *s, struct snake *snake)
{
    int ffx, ffy;//上一次食物的XY坐标
    ffx = *fx;
    ffy = *fy;

    if (*x == *fx && *y == *fy)//如果吃到了食物,产生下一个食物
    { 
        do {
            *fx = 1 + rand() % (N - 3);
            *fy = 1 + rand() % (M - 3);
        } while (ffx == *fx && ffy == *fy);//保证与上次食物位置不同

        for (int i= (*s); i >= 0; i--)
        {
            if ((snake + *s)->snake_x == *fx && (snake + *s)->snake_y == *fy) {
                *fx = 1 + rand() % (N - 3);
                *fy = 1 + rand() % (M - 3);
            }
        }//大概率保证食物与蛇身子的位置不同(不能完全保证)
        (*s)++ ;                          //分数加一!!!!!!!
    }
}


void control(int *x,int *y,int *X,int *Y)//xy是蛇头的坐标,XY是控制运动方向的量
{
    if (_kbhit())
    {
        switch (_getch())
        {
        case 'w' :
        case 'W' :
            if(interf[*y - 1][*x]!='@'){   //if语句保证蛇不能倒着走
                *X = 0; *Y = -1;
            }
            break;
        case 'd':
        case 'D':
            if(interf[*y][*x + 1] != '@'){
                *X = 1; *Y = 0;
            }
                break;
        case 's':
        case 'S':
            if (interf[*y + 1][*x] != '@') {
                *X = 0; *Y = 1;
            }
                break;
        case 'a':
        case 'A':
            if (interf[*y][*x - 1] != '@') {
                *X = -1; *Y = 0;
            }
                break;
        default:
            break;
        } 
    }
    *x = *x + *X;//改变一次位置
    *y = *y + *Y;
}


void draw(void)
{
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            printf("%c", interf[i][j]);
        }
        printf("\n");
    }
}


void death(int x,int y,int s)
{
    if (x == 0 || x == N-1 || y  == 0 || y == M-1 || interf[y][x] == '@') {
        for (;;)
        {
            system("cls");
            printf("\n              游戏结束!\n");
            printf("              最终得分:%d \n", s);
            Sleep(140);
        //system("pause");
        }

    }
}
  • 104
    点赞
  • 500
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
以下是一个简单的C语言贪吃蛇游戏程序,使用了windows.h库和conio.h库: ``` #include <stdio.h> #include <windows.h> #include <conio.h> #define MAP_WIDTH 40 #define MAP_HEIGHT 20 int map[MAP_HEIGHT][MAP_WIDTH] = { 0 }; int snake[100][2] = { 0 }; int length = 3; int direction = 3; int score = 0; void gotoxy(int x, int y) { COORD pos; pos.X = x; pos.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos); } void initMap() { int i, j; for (i = 0; i < MAP_HEIGHT; i++) { for (j = 0; j < MAP_WIDTH; j++) { if (i == 0 || i == MAP_HEIGHT - 1 || j == 0 || j == MAP_WIDTH - 1) { map[i][j] = 1; } } } } void showMap() { int i, j; for (i = 0; i < MAP_HEIGHT; i++) { for (j = 0; j < MAP_WIDTH; j++) { gotoxy(j, i); if (map[i][j] == 0) { printf(" "); } else if (map[i][j] == 1) { printf("#"); } else if (map[i][j] == 2) { printf("@"); } else if (map[i][j] == 3) { printf("*"); } } } } void initSnake() { int i; for (i = 0; i < length; i++) { snake[i][0] = MAP_WIDTH / 2 + i; snake[i][1] = MAP_HEIGHT / 2; map[snake[i][1]][snake[i][0]] = 3; } } void showSnake() { int i; for (i = 0; i < length; i++) { gotoxy(snake[i][0], snake[i][1]); printf("*"); } } void createFood() { int x, y; do { x = rand() % (MAP_WIDTH - 2) + 1; y = rand() % (MAP_HEIGHT - 2) + 1; } while (map[y][x] != 0); map[y][x] = 2; } void updateSnake() { int i, tail_x, tail_y; tail_x = snake[length - 1][0]; tail_y = snake[length - 1][1]; for (i = length - 1; i > 0; i--) { snake[i][0] = snake[i - 1][0]; snake[i][1] = snake[i - 1][1]; } if (direction == 0) { snake[0][1]--; } else if (direction == 1) { snake[0][0]++; } else if (direction == 2) { snake[0][1]++; } else if (direction == 3) { snake[0][0]--; } if (map[snake[0][1]][snake[0][0]] == 1 || map[snake[0][1]][snake[0][0]] == 3) { gotoxy(MAP_WIDTH / 2 - 4, MAP_HEIGHT / 2); printf("Game Over!"); getch(); exit(0); } if (map[snake[0][1]][snake[0][0]] == 2) { length++; score += 10; createFood(); } map[tail_y][tail_x] = 0; map[snake[0][1]][snake[0][0]] = 3; } void showScore() { gotoxy(MAP_WIDTH + 5, 5); printf("Score: %d", score); } int main() { initMap(); initSnake(); createFood(); while (1) { showMap(); showSnake(); showScore(); Sleep(100); updateSnake(); if (_kbhit()) { int ch = _getch(); if (ch == 'w' && direction != 2) { direction = 0; } else if (ch == 'd' && direction != 3) { direction = 1; } else if (ch == 's' && direction != 0) { direction = 2; } else if (ch == 'a' && direction != 1) { direction = 3; } } } return 0; } ``` 该程序使用二维数组表示地图,使用二维数组表示蛇,通过调用控制台API函数来实现显示,并使用conio.h库来实现键盘输入。程序运行后,使用wasd来控制蛇的移动,吃到食物后蛇的长度会增加,分数也会增加。当蛇撞到墙或自己时,游戏结束。
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值