您的位置:首页 > 编程语言 > C语言/C++

简单小游戏-剪刀石头布的c语言实现

2017-10-22 20:29 471 查看
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
char gesture[3][10] = { "scissor", "stone", "cloth" };
int man, computer, result, ret;

srand(time(NULL));
while (1) {
computer = rand() % 3;
printf("\nInput your gesture (0-scissor 1-stone 2-cloth):\n");
man = 0;
ret = scanf("%d", &man);
getchar();  //主要为了处理man输入为非数字的情况
if (ret != 1 || man < 0 || man > 2) {
printf("Invalid input! Please input 0, 1 or 2.\n");
continue;
}
printf("Your gesture: %s\tComputer's gesture: %s\n",
gesture[man], gesture[computer]);

result = (man - computer + 4) % 3 - 1;
if (result > 0)
printf("You win!\n");
else if (result == 0)
printf("Draw!\n");
else
printf("You lose!\n");
}
return 0;
}


注意

(man - computer + 4) % 3 - 1这个神奇的表达式是如何比较出0、1、2这三个数字在“剪刀石头布”意义上的大小的?

胜 负 平 胜 负

man-computer -2 -1 0 1 2

man-computer+4 2 3 4 5 6

(man-computer+4)%3 2 0 1 2 0

(man-computer+4)%3-1 1 -1 0 1 -1

剪刀石头布相生相克,形成一个环,凡是具有环的特性的数学模型都可以考虑用取模运算,首先确定了man-computer和%3,然后再调整其它常数得到normalized的结果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: