C语言“抢30”游戏代码解析
2018/11/13 18:49:49 来源:Linux社区 作者:Linux

问题描述

由两个人玩“抢30”游戏,游戏规则是:第一个人先说“1”或“2”,第二个人要接着往下说一个或两个数,然后又轮到第一个人,再接着往下说一个或两个数。这样两人反复轮流,每次每个人说一个或两个数都可以,但是不可以连说三个数,谁先抢到30,谁得胜。

问题分析

首先,分析这个游戏是否公平。一个游戏的公平性主要体现在游戏双方赢的机会性。

经分析可知,获胜者最后总能说到27,还有呢?获胜者陆续说出了 24,21,18,15,12,9,6,3。因此,只要能控制讲出上述数,就一定能在最后“抢到30”。在大家不知情的情况下,不管先说后说,都有赢的可能性,但游戏里潜藏着人为可控的必胜因素。还可以发现,失败者报1个数,获胜者就报2个数;失败者报2个数,获胜者就只报1个数。 所以获胜者总能迅速报数。

规律1使用逆推的方法。

要想抢到30,必须先抢到27,这样,无论对方说28或28、29,自己总能抢到30。要想抢到27,必须先抢到24,这样,无论对方说25或25、 26,自己总能抢到27……照此推理下去,要想抢到6,必须先要抢到3,这样无论对方说4或4、5,自己总能抢到6。最后,问题转化为如何抢到3,要想抢到3,只有让对方先开始,这样,无论对方先说1或1、2,自己总能抢到3。由此可见,这个游戏是偏向后开口的人,若这个人能抢到3,6,9,12,……,21,24, 27,则一定会赢,因此,这个游戏是不公平的。

规律2使用循环法。

根据游戏规则,第一个人可以在1或1、2中选择一个或两个数字,对于“抢30”游戏,第二个人总是可以控制每轮报数的个数为3,由于30可以被3整除,因此第二个人可以控制自己最后说到30从而获胜。

如果把“抢30”游戏改成“抢50”,可类似地进行分析。要先抢到50,就要先抢到 47,44,41,…,5, 2。因此,我们发现,“抢50”的游戏是偏向先开口的人。

下面是完整的代码:

​#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int input(int t);
int copu(int s);
int main()
{
    int tol=0;
    printf("\n* * * * * * * *catch thirty* * * * * * * \n");
    printf("Game Begin\n");
    rand();  /*初始化随机数发生器*/
    /*取随机数决定机器和人谁先走第一步。若为1,则表示人先走第一步*/
    if(rand()%2)
        tol=input(tol);
    while(tol!=30)  /*游戏结束条件*/
        if((tol=copu(tol)) == 30)  /*计算机取一个数,若为30则机器胜利*/
            printf("I lose! \n");
        else
            if((tol=input(tol)) == 30)  /*人取一个数,若为30则人胜利*/
                printf("I lose! \n");
    printf(" * * * * * * * *Game Over * * * * * * * *\n");
    return 0;
}

int input(int t)
{
    int a;
    do{
        printf("Please count:");
        scanf("%d", &a);
        if(a>2 || a<1 || t+a>30)
            printf("Error input,again!");
        else
            printf("You count:%d\n", t+a);
    }while(a>2 || a<1 || t+a>30);
    return t+a;  /*返回当前已经取走的数的累加和*/
}

int copu(int s)
{
    int c;
    printf("Computer count:");
    if((s+1)%3 == 0)  /*若剩余的数的模为1,则取1*/
        printf(" %d\n",++s);
    else
        if((s+2)%3 == 0)
        {
            s+=2;  /*若剩余的数的模为2,则取2*/
            printf(" %d\n",s);
        }
        else
        {
            c=rand()%2+1;  /*否则随机取1或2*/
            s+=c;
            printf(" %d\n",s);
        }
    return s;
}

下面是运行结果:

[linuxidc@localhost linuxidc.com]$ ./linuxidc

* * * * * * * *catch thirty* * * * * * *
Game Begin
Computer count: 2
Please count:2
You count:4
Computer count: 6
Please count:1
You count:7
Computer count: 9
Please count:2
You count:11
Computer count: 12
Please count:1
You count:13
Computer count: 15
Please count:2
You count:17
Computer count: 18
Please count:2
You count:20
Computer count: 21
Please count:2
You count:23
Computer count: 24
Please count:2
You count:26
Computer count: 27
Please count:2
You count:29
Computer count: 30
I lose!
 * * * * * * * *Game Over * * * * * * * *

​C语言“抢30”游戏代码解析

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

本文永久更新链接地址https://www.linuxidc.com/Linux/2018-11/155316.htm


6

本栏最新