实现板球比赛的C/C++程序
在本文中,任务是创建一个 2 人板球游戏,其中玩家 1是操作程序的用户,而玩家 2是计算机。在这个游戏中,遵循以下一系列步骤:
- 首先,程序将生成一个介于 0 和 25 之间的随机数。该数字将是玩家 1 赢得这场比赛所需的分数。假设程序生成的随机数是15,那么这个数字就是玩家1需要达到的分数。
- 第二步是玩家1(用户)和玩家2(电脑)之间的真实匹配。
- 用户将使用键盘输入数字 1 到 6。然后系统将再次生成一个 1 到 6 之间的随机数。如果用户的输入与系统生成的随机数不同,那么它就是命中,用户将获得与给出的相同数字的分数由用户输入。如果两个数字匹配,则用户将出局并打印最终总分。
- 用户得分的总分是用户输入的所有数字的总和。分数是在用户每次输入后计算的。用户的先前输入 + 当前输入。
例子:
Random Number generated by System is 15. This is the winning score.
Now Player will enter number between 1 and 6.
Player: 2
System will now generate a random number between 1 and 6.
System: 1
The player is safe he can play further as both numbers are different.
Player will input a random number between 1 and 6.
Player: 3
System will now generate a random number between 1 and 6.
System: 4
This process keeps ongoing till same number is chosen by Player and System
Player: 6
System: 6
Now, as both numbers are same(player’s and system’s) then player is out.
Result: You lose, your total score is 5.
GAME OVER.
下面是实现上述方法的 C++ 程序:
C++
// C++ program for the above approach
#include
#include
#include
using namespace std;
// Driver Code
int main()
{
int totalrun = 0;
srand(time(0));
int i;
// Generate a random number
// and store in variable
i = (rand() % 25) + 1;
cout << "~~~~~~~~ CRICKET GAME ~~~"
<< "~~~~~~~" << endl;
// Displaying the winning score
cout << "Your winning score "
<< i << "\n";
// while loop for true condition
while (1) {
int player = 0;
int a;
if (totalrun > i) {
cout << "you won your score="
<< totalrun << "\n";
// To exit loop
exit(0);
}
else {
// Generate random no. and
// store in a variable
a = (rand() % 6) + 1;
cout << "Enter no. between "
<< "1 to 6" << endl;
// Taking input from user
// to score runs
cin >> player;
// Checking if user's score
// exceeds the winning score
// Displaying random number
// taken by system on screen
cout << "System: " << a << endl;
// Check if number inserted
// by user is the same random
// number generated by system
// inside loop
if (player == a) {
cout << "OUT your score ="
<< totalrun
<< endl;
// To exit loop
exit(0);
}
// Storing total runs scored
// by user
else {
totalrun = totalrun + player;
}
}
}
return 0;
}
输出: