<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
閱讀更多 跟黃哥學編程 的文章