C语言编程实战——编写简单贪吃蛇程序

  心之何如,有似万丈迷津,遥亘千里,其中并无舟子可渡人,除了自渡,他人爱莫能助。
                          —-三毛

编程环境:VC++

一、相关结构体以及函数:

1、Windows下坐标结构体COORD

  COORD是Windows API中定义的一种结构,表示一个字符在控制台屏幕上的坐标。其定义为:

typedef struct _COORD {
SHORT X;    // horizontal coordinate
SHORT Y;    // vertical coordinate
} COORD;

2、SetConsoleCursorPosition()函数:

  Windows API中设置光标坐标的函数。头文件为#include < windows.h>

实例:该程序实现将“Helloword”打印到固定坐标。

#include<stdio.h>
#include<windows.h>
int main()
{
    HANDLE hOut;
    COORD pos={15,5}; 

    hOut=GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleCursorPosition(hOut,pos); //将光标位置设置为(15,5)

    printf("HelloWorld!\n");
    return 0;
}

  GetStdHandle()函数用于从一个特定的标准设备(标准输入、标准输出或标准错误)中取得一个句柄(用来标识不同设备的数值)。可以嵌套使用。每次设置光标之前必须先调用获得一个值hOut,所以可以把hOut定义成全局变量。

3、kbhit()按键捕捉函数:

  检查当前是否有键盘输入,若有则返回一个非0值,否则返回0 。

实例:程序一直打印HelloWorld,直到按“ESC”结束。

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main(void)
{
    char ch;
    while(ch!=27) //27为按键ESC的ASCII码
    {
        printf("HelloWorld\n");
        if(kbhit())   //捕捉按键
        ch=getch();   //将捕捉到的按键赋值给ch
    }
    printf("End!\n");
    system("pause");
    return 0;
}

4、rand()函数:

  rand()函数是产生随机数的一个随机函数。包含于头文件#include< stdlib.h >中。

  我们通常通过伪随机数生成器提供一粒新的随机种子。函数 srand()(来自stdlib.h)可以为随机数生成器播散种子

#include <stdio.h>
#include <stdlib.h>
int main()
{
    unsigned int seed; /*申明初始化器的种子,注意是unsigned int 型的*/
    int k;
    printf("Enter a positive integer seed value: \n");
    scanf("%u",&seed);
    srand(seed); //srand函数是随机数发生器的初始化函数
    printf("Random Numbers are:\n");
    for(k = 1; k <= 10; k++)
    {
        printf("%i",rand()); //若是rand()%n表示生成n以内的所有整数
        printf("\n");
    }
    return 0;
}

  %i和%d都是表示有符号十进制整数,但%i可以自动将输入的八进制(或者十六进制)转换为十进制,而%d则不会进行转换。


二、分模块写程序:

1、绘制边框draw_frame():

  因为我这里边框有游戏边框,和计分的边框两个,所以我封装了一个函数,方便直接调用。注意,这一Y轴正半轴是往下的,区别于我们数学中的坐标。

void draw_frame(int W,int H,int initX,int initY)   //顺时针画框函数W、H为长度高度;initX ,initY为起点坐标 

{
    COORD pos1={initX,initY};
    int i;

    for(i= 0; i< W;i++) 
    {
        pos1.X++;   //先不断往右移动
        SetConsoleCursorPosition(hOut,pos1);
        printf(".");
    }

    for(i= 0; i< H;i++)
    {
        pos1.Y++;  //再向下
        SetConsoleCursorPosition(hOut,pos1);
        printf(".");
    }

    for(i= 0; i< W;i++) //再向左
    {
        pos1.X--;
        SetConsoleCursorPosition(hOut,pos1);
        printf(".");
    }

    for(i= 0; i< H;i++)
    {
        pos1.Y--;   //再向上
        SetConsoleCursorPosition(hOut,pos1);
        printf(".");
    }

}

比如我调用draw_frame(30,20,0,0);得到如下结果:

这里写图片描述


2、计分框:score_frame()

  主要是调用上面画框函数,但是还需要作相关处理,因为要打印“得分”,以及还要能够更新数据。

void score_frame()
{
    //计分方框
    draw_frame(10,5,WIDTH+10,0);   //调用上面画框函数画一个宽度为5,高度为10,起始坐标为(WIDTH+10,0)的框。这里我们把起始坐标放在了原来边框右边10单位初,因为是顺时针画,最终回到(WIDTH+10,0)这个点,所以只要起始点X轴大于WIDTH就可以了。

    //将光标挪到方框内,打印“得分:”提示字符
    COORD pos1={WIDTH+11,1}; 
    SetConsoleCursorPosition(hOut,pos1);
    printf("得分:");

    //将光标继续挪动,用于计分:
    COORD pos2={WIDTH+12,2};   //写计分位置的初始坐标,因为之前方框的起始坐标为(10,1),所以这里都加1。
    SetConsoleCursorPosition(hOut,pos2);

    printf("%d",score);
}

这里写图片描述


3、初始化贪吃蛇身:

  想要画出一条蛇,一个点一个点画,将每个点的坐标都保存在一个数组里面。

void InitSnake(COORD SnakeHead)
{
    int i;
    COORD temp = SnakeHead; //蛇头的起始坐标
    for( i=0 ; i< InitLEN ; i++ )
    {   
        arr[i]=temp;  //通过数组来存储蛇,方便后面显示
        SetConsoleCursorPosition(hOut,temp);

        temp.X--;    //打印一截,光标移动,避免覆盖打印在同一个点上。
    }

    SnakeLEN = InitLEN; //InitLEN是一个宏定义,蛇的初始长度
}

4、显示蛇身:

void showSnake()
{   
    int i;
    for( i=0; i < SnakeLEN;i++)
    {
        SetConsoleCursorPosition(hOut,arr[i]); //设置光标位置
        if(i == 0)        
        {
            printf("@"); //最先打印的是蛇头
        }
        else
        {

            printf("*"); 蛇身
        }
    }
}

蛇头坐标为(5,3)
这里写图片描述


4、用随机数产生随机食物:

void creatFood()
{
    srand((unsigned)time(NULL));
    int x = (rand()%(WIDTH-1)+1);  //-1为了产生随机数小于WIDTH,+1为了使产生随机数大于0
    int y = (rand()%(HIGH-1)+1);
    food_pos.X =x; //food_pos是一个COORD变量
    food_pos.Y =y;
    SetConsoleCursorPosition(hOut,food_pos);
    printf("o");  //打印食物图样
}

5.1、清除蛇身函数clearSnake()

void clearSnake()   
{   
    int i;
    for( i=0; i < SnakeLEN;i++)
    {
        SetConsoleCursorPosition(hOut,arr[i]);
        printf(" ");  //打印空格来覆盖之前的轨迹。
    }
}

5.2、移动move():

  上面画出了一条蛇,但是是静态的,我们要想办法让它动起来,动次动次,小火车要跑起来了。
  移动的主要思想就是通过单位时间上的位移来实现的,也相当于设定时间的画线,不过每次移动都需要把之前的蛇清除,然后再打印一次,让我们看起来就像有一条蛇在动。

void move(int dir)
{
    int i;
    Sleep(100);     //通过单位时间上位移来控制移动
    clearSnake();   //清除走过的轨迹


    //将前一个点的状态给后一个点,当i=SnakeLEN-2,将蛇头状态赋给第二个值。所以每隔100ms,后一个点的坐标就等于前一个点的坐标了。
    for( i=0;i<SnakeLEN-1;i++)
    {
        arr[SnakeLEN-1-i] = arr[SnakeLEN-2-i];
    }


    //这里RIGHT 、LEFT、UP、DOWN是宏定义,分别存放d a s w的ascii码
    switch(dir){
    case RIGHT:
        {
            arr[0].X++;   //蛇头运动
            break;  
        }
    case LEFT:
        {
            arr[0].X--;
            break;  
        }

    case UP:
        {
            arr[0].Y--;
            break;  
        }

    case DOWN:
        {
            arr[0].Y++;
            break;  
        }
    default:
        break;
    }

    die();  //死亡的几种方式,下文作做介绍

    //吃食物:
    if(food_pos.X == arr[0].X && food_pos.Y == arr[0].Y )    //头的坐标和食物坐标相同(吃食物变长)
    {

        creatFood();   //产生随机食物
        SnakeLEN++;    //蛇身长度增加

        COORD pos2={WIDTH+12,2};   //写计分位置的初始坐标,因为之前方框的起始坐标为(10,1),所以这里都加1。
        SetConsoleCursorPosition(hOut,pos2);

        score++;
        printf("%d",score);
        printf(" ");        //打印空白用于覆盖上一次计分


    }

    showSnake();  //因为每次移动都会清除之前的蛇,所以每次都需要再打印一次。
}

6、死亡的几种方式:

  • 撞到墙挂掉:蛇头坐标超出方框
  • 吃到自己挂掉:蛇头坐标和身体任何部位坐标相等
  • 撞到障碍物挂掉:蛇头坐标和障碍物坐标相等
void die()
{
    int i;
    for(i = 1;i < SnakeLEN-1;i++ )   //吃到自己,就会死掉。
    {
        if(arr[0].X == arr[i].X && arr[0].Y == arr[i].Y)
        {
            myexit();   
        }
    }

    if(arr[0].X >= WIDTH || arr[0].X <= 0 || arr[0].Y >= HIGH || arr[0].Y <= 0 )   //撞墙就死掉
    {
        myexit();
    }


    for(i = 0;i < 50;i++ )   //撞到障碍物,死掉
    {

        if(arr[0].X == tmp_arr[i].X && arr[0].Y == tmp_arr[i].Y)
        {
            myexit();  //GAME OVER
        }
    }

}

7、产生障碍物:

void barrier_save()      //保存所有生成的障碍物的点(所有障碍物由点组成)
{
    tmp_arr[barrier_num]=tmp_barrier;
    barrier_num++;           //全局变量
}

void creatBarrier(COORD pos,int dir,int len)
{
    int i =0;
    tmp_barrier=pos;

    for(;i < len; i++)
    {
        static int j=0;
        SetConsoleCursorPosition(hOut,tmp_barrier);
        printf("+");
        if(dir == 1 ) //dir的为0为1的值为二分之一,为了让它产生横向和纵向的障碍物概率相同。
        {
            tmp_barrier.X++;
            barrier_save();    //每次改变都会获得一个新的点,需要把这个点记录下来。
        }
        else 
        {
            tmp_barrier.Y++;
            barrier_save();
        }

        barrier_save();
    }
}
void crossWall()
{
    srand((unsigned)time(NULL));
    int i =0;
    for ( ; i < 5 ; i++) 
    {
        //随机数产生障碍物
        tmp_wall.X=(rand()%(WIDTH-3)); 
        tmp_wall.Y=(rand()%(HIGH-3));
        half = (rand()%2+1);   //随机获得 1 或者 2 ,两者概率都为二分之一

        creatBarrier(tmp_wall,half,3); //产生一个长度为3的障碍物
    }
}

8、键盘控制:

这里主要是通过kbhit()函数来捕捉按键,这很关键,让我少走了很多弯路。

void kbctrl()
{   
    char ch = 'd';   //设定起始按键为‘d’,为了让它开始就向右走
    int dir=RIGHT;   //设定起始移动方向
    while(1)
    {   

        if(kbhit())      //加入键盘控制,判断是否有按键
        {
            ch=getch();
        }

        switch(ch)      //判断是否是按键
        {
            case 'd':          
            {   
                dir = RIGHT;
                move(dir);
                break; //跳出以后依旧可以保持原来状态
            }

            case 's':
            {
                dir = DOWN;
                move(dir);
                break;
            }

            case 'a':
            {
                dir = LEFT;
                move(dir);
                break;
            }

            case 'w':
            {   
                dir = UP;
                move(dir);
                break;
            }

            default:   //按其他键,保持原来状态
            {
                move(dir);  
                break;
            }
        }
    }

}

完整代码:

// myproject.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h >
#include <time.h>

#define InitLEN   10
#define MAXLEN 100

#define HIGH 20
#define WIDTH  40

int SnakeLEN=0;
int score=0;       //得分
int barrier_num =0;  //所有障碍物组成点的个数

int half;       
//#define HPRIZON       1
//#define VERTICAL  2

COORD arr[MAXLEN];
COORD tmp_arr[50];

COORD food_pos;
COORD map_pos;
COORD tmp_wall;
COORD tmp_barrier;

#define RIGHT 39
#define LEFT  37
#define UP    38
#define DOWN  40



HANDLE hOut=GetStdHandle(STD_OUTPUT_HANDLE);

void clearSnake();
void showSnake();
void creatFood();
void creatMap();
void die();
void barrier_save();

void creatBarrier(COORD pos,int dir,int len);
void crossWall();

struct wall{
    int dir;
    int len;
    COORD bPos;
};

struct wall wall_arr[50];



void draw_frame(int W,int H,int initX,int initY)   //顺时针画框函数W、H为长度高度;initX ,initY为其实坐标 
{
    COORD pos1={initX,initY};
    int i;

    for(i= 0; i< W;i++)
    {
        pos1.X++;
        SetConsoleCursorPosition(hOut,pos1);
        printf(".");
    }

    for(i= 0; i< H;i++)
    {
        pos1.Y++;
        SetConsoleCursorPosition(hOut,pos1);
        printf(".");
    }

    for(i= 0; i< W;i++)
    {
        pos1.X--;
        SetConsoleCursorPosition(hOut,pos1);
        printf(".");
    }

    for(i= 0; i< H;i++)
    {
        pos1.Y--;
        SetConsoleCursorPosition(hOut,pos1);
        printf(".");
    }

}


void InitSnake(COORD SnakeHead)
{
    int i;
    COORD temp = SnakeHead;
    for( i=0 ; i< InitLEN ; i++ )
    {   
        arr[i]=temp;
        SetConsoleCursorPosition(hOut,temp);

        printf("@");

        temp.X--;
    }

    SnakeLEN = InitLEN;
}

void move(int dir)
{
    int i;
    Sleep(100);
    clearSnake();


    //将蛇头状态给蛇身
    for( i=0;i<SnakeLEN-1;i++)
    {
        arr[SnakeLEN-1-i] = arr[SnakeLEN-2-i];
    }


    switch(dir){
    case RIGHT:
        {
            arr[0].X++;   //蛇头运动
            break;  
        }
    case LEFT:
        {
            arr[0].X--;
            break;  
        }

    case UP:
        {
            arr[0].Y--;
            break;  
        }

    case DOWN:
        {
            arr[0].Y++;
            break;  
        }
    default:
        break;
    }

    die();


    if(food_pos.X == arr[0].X && food_pos.Y == arr[0].Y )    //头的坐标和食物坐标相同(吃食物变长)
    {

        creatFood();
        SnakeLEN++;

        COORD pos2={WIDTH+12,2};   //写计分位置的初始坐标,因为之前方框的起始坐标为(10,1),所以这里都加1。
        SetConsoleCursorPosition(hOut,pos2);

        score++;
        printf("%d",score);
        printf(" ");        //打印空白用于覆盖上一次计分


    }




 //show snake
    showSnake();


}


void showSnake()
{   
    int i;
    for( i=0; i < SnakeLEN;i++)
    {
        SetConsoleCursorPosition(hOut,arr[i]);
        if(i == 0)
        {
            printf("@");
        }
        else
        {

            printf("*");
        }
    }
}

void clearSnake()   
{   
    int i;
    for( i=0; i < SnakeLEN;i++)
    {
        SetConsoleCursorPosition(hOut,arr[i]);
        printf(" ");
    }
}


void barrier_save()      //保存所有生成的障碍物的点(所有障碍物由点组成)
{
    tmp_arr[barrier_num]=tmp_barrier;
    barrier_num++;           //全局变量
}

void creatBarrier(COORD pos,int dir,int len)
{
    int i =0;
    tmp_barrier=pos;

    for(;i < len; i++)
    {
        static int j=0;
        SetConsoleCursorPosition(hOut,tmp_barrier);
        printf("+");
        if(dir == 1 )
        {
            tmp_barrier.X++;
            barrier_save();    //每次改变都会获得一个新的点,需要把这个点记录下来。
        }
        else 
        {
            tmp_barrier.Y++;
            barrier_save();
        }

        barrier_save();
    }



}


void kbctrl()
{   
    char ch = 'd';
    int dir=RIGHT;
    while(1)
    {   

        if(kbhit())      //加入键盘控制,判断是否有按键
        {
            ch=getch();
        }

        switch(ch)      //判断是否是 'a' 's'
        {
            case 'd':          
            {   
                dir = RIGHT;
                move(dir);
                break;
            }

            case 's':
            {
                dir = DOWN;
                move(dir);
                break;
            }

            case 'a':
            {
                dir = LEFT;
                move(dir);
                break;
            }

            case 'w':
            {   
                dir = UP;
                move(dir);
                break;
            }

            default:
            {
                move(dir);
                break;
            }
        }
    }

}


void creatFood()
{
    srand((unsigned)time(NULL));
    int x = (rand()%(WIDTH-1)+1);  //-1为了产生随机数小于WIDTH,+1为了使产生随机数大于0
    int y = (rand()%(HIGH-1)+1);
    food_pos.X =x;
    food_pos.Y =y;
    SetConsoleCursorPosition(hOut,food_pos);
    printf("o");
}


void myexit()
{
    COORD exit_pos={WIDTH+2,HIGH+2};
    SetConsoleCursorPosition(hOut,exit_pos);
    printf("GAME OVER!");
    exit(0);
}

//死亡的方式:
void die()
{
    int i;
    for(i = 1;i < SnakeLEN-1;i++ )   //吃到自己,就会死掉。
    {
        if(arr[0].X == arr[i].X && arr[0].Y == arr[i].Y)
        {
            myexit();   
        }
    }

    if(arr[0].X >= WIDTH || arr[0].X <= 0 || arr[0].Y >= HIGH || arr[0].Y <= 0 )   //撞墙就死掉
    {
        myexit();
    }


    for(i = 0;i < 50;i++ )   //撞到障碍物,死掉
    {

        if(arr[0].X == tmp_arr[i].X && arr[0].Y == tmp_arr[i].Y)
        {
            myexit();
        }
    }

}


void score_frame()
{
    //计分方框
    draw_frame(10,5,WIDTH+10,0);
    COORD pos1={WIDTH+11,1};
    SetConsoleCursorPosition(hOut,pos1);
    printf("得分:");

    //计分
    COORD pos2={WIDTH+12,2};   //写计分位置的初始坐标,因为之前方框的起始坐标为(10,1),所以这里都加1。
    SetConsoleCursorPosition(hOut,pos2);

    printf("%d",score);
}



int main(int argc, char* argv[])
{

    system("title 贪吃蛇");
    COORD pos={5,3};
    crossWall();
    draw_frame(WIDTH,HIGH,0,0);
    score_frame();

    InitSnake(pos);


    creatFood();

/*  
    while(1)
    {
        move(RIGHT);
        if(kbhit())
        {
            ch=getch();
            break;
        }   
    }
*/  
    kbctrl();

    printf("\n");
    return 0;
}


void crossWall()
{
    srand((unsigned)time(NULL));
    int i =0;
    for ( ; i < 5 ; i++)
    {

        tmp_wall.X=(rand()%(WIDTH-3));
        tmp_wall.Y=(rand()%(HIGH-3));
    //  tmp_arr[i] = tmp_wall;

        half = (rand()%2+1);   //随机获得 1 或者 2 ,两者概率都为二分之一

        creatBarrier(tmp_wall,half,3);
    }
}

运行效果:

这里写图片描述

心得体会:

  花了三天写了代码,由浅入深的系统的写了一个完整的小项目,还是蛮有成就感的,也进一步对C语言的知识进行巩固。在这个过程中,遇到蛮多问题的。学会了如何一步一步去解决。

  比如最开始虽然实现了贪吃蛇的移动问题,通过网上搜索也学会了使用清屏函数system(“cls”)去清除移动过程中的的轨迹,但是到最后发现了个问题,如果使用这个函数的话,是清除整个屏幕,那我画好的边界不就没了么?通过询问老师,后来得到了解决方法,就是通过打印空格来实现清除,当时就恍然大悟。然后又把代码推翻重新去写清除这部分代码了。

第二个问题就是当时不知道用kbhit()这个函数来捕捉按键,自己用直接通过switch来判断输入按键的值,来用for循环来控制移动,然后发现发现这样很不科学,要等for循环结束以后它才会再一次捕捉按键。后来发现竟然有kbhit()这么好使,所以问题就变得简单了。

   问题是当时想着控制它转弯不那么别扭,最开始的想法是通过坐标的形式,因为当时是想着蛇头的坐标始终比后一个坐标大一个单位,所以想让蛇身依次每个向前多移动一步,但是没有考虑到时间问题,只考虑空间问题,后来发现是并排往下走的。后来经过老师指点,原来思想是蛇头动,带动后面的,没移动一步,把前面一点的位置信息赋值给下一个点,这样就是后面的点在重复前面相邻点的运动。。

  • 9
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
适用于初学者    经典c程序100例==11--20 【程序11】 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月    后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少? 1.程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21.... 2.程序源代码: #include "stdio.h" #include "conio.h" main() { long f1,f2; int i; f1=f2=1; for(i=1;i<=20;i++) { printf("%12ld %12ld",f1,f2); if(i%2==0) printf("\n"); /*控制输出,每行四个*/ f1=f1+f2; /*前两个月加起来赋值给第三个月*/ f2=f1+f2; /*前两个月加起来赋值给第三个月*/ } getch(); } ============================================================== 【程序12】 题目:判断101-200之间有多少个素数,并输出所有素数。 1.程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,       则表明此数不是素数,反之是素数。        2.程序源代码: #include "stdio.h" #include "conio.h" #include "math.h" main() { int m,i,k,h=0,leap=1; printf("\n"); for(m=101;m<=200;m++) { k=sqrt(m+1); for(i=2;i<=k;i++) if(m%i==0) { leap=0; break; } if(leap) { printf("%-4d",m); h++; if(h%10==0) printf("\n"); } leap=1; } printf("\nThe total is %d",h); getch(); } ============================================================== 【程序13】 题目:打印出所有的“水仙花数”,所谓“水仙花数”是指一个三位数,其各位数字立方和等于该数    本身。例如:153是一个“水仙花数”,因为153=1的三次方+5的三次方+3的三次方。 1.程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。 2.程序源代码: #include "stdio.h" #include "conio.h" main() { int i,j,k,n; printf("'water flower'number is:"); for(n=100;n<1000;n++) { i=n/100;/*分解出百位*/ j=n/10%10;/*分解出十位*/ k=n%10;/*分解出个位*/ if(i*100+j*10+k==i*i*i+j*j*j+k*k*k) printf("%-5d",n); } getch(); } ============================================================== 【程序14】 题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。 程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成: (1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。 (2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数你n,  重复执行第一步。 (3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。 2.程序源代码: /* zheng int is divided yinshu*/ #include "stdio.h" #include "conio.h" main() { int n,i; printf("\nplease input a number:\n"); scanf("%d",&n); printf("%d=",n); for(i=2;i<=n;i++) while(n!=i) { if(n%i==0) { printf("%d*",i); n=n/i; } else break; } printf("%d",n); getch(); } ============================================================== 【程序15】 题目:利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,    60分以下的用C表示。 1.程序分析:(a>b)?a:b这是条件运算符的基本例子。 2.程序源代码: #include "stdio.h" #include "conio.h" main() { int score; char grade; printf("please input a score\n"); scanf("%d",&score); grade=score>=90?'A':(score>=60?'B':'C'); printf("%d belongs to %c",score,grade); getch(); } ============================================================== 【程序16】 题目:输入两个正整数m和n,求其最大公约数和最小公倍数。 1.程序分析:利用辗除法。 2.程序源代码: #include "stdio.h" #include "conio.h" main() { int a,b,num1,num2,temp; printf("please input two numbers:\n"); scanf("%d,%d",&num1,&num2); if(num1<num2)/*交换两个数,使大数放在num1上*/ { temp=num1; num1=num2; num2=temp; } a=num1;b=num2; while(b!=0)/*利用辗除法,直到b为0为止*/ { temp=a%b; a=b; b=temp; } printf("gongyueshu:%d\n",a); printf("gongbeishu:%d\n",num1*num2/a); getch(); } ============================================================== 【程序17】 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。 1.程序分析:利用while语句,条件为输入的字符不为'\n'.        2.程序源代码: #include "stdio.h" #include "conio.h" main() { char c; int letters=0,space=0,digit=0,others=0; printf("please input some characters\n"); while((c=getchar())!='\n') { if(c>='a'&&c<='z'||c>='A'&&c<='Z') letters++; else if(c==' ') space++; else if(c>='0'&&c<='9') digit++; else others++; } printf("all in all:char=%d space=%d digit=%d others=%d\n",letters, space,digit,others); getch(); } ============================================================== 【程序18】 题目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时    共有5个数相加),几个数相加有键盘控制。 1.程序分析:关键是计算出每一项的值。 2.程序源代码: #include "stdio.h" #include "conio.h" main() { int a,n,count=1; long int sn=0,tn=0; printf("please input a and n\n"); scanf("%d,%d",&a,&n); printf("a=%d,n=%d\n",a,n); while(count<=n) { tn=tn+a; sn=sn+tn; a=a*10; ++count; } printf("a+aa+...=%ld\n",sn); getch(); } ============================================================== 【程序19】 题目:一个数如果恰好等于它的因子之和,这个数就称为“完数”。例如6=1+2+3.编程    找出1000以内的所有完数。 1. 程序分析:请参照程序<--上页程序14. 2.程序源代码: #include "stdio.h" #include "conio.h" main() { static int k[10]; int i,j,n,s; for(j=2;j<1000;j++) { n=-1; s=j; for(i=1;i<j;i++) { if((j%i)==0) { n++; s=s-i; k[n]=i; } } if(s==0) { printf("%d is a wanshu",j); for(i=0;i<n;i++) printf("%d,",k[i]); printf("%d\n",k[n]); } } getch(); } ============================================================== 【程序20】 题目:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在    第10次落地时,共经过多少米?第10次反弹多高? 1.程序分析:见下面注释 2.程序源代码: #include "stdio.h" #include "stdio.h" main() { float sn=100.0,hn=sn/2; int n; for(n=2;n<=10;n++) { sn=sn+2*hn;/*第n次落地时共经过的米数*/ hn=hn/2; /*第n次反跳高度*/ } printf("the total of road is %f\n",sn); printf("the tenth is %f meter\n",hn); getch(); }
用windows api 做的贪吃蛇 #include #include"resource.h" #include"Node.h" #include #include TCHAR szAppname[] = TEXT("Snack_eat"); #define SIDE (x_Client/80) #define x_Client 800 #define y_Client 800 #define X_MAX 800-20-SIDE //点x的范围 #define Y_MAX 800-60-SIDE //点y的范围 #define TIME_ID 1 #define SECOND 100 #define NUM_POINT 10 //点的总个数 #define ADD_SCORE 10 LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { HWND hwnd; //窗口句柄 MSG msg; //消息 WNDCLASS wndclass; //窗口类 HACCEL hAccel;//加速键句柄 wndclass.style = CS_HREDRAW | CS_VREDRAW; //窗口的水平和垂直尺寸被改变时,窗口被重绘 wndclass.lpfnWndProc = WndProc; //窗口过程为WndProc函数 wndclass.cbClsExtra = 0; //预留额外空间 wndclass.cbWndExtra = 0; //预留额外空间 wndclass.hInstance = hInstance; //应用程序的实例句柄,WinMain的第一个参数 wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); //设置图标 wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); //载入预定义的鼠标指针 wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); //设置画刷 wndclass.lpszMenuName = szAppname; //设置菜单 wndclass.lpszClassName = szAppname; //设置窗口类的名字 if (!RegisterClass(&wndclass))//注册窗口类 { MessageBox(NULL, TEXT("这个程序需要windows NT!"), szAppname, MB_ICONERROR); return 0; } hwnd = CreateWindow(szAppname, TEXT("Snack_eat"),//CreateWindow函数调用时,WndProc将受到WM_CREATE WS_OVERLAPPEDWINDOW&~WS_THICKFRAME& ~WS_MAXIMIZEBOX,//普通的层叠窗口&禁止改变大小&禁止最大化 CW_USEDEFAULT, //初始x坐标(默认) CW_USEDEFAULT, //初始y坐标 x_Client, //初始x方向尺寸 770 y_Client, //初始y方向尺寸 750 NULL, //父窗口句柄 NULL, //窗口菜单句柄 hInstance, //程序实例句柄 WinMain函数中第二个参数 NULL); //创建参数 ShowWindow(hwnd, iCmdShow);//显示窗口,iCmdShow是WinMain的第四个参数,决定窗口在屏幕中的初始化显示形式,例:SW_SHOWNORMAL表示正常显示 UpdateWindow(hwnd);//使窗口客户区重绘,通过向WndProc发送一条WM_PAINT消息而完成的 hAccel = LoadAccelerators(hInstance, szAppname);//加载加速键 while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(hwnd, hAccel, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } }/* while (GetMessage(&msg, NULL, 0, 0))//GetMessage函数从消息队列中得到消息,填充msg。如果msg.message等于WM_QUIT,返回0,否则返回非0 { TranslateMessage(&msg);//将msg返回给windows已进行某些键盘消息的转换 DispatchMessage(&msg);//将msg再次返回给windows }*/ return msg.wParam;//msg.wParam是PostQuitMessage函数的参数值,通常是0 } ...
以下是一个简单贪吃蛇游戏程序,使用了C语言和标准库函数: ```c #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <windows.h> // 定义界面大小 #define WIDTH 30 #define HEIGHT 20 // 定义蛇的最大长度 #define MAX_LENGTH WIDTH*HEIGHT // 定义蛇的方向 #define UP 1 #define DOWN 2 #define LEFT 3 #define RIGHT 4 // 定义蛇身体和食物的标识符 #define BODY '*' #define FOOD '$' // 定义全局变量 int score = 0; // 得分 int direction = RIGHT; // 初始方向为向右 int length = 3; // 初始长度为3 int x[MAX_LENGTH] = {0}, y[MAX_LENGTH] = {0}; // 蛇的坐标数组 int food_x, food_y; // 食物的坐标 // 初始化游戏 void init() { // 隐藏光标 HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO cci; GetConsoleCursorInfo(hOut, &cci); cci.bVisible = FALSE; SetConsoleCursorInfo(hOut, &cci); // 初始化蛇的坐标 x[0] = WIDTH/2; y[0] = HEIGHT/2; for (int i = 1; i < length; i++) { x[i] = x[i-1]-1; y[i] = y[i-1]; } // 随机生成食物的坐标 srand((unsigned) time(NULL)); food_x = rand()%WIDTH; food_y = rand()%HEIGHT; } // 绘制界面 void draw() { system("cls"); // 清屏 // 绘制上边界 for (int i = 0; i < WIDTH+2; i++) { printf("#"); } printf("\n"); // 绘制中间部分 for (int i = 0; i < HEIGHT; i++) { printf("#"); for (int j = 0; j < WIDTH; j++) { // 判断当前位置是否为蛇身体 int is_body = 0; for (int k = 0; k < length; k++) { if (x[k] == j && y[k] == i) { printf("%c", BODY); is_body = 1; break; } } // 判断当前位置是否为食物 if (!is_body && j == food_x && i == food_y) { printf("%c", FOOD); } else if (!is_body) { printf(" "); } } printf("#\n"); } // 绘制下边界 for (int i = 0; i < WIDTH+2; i++) { printf("#"); } printf("\n"); // 显示得分 printf("Score: %d\n", score); } // 控制蛇的移动 void move() { // 获取键盘输入 if (_kbhit()) { char ch = _getch(); switch (ch) { case 'w': case 'W': if (direction != DOWN) { direction = UP; } break; case 's': case 'S': if (direction != UP) { direction = DOWN; } break; case 'a': case 'A': if (direction != RIGHT) { direction = LEFT; } break; case 'd': case 'D': if (direction != LEFT) { direction = RIGHT; } break; } } // 更新蛇的坐标 for (int i = length-1; i > 0; i--) { x[i] = x[i-1]; y[i] = y[i-1]; } switch (direction) { case UP: y[0]--; break; case DOWN: y[0]++; break; case LEFT: x[0]--; break; case RIGHT: x[0]++; break; } // 判断是否吃到食物 if (x[0] == food_x && y[0] == food_y) { // 随机生成新的食物坐标 food_x = rand()%WIDTH; food_y = rand()%HEIGHT; // 增加蛇的长度 length++; score++; } // 判断是否撞墙或撞到自己 if (x[0] < 0 || x[0] >= WIDTH || y[0] < 0 || y[0] >= HEIGHT) { printf("Game Over!\n"); exit(0); } for (int i = 1; i < length; i++) { if (x[i] == x[0] && y[i] == y[0]) { printf("Game Over!\n"); exit(0); } } } int main() { init(); // 初始化游戏 // 主循环 while (1) { draw(); // 绘制界面 move(); // 控制蛇的移动 Sleep(100); // 暂停100毫秒 } return 0; } ``` 这个程序使用了Windows API中的一些函数,如`GetStdHandle`、`CONSOLE_CURSOR_INFO`和`SetConsoleCursorInfo`等,用于隐藏光标。`_kbhit`和`_getch`函数用于读取键盘输入,`Sleep`函数用于暂停程序一定的时间。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值