简单小游戏-剪刀石头布的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的结果。
相关文章推荐
- C语言实现简单的三子棋小游戏
- 简单c语言小游戏实现原理
- 用C语言实现简单的三子棋小游戏
- C语言实现简单的三子棋小游戏
- C语言实现的一个简单的猜数小游戏
- C语言-实现简单的车辆管理系统-课程设计
- 简单视频加密【C语言实现】
- C语言使用数组实现简单队列
- C语言程序简单实现贪吃蛇小游戏—不需要graphics.h头文件
- 一个简单的加密算法Kaiser(C语言实现)
- c语言简单小游戏(模拟魔塔)
- c语言下实现stateMachine的一种简单架构
- 比之前那个版本更简单的C语言实现的比较大小
- C语言实现一个简单的计算器
- C语言简单实现接口
- C语言实现简单内存池
- 用简单的C语言实现多任务轮流切换(模拟操作系统线程机制)【转】
- [数据结构]单链表C语言的简单实现
- C语言使用结构体实现接口简单列子
- Boyer-Moore算法--C语言实现(简单易懂)