骰子各个面的关系如下:
1-6
2-5
3-4
总和为7,并且123得两两相邻,456同理。
难点在于第一次随机数确定顶面与底部后,旁边四个面必须符合上面的规则,不能随机给面赋值。
屎山又来了!
#ifndef DICE_H
#define DICE_H
#include<vector>
using namespace std;
class Dice {
public:
void getNum();
void Dynamicnum(vector <int>& a);
void Show(vector <int>& a);
private:
TRandom rand;
};
#endif
下面这个用srand() rand()代替也行
#ifndef TRANDOM_H
#define TRANDOM_H
#include <limits.h> //定义INT_MAX和ULONG_MAX常量
#include <windows.h> //定义GetTickCount()函数,其返回从开机到现在经过的毫秒数
class TRandom
{
public:
TRandom(long seed = 0) { mSeed = (seed ? seed : GetTickCount()); }
void Seed(long seed = 0) { mSeed = (seed ? seed : GetTickCount()); }
int Integer() { return Next(); }
int Integer(int min, int max) { return min + Next() % (max - min + 1); }
double Real() { return double(Next()) / double(INT_MAX); }
private:
void Change() { mSeed = (314159265 * mSeed + 13579) % ULONG_MAX; }
int Next() {
int loops = mSeed % 3; for (int i = 0; i <= loops; i++) Change();
return int(mSeed / 2);
}
unsigned long mSeed;
};
#endif
#include<iostream>
#include <algorithm>
#include"TRandom.h"
#include"Dice.h"
#include<vector>
using namespace std;
//这样写把骰子固定死了
vector<int> value34{ 6,5,1,2 };
vector<int> value16{ 3,5,4,2 };
vector<int> value25{ 3,1,4,6 };
int main() {
Dice dice;
dice.getNum();
return 0;
}
void Dice::getNum() {
int top = rand.Integer(1, 6);
cout << "上面:" << top;
switch (top) {
case 1:cout << "下面为:" << 6;
Dynamicnum(value16);
Show(value16);
break;
case 2: cout << "下面为:" << 5;
Dynamicnum(value25);
Show(value25);
break;
case 3:cout << "下面为:" << 4;
Dynamicnum(value34);
Show(value34);
break;
case 4:cout << "下面为:" << 3;
reverse(value34.begin(), value34.end());
Dynamicnum(value34);
Show(value34);
break;
case 5:cout << "下面为:" << 2;
reverse(value25.begin(), value25.end());
Dynamicnum(value25);
Show(value25);
break;
case 6:cout << "下面为:" << 1;
reverse(value16.begin(), value16.end());
Dynamicnum(value16);
Show(value16);
//default:
}
return;
}
void Dice::Dynamicnum(vector <int>& a)
{
for (int i = 0; i < rand.Integer(1, 5); ++i) {
int temp = *(a.begin() + 3);
a.erase(a.begin() + 3);
a.insert(a.begin(), temp);
}
}
void Dice::Show(vector<int>& a) {
cout << endl;
cout<< "前面 右侧 后侧 左侧 "<<endl;
for (vector<int>::iterator it = a.begin(); it != a.end(); it++)
cout << *it << " ";
}
当然也有其他写法,比如分别绕XYZ轴转动,转动次数随机。