C语言实现贪吃蛇源码

先放效果

源代码

//2016-2-12
//zhaoyu
//Gmail:[email protected]
//Language: C
//Platform:Code::Blocks
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
#include <time.h>

typedef struct snake
{
    int x;
    int y;
    struct snake *next;
}Snake;
int X, Y;
enum STATUS{Up = 1, Down, Left, Right};

Snake *pHead, *pBody;//the head of the snake

enum STATUS Direction;
int score=0, scorePerFood=10;
int gameStatus = 0;
int timeInterval = 200;
void gameEnd(void);
void setPosition(int x, int y)
{
    COORD pos;
    HANDLE hOutput;
    pos.X = x;
    pos.Y = y;
    hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleCursorPosition(hOutput, pos);
}
void hideCursor()
{
	CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
void creatInterface(void)
{
    int i;
    for(i=0;i<58;i+=2)
    {
        setPosition(i,0);
        printf("¡ö");//a ¡ö occupy two character space
        setPosition(i,26);
        printf("¡ö");
    }
    for(i=1;i<26;i++)
    {
        setPosition(0,i);
        printf("¡ö");
        setPosition(56,i);
        printf("¡ö");
    }
    setPosition(65, 10);
    printf("Introduction");
    setPosition(63,12);
    printf("¡ü\tMove up.");
    setPosition(63,14);
    printf("¡ý\tMove Down.");
    setPosition(63,16);
    printf("¡û\tMove left.");
    setPosition(63,18);
    printf("¡ú\tMove right.");
    setPosition(63,20);
    printf("F1\tSpeed up.");
    setPosition(63, 22);
    printf("F2\tSlow down.");
    setPosition(63, 24);
    printf("Space\tGame pause.");
    setPosition(63,26);
    printf("ESC\tQuit the game.");
    setPosition(63, 4);
    printf("Score:");
    setPosition(63, 6);
    printf("Score Per Food:");
}
void initializeSnake(void)
{
    Snake *pTail;
    int i;
    pTail = (Snake *)malloc(sizeof(Snake));
    pTail->x = 24;
    pTail->y = 5;
    pTail->next = NULL;
    for (i = 1; i < 4; i++)
    {
        pHead = (Snake *)malloc(sizeof(Snake));
        pHead->next = pTail;
        pHead->x = 24 + 2*i;
        pHead->y = 5;
        pTail = pHead;//Important
    }
    while (pTail != NULL)
    {
        setPosition(pTail->x, pTail->y);
        printf("¡ö");
        pTail = pTail->next;
    }
}
int biteSelf(void)
{
    Snake *pSelf = pHead->next;
    while (pSelf != NULL)
    {
        if (pHead->x==pSelf->x && pHead->y==pSelf->y)
        {
            return 1;
        }
        pSelf = pSelf->next;
    }
    return 0;
}
void creatFood(void)
{
    int flag = 0;
    X = Y = 4;
    srand((unsigned)time(NULL));
    do{
        X = rand()%52 + 2;
        Y = rand()%24 + 1;

        if (X%2 != 0)
        {
            flag = 1;
        }
        else
        {
            flag = 0;
        }//Important
        pBody = pHead;
        while (pBody->next != NULL)
        {
            if(pBody->x==X && pBody->y==Y)
            {
                flag = 1;
            }
            pBody = pBody->next;
        }
    }while(flag==1);
    setPosition(X, Y);
    printf("¡ö");
}

void hitWall(void)
{
    if (pHead->x==0 || pHead->x>=56 || pHead->y==0 || pHead->y>=26)
    {
        gameStatus = 1;
        gameEnd();
    }
}
void snakeMove(void)
{
    Snake *pNextHead;
    hitWall();

    pNextHead = (Snake *)malloc(sizeof(Snake));
    pNextHead->next = pHead;
    switch(Direction)
    {
    case Up:
        pNextHead->x = pHead->x;
        pNextHead->y = pHead->y - 1;
        break;
    case Down:
        pNextHead->x = pHead->x;
        pNextHead->y = pHead->y + 1;
        break;
    case Right:
        pNextHead->x = pHead->x + 2;
        pNextHead->y = pHead->y;
        break;
    case Left:
        pNextHead->x = pHead->x - 2;
        pNextHead->y = pHead->y;
        break;
    default:
        break;
    }
    pHead = pNextHead;
    pBody = pHead;
    if (pNextHead->x == X && pNextHead->y == Y)
    {
        while (pBody != NULL)
        {
            setPosition(pBody->x, pBody->y);
            printf("¡ö");
            pBody = pBody->next;
        }
        score += scorePerFood;
        creatFood();
    }
    else
    {
        setPosition(pBody->x, pBody->y);
        printf("¡ö");
        while (pBody->next->next != NULL)
        {
            pBody = pBody->next;
        }
        setPosition(pBody->next->x, pBody->next->y);
        printf("  ");
        free(pBody->next);
        pBody->next = NULL;
    }
    if (biteSelf() == 1)
    {
        gameStatus = 2;
        gameEnd();
    }
}
void pause(void)
{
    while(1)
    {
        Sleep(300);
        if(GetAsyncKeyState(VK_SPACE))
        {
            break;
        }
    }
}
void gameCircle(void)
{
    Direction = Right;
    while (1)
    {
        setPosition(72, 4);
        printf("%d", score);
        setPosition(80, 6);
        printf("%d ", scorePerFood);//Attention space is needed
        if (GetAsyncKeyState(VK_UP) && Direction!=Down)
        {
            Direction = Up;
        }
        else if (GetAsyncKeyState(VK_DOWN) && Direction!=Up)
        {
            Direction = Down;
        }
        else if (GetAsyncKeyState(VK_LEFT) && Direction!=Right)
        {
            Direction = Left;
        }
        else if (GetAsyncKeyState(VK_RIGHT) && Direction!=Left)
        {
            Direction = Right;
        }
        else if (GetAsyncKeyState(VK_SPACE))
        {
            pause();
        }
        else if (GetAsyncKeyState(VK_ESCAPE))
        {
            gameStatus = 3;
            break;
        }
        else if (GetAsyncKeyState(VK_F1))
        {
            if(timeInterval >= 70)
            {
                timeInterval -= 60;
            }
        }
        else if (GetAsyncKeyState(VK_F2))
        {
            if (timeInterval <= 400)
            {
                timeInterval += 60;
            }

        }
        switch (timeInterval)
        {
            case 20: scorePerFood = 20;break;
            case 80: scorePerFood = 15;break;
            case 140: scorePerFood = 12;break;
            case 200: scorePerFood = 10;break;
            case 260: scorePerFood = 8;break;
            case 320: scorePerFood = 6;break;
            case 380: scorePerFood = 4;break;
            case 440: scorePerFood = 2;break;
            default: scorePerFood = 0;break;
        }
        Sleep(timeInterval);
        snakeMove();
    }
}
void welcomePage(void)
{
    setPosition(35,2);
	printf("Welcome to Snake");
	setPosition(15, 5);
	printf("Rules:");
	setPosition(15, 7);
	printf("1.  Use ¡ü.¡ý.¡û.¡ú to control the movement of the Snake.");
	setPosition(15, 9);
	printf("2.  Biting the snake itself is forbidden.");
	setPosition(15, 11);
	printf("3.  Hit the wall is forbidden.");
	setPosition(15, 13);
	printf("Developeder:  zhaoyu.");
    setPosition(15, 15);
    printf("Blog:  http://blog.csdn.net/sinat_30046339");
    setPosition(28, 23);
    printf("Press any key to continue...");
	setPosition(0, 28);
	getchar();
	system("cls");
}
void gameEnd(void)
{
    system("cls");
    setPosition(32, 10);
    switch(gameStatus)
    {
    case 1:
        printf("You hit the wall!");
        break;
    case 2:
        printf("You bit yourself!");
        break;
    case 3:
        printf("You chose to end the game.");
        break;
    default:
        break;
    }
    setPosition(32, 14);
    printf("Your final score is   %d", score);
    getchar();
    setPosition(0, 25);
    exit(0);
}
void gameStart(void)
{
	system("mode con cols=100 lines=30");//no space around equal sign
	welcomePage();
	creatInterface();
	initializeSnake();
	creatFood();
}

//Main Function
int main(void)
{
    hideCursor();
	gameStart();
	gameCircle();
	gameEnd();
	return 0;
}

  

时间: 2024-10-26 15:11:20

C语言实现贪吃蛇源码的相关文章

c# 贪吃蛇源码

using UnityEngine; using System.Collections;using System.Diagnostics;using UnityEngine.SceneManagement;using System.Collections.Generic;using System.Linq;using UnityEngine.UI; public class SnakeMove : MonoBehaviour {    List<Transform> Body = new Li

js贪吃蛇源码

1.注意,自己引入jquery,这个demo基于jquery的,我的jquery是写的本地的 2.没有写注释,看不懂的再问我吧, <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> * { padding: 0; margin: 0; } div.w

python小游戏贪吃蛇源码下载

回车键:开始游戏,空格键:暂停 / 继续,方向键 或 WSAD 键:控制移动方向 下载地址 原文地址:https://www.cnblogs.com/pythongood/p/11173838.html

C语言之贪吃蛇(ncurses)

声明: 以下内容可能会引起某些读者不适, 请小心阅读. 有些内容并没有详细介绍, 可能简单理解也是错误的, 但是这都是为了尽量简单. 前言: 代码是很久之前写的,属于边想边写的那种,很混乱. 推荐材料: NCURSES Programming HOWTO 贪吃蛇应该是我们这代人都玩过的游戏.而如果我们要写一个贪吃蛇最需要考虑的就是贪吃蛇是如何移动的.其实贪吃蛇的移动就是尾部的减少和头部的增加. 这篇文章: 介绍一些ncurses库的基础内容 贪吃蛇游戏的代码解释 介绍一些ncurses库的基础内

c语言版贪吃蛇小游戏

编译环境:windows 7 64位 编译工具:codeblocks 13.12 备注:未使用graphics.h 声明:个人原创,未经允许,禁止转载!!! 数据结构:双向链表 1.程序未使用graphis.h中的 函数,所以采用先清屏,再打印的方式显示图形,大约每秒刷新一次: 2.除蛇头元素外,其它元素的状态(行进方向)均重复前一元素: 3.蛇的图形元素为笑脸,可在源码中更改symbol参数选用不同元素. 游戏截图1                                      

C语言实现贪吃蛇之结构链表篇

之前的两篇博客将运用的C语言知识限定在了一般的数组上,但如果已经完整地了解过C语言的话,运用结构和链表会让程序的结构更明了,逻辑更清晰.这篇博客就将介绍如何用结构和链表改善之前的程序. 首先,我们为蛇的节点定义一个结构: typedef struct node{ COORD cor; struct node *next; }node; COORD结构我在上一篇已经介绍过,这里就直接借用了. COORD food = { 3,5 }; node *head; food也相应地由COORD来定义,并

C语言实现贪吃蛇之全靠数组篇

贪吃蛇游戏的设计思路很简单,相信有过一些编程经验的同学都不至于束手无策,可在我刚刚接触编程时,这个小小的贪吃蛇游戏可是让我费了不少脑筋,如今学习编程已经快一年了,前几天又看了一遍K&R,打算写几个贪吃蛇程序巩固一下知识.我打算写若干篇贪吃蛇的博客,从简单粗糙的开始,不断改良,希望能给初学C语言的同学一点借鉴. 话不多说,我们现在就开始吧,首先我们整理一下思路.首先我们要明确,既然贪吃蛇游戏理论上可以无限继续下去,那么游戏主体一定就是一个循环.蛇的移动就在这个循环中完成.如果是初学编程的话,可能会

架构练习:c语言实现贪吃蛇(三):封装蛇的移动方法

目前进展: 封装蛇的移动方法: typedef struct snakeinfo { int numParts;/* how many parts,蛇身体分多少个段 */ int lenParts[GAME_WIDTH];/* 蛇身体每段的长度 */ int xPartsHead[GAME_WIDTH];/* 蛇身体第i段的x坐标,初始值为1 */ int yPartsHead[GAME_WIDTH];/* 蛇身体第i段的y坐标,初始值为1 */ uchar direction;/* 蛇当前在像

架构练习:c语言实现贪吃蛇(四):接收按键改变蛇的前进方向

创建一个线程,接收按键,改变蛇的前进方向: 根据小键盘数值对应的方向: '2':蛇向下行 '4':蛇向左行 '6':蛇向右行 '8':蛇向上行 源码: #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <curses.h> #include <curses.h>