从零开始制作一款游戏2(By C++)
关于
《从零开始制作一款游戏》系列是面向编程新手的小程序实例。代码都比较短,所以希望大家能跟着思路一步一步地手动输入代码不要复制黏贴!——那样只会让这篇文章对你来说毫无意义。
正文
我从网上找到了一个叫Monty Hall
的小游戏,规则是这样的:
参赛者会看见三扇关闭了的门,其中一扇的后面有一辆汽车,选中后面有车的那扇门可赢得该汽车,另外两扇门后面则各藏有一只山羊。当参赛者选定了一扇门,但未去开启它的时候,节目主持人开启剩下两扇门的其中一扇,露出其中一只山羊。主持人其后会问参赛者要不要换另一扇仍然关上的门。
要实现这个游戏,我们需要:
- 输出一个随机数的函数
rand()
。它在cstdlib
库中,不过我们还需要time()
函数来协助,它在ctime
库中。 - 让程序暂停一段时间的函数
sleep()
,我需要它来制作一个装B的开场。它在unistd.h
库中。
程序
我打算使用C++来制作这个小程序。
首先是头文件们:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "unistd.h"
using namespace std;
接下来,我把游戏的代码放进start()
函数中:
int start(void){
cout << "--------------------------------" << endl;
sleep(1);
cout << "...Game Start..." <<endl;
sleep(1);
unsigned int car_door = rand()%3;
unsigned int user_choose;
然后,玩家会选择一扇门:
cout << "Choose the door(0~2): door ";
cin >> user_choose;
if(user_choose > 2){
cout << "Maybe you should learn how to type 0/1/2\n\tGood Job!";
return 0;
}
然后就轮到主持人打开门了:
unsigned int hostess_open = rand()&3 - 1;
for(int i=1; i>0; i++){
if(hostess_open == user_choose) hostess_open = rand()&3 - 1;
else if(hostess_open == car_door) hostess_open = rand()%3 - 1;
else break;
}
cout << "I will open a door now. door " << hostess_open << " is full of sheep" << endl;
接下来,玩家会选择最后要打开的门
int user_open;
cout << "Then it's your turn\nOpen a door: door ";
cin >> user_open;
if(user_open > 2){
cout << "Maybe you should learn how to type 0/1/2\n\tGood Job!";
return 0;
}
if(user_open == car_door) cout << "\tYou Win!" << endl;
else cout << "\tYou Lose!" << endl;
}
其中,变量car_door
是后面有车的门;user_choose
是玩家最开始选择的门;user_open
是玩家最后打开的门;hostess_open
则是主持人打开的门。
最后,就是main函数了:
int main(){
srand(int(time(0)));
cout << "****************************************************************" << endl
<< "* *" << endl
<< "* Monty Hall *" << endl
<< "* *" << endl
<< "****************************************************************" << endl
<< "by ";
sleep(1);
cout << "C.";
sleep(1);
cout << "Y.";
sleep(1);
cout << "张" << endl;
sleep(1);
cout << "There is a car behind one door, other is full of sheeps.\tFind the car.\n\tGood Luck!" << endl;
start();
for(char i; i != 'N'; ){
cout << "Again?\t[Y]es\t[N]o" << endl;
cin >> i;
if(i == 'Y') start();
}
return 0;
}
运行结果
很明显,我的运气还是不错的
****************************************************************
* *
* Monty Hall *
* *
****************************************************************
by C.Y.张
There is a car behind one door, other is full of sheeps. Find the car.
Good Luck!
--------------------------------
...Game Start...
Choose the door(0~2): door 2
I will open a door now. door 0 is full of sheep
Then it's your turn
Open a door: door 1
You Win!
Again? [Y]es [N]o
Y
--------------------------------
...Game Start...
Choose the door(0~2): door 1
I will open a door now. door 4294967295 is full of sheep
Then it's your turn
Open a door: door 2
You Lose!
Again? [Y]es [N]o
怎么样,我的开场帅不帅?就写到这里,看电影去喽