题目:剪刀石头布
虚拟机:VMware Workstation Pro
Ubuntu
第一步:创建文件
① 在opt下创建名为game的文件夹用于存放游戏
② 在game创建一个cpp文件(game.cpp)
第二步:编写代码
源代码:
#include <iostream>
#include <cstdlib>
#include <string>
#include <ctime>
using namespace std;
int main()
{ cout << "****** 欢迎来到石头剪刀布游戏 ****** \n" << endl;
cout << "游戏规则如下:石头>剪刀>布>石头\n" << endl;
cout << "其中,R代表石头,S代表剪刀,C代表布。当您输入您选择出的手势,电脑将自动生成一个手势,按照大小规则判断输赢。\n" << endl;
enum Chioce {rock, shear, cloth}; // 枚举
enum Result {you, me, tie};
Chioce yours, mine; // 定义枚举变量
Result winner;
string s1; // 定义字符串变量
cout << "你出的是:";
cin >> s1;
cout << s1 << endl;
switch (s1[0])
{
case 'R': case 'r': yours = rock; break;
case 'S': case 's': yours = shear; break;
case 'C': case 'c': yours = cloth; break;
default: break;
}
// 出错:产生的随机数并不是真的随机数。每次都是布。原因还不知道为啥
int n = rand(); // 产生随机数
cout << n << endl;
switch(n%3)
{
case 0:mine = shear; break;
case 1:mine = rock; break;
case 2:mine = cloth; break;
default: break;
}
cout << mine <<endl;
if(yours == mine) winner = tie;
if(mine == rock && yours == shear || mine == shear && yours == cloth || mine == cloth && yours == rock)
{
winner = me;
}
if(yours == rock && mine == shear || yours == shear && mine == cloth || yours == cloth && mine == rock)
{
winner = you;
}
switch(winner)
{
case you: cout << "You win!\n"; break;
case me: cout << "I win!\n"; break;
case tie: cout << "It's tie!\n"; break;
default: break;
}
return 0;
}
问题:
- 产生的随机数并不是真的随机数,而是伪随机数
- 只能运行一次游戏,无法多次运行
第三步:编译执行
①g++ 文件名 -o 执行文件名(自己设定)
②./执行文件名(程序运行成功!)