<code>设计一个"石头,剪子,布"游戏,有时又叫"Rochambeau",你小时候可能玩过,下面是规则.
你和你的对手,在同一时间做出特定的手势,必须是下面一种手势:石头,剪子,布.胜利者从
下面的规则中产生,这个规则本身是个悖论.
(a) 布包石头.
(b)石头砸剪子,
(c)剪子剪破布.在你的计算机版本中,用户输入她/他的选项,计算机找一个随机选项,然后由你
的程序来决定一个胜利者或者平手.注意:最好的算法是尽量少的使用 if 语句./<code>
<code>/*
本代码由黄哥Python培训 黄哥所写,改写于黄哥Python版本的思路。
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int exist_in(char *arr1[][2], char *arr2[], int length);
int main(void)
{
int i = 0, length;
time_t t;
char *person ;
char *computer ;
char *computer_person[2];
char *guess_arr[] = {"石头", "剪刀", "布"};
char *win[3][2] = {{"布", "石头"}, {"石头", "剪刀"}, {"剪刀", "布"}};
length = (int)sizeof(win)/(int)sizeof(win[0]);
while (1)
{
srand((unsigned) time(&t));
i = rand() % 3 ;
computer = (char *)malloc(100 * sizeof(char));
strcpy(computer,guess_arr[i] );
printf("请输入 剪刀 石头 布:\\n");
person = (char *)malloc(100 * sizeof(char));
scanf("%s", person);
computer_person[0] = computer;
computer_person[1] = person;
if (strcmp(computer, person) == 0 )
{
printf("平手!\\n");
}
else if (exist_in(win, computer_person, length))
{
printf("电脑获胜\\n");
}
else
{
printf("人获胜\\n");
free(computer);
free(person);
person = NULL;
computer = NULL;
break;
}
free(computer);
free(person);
person = NULL;
computer = NULL;
}
return 0;
}
// 判断字符串组成的数组在不在一位二维的数组中
int exist_in(char *arr1[][2], char *arr2[], int length)
{
int i;
for (i = 0; i < length; i++)
{
if (strcmp(arr1[i][0], arr2[0]) == 0 && strcmp(arr1[i][1], arr2[1]) == 0)
{
return 1;
}
}
return 0;
}/<string.h>/<time.h>/<stdlib.h>/<stdio.h>/<code>
Python、PHP、Go 版本请看
https://github.com/pythonpeixun/article/blob/master/jdstb.md
閱讀更多 跟黃哥學編程 的文章