而Loop和gen rand()

时间:2013-02-27 21:04:58

标签: c++ loops random while-loop

所以我基本上创造了一个二十一点的游戏,即时通讯卡在我必须询问用户是否需要另一张卡(拿一个HIT)的地方,我决定做一个循环。我想弄清楚的一个问题是我怎么能这样做,所以为第一个HIT选择的随机数,不能再次被选中,因为我将该变量分配给" card3&# 34;

while (hit == 'yes' || hit == 'Yes' || hit =='Y' || hit == 'y')
{
//create new card, add onto total, ask again
card3 = rand() % 51 + 1;
while (card3 == card1 || deal1 == card2 || card3 == deal1){
  card3 = rand() % 52 + 1;
}
if (card3 == 1 || card3 == 2 || card3 == 3 || card3 == 4){
cout <<"|A|";
total = total + 11;}
else if (card3 == 5 || card3 == 6 || card3 == 7 || card3 == 8){
cout <<"|2|";
total = total + 2;}
else if (card3 == 9 || card3 == 10 || card3 == 11 || card3 == 12){
cout <<"|3|";
total = total + 3;}
else if (card3 == 13 || card3 == 14 || card3 == 15 || card3 == 16){
cout <<"|4|";
total = total + 4;}
else if (card3 == 17 || card3 == 18 || card3 == 19 || card3 == 20){
cout <<"|5|";
total = total + 5;}
else if (card3 == 21 || card3 == 22 || card3 == 23 || card3 == 24){
cout <<"|6|";
total = total + 6;}
else if (card3 == 25 || card3 == 26 || card3 == 27 || card3 == 28){
cout <<"|7|";
total = total + 7;}
else if (card3 == 29 || card3 == 30 || card3 == 31 || card3 == 32){
cout <<"|8|";
total = total + 8;}
else if (card3 == 33 || card3 == 34 || card3 == 35 || card3 == 36){
cout <<"|9|";
total = total + 9;}
else if (card3 == 37 || card3 == 38 || card3 == 39 || card3 == 40){
cout <<"|10|";
total = total + 10;}
else if (card3 == 41 || card3 == 42 || card3 == 43 || card3 == 44){
cout <<"|J|";
total = total + 10;}
else if (card3 == 45 || card3 == 46 || card3 == 47 || card3 == 48){
cout <<"|Q|";
total = total + 10;}
else if (card3 == 49 || card3== 50 || card3 == 51 || card3 == 52){
cout <<"|K|";
total = total + 10;}
cout << endl;
cout <<"Your total is: " << total << endl;
cout <<"Would you like another card? yes or no: " << endl;
cin >> hit; 
cout << endl;
}

2 个答案:

答案 0 :(得分:2)

您可以将所有卡片放入容器中,然后使用std::random_shuffle将它们随机播放。然后从容器背面一次弹出一张卡片。当甲板完成后,重新开始。

答案 1 :(得分:0)

看起来像是应该使用数组的练习。我不能为你编写程序,而是阅读数组 - 它们是解决方案的重要组成部分。您可以创建一个包含52个布尔变量的数组,以指示已选择哪些卡。您应该设计一种算法来检查是否已经挑选了一张卡,当我们获得随机选择的卡时,请继续挑选一张新卡。