剪刀石头布(也称为石头剪刀布)是一种手工游戏,在两个人之间玩,每个玩家同时形成三种形状中的一种。游戏的获胜者是根据以下规则决定的:
- 摇滚vs纸->纸胜。
- 岩石vs剪刀->岩石获胜。
- 纸vs剪->剪胜。
在该游戏中,将要求用户做出选择,并根据用户和计算机的选择,然后将结果与计算机和用户的选择一起显示。
方法:下面是程序中需要实现的功能:
main()函数:
- 它由变量的声明组成。
- printf()和scanf()函数用于显示内容并从用户那里获取输入。它还包含两个预定义的功能:
- srand()和rand()用于生成[0,RAND_MAX)和srand()范围内的随机数,尤其有助于每次生成一个随机数。
- 取用100生成的随机数取模,使其范围在(0到100)之间。
- 由于范围最多只有100个,因此所有选项(例如石头,纸张和剪刀)之间的分布相等,因为所有选项都有相等的出现概率。
Note: This random number will decide the choice of computer as:
- If the number is between 0-33 then the choice will be Stone.
- If the number is between 33-66 then the choice will be Paper.
- If the number is between 66-100 then the choice will be Scissors.
game()函数:此函数由if-else语句组成,该语句将比较用户和计算机的选择。如果用户获胜,则它将返回1 。否则,如果计算机获胜,它将返回0 。如果是平局,则将返回-1 。
下面是上述方法的实现:
C
// C program for the above approach
#include
#include
#include
// Function to implement the game
int game(char you, char computer)
{
// If both the user and computer
// has chose the same thing
if (you == computer)
return -1;
// If user's choice is stone and
// computer's choice is paper
if (you == 's' && computer == 'p')
return 0
// If user's choice is paper and
// computer's choice is stone
else if (you == 'p' && computer == 's') return 1;
// If user's choice is stone and
// computer's choice is scissor
if (you == 's' && computer == 'z')
return 1;
// If user's choice is scissor and
// computer's choice is stone
else if (you == 'z' && computer == 's')
return 0;
// If user's choice is paper and
// computer's choice is scissor
if (you == 'p' && computer == 'z')
return 0;
// If user's choice is scissor and
// computer's choice is paper
else if (you == 'z' && computer == 'p')
return 1;
}
// Driver Code
int main()
{
// Stores the random number
int n;
char you, computer, result;
// Chooses the random number
// every time
srand(time(0));
// Make the random number less
// than 100, divided it by 100
n = rand() % 100;
// Using simple probability 100 is
// roughly divided among stone,
// paper, and scissor
if (n < 33)
// s is denoting Stone
computer = 's';
else if (n > 33 && n < 66)
// p is denoting Paper
computer = 'p';
// z is denoting Scissor
else
computer = 'z';
printf("\n\n\n\n\t\t\t\tEnter s "
"for STONE, p for PAPER "
"and z for SCISSOR\n\t\t\"
"t\t\t\t\t");
// input from the user
scanf("%c", &you);
// Function Call to play the game
result = game(you, computer);
if (result == -1) {
printf("\n\n\t\t\t\tGame Draw!\n");
}
else if (result == 1) {
printf("\n\n\t\t\t\tWow! "
"You have won the game!\n");
else printf("\n\n\t\t\t\tOh! You "
"have lost the game!\n");
printf("\t\t\t\tYOu choose : %c"
" and Computer choose : "
"%c\n",
you, computer);
return 0;
}
输出:
- 首先,将询问用户有关选择:
- 当用户输入选项时,将显示结果:
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。