簡體   English   中英

c ++程序取卡號

[英]c++ progam to take card number

我正在用 C++ 開發以下游戲:

用戶輸入一個數字 (n),程序隨機抽取一組在全局數組 main 頂部聲明的卡片。 然后它每次輸出隨機數量的 (n) 張卡片。

問題是數字,例如“3 Hearts”,出現了不止一次。 我做了一個函數來糾正這個問題,但是它沒有解決問題。

有人可以看看下面的代碼並幫助我找到可能導致問題的原因嗎?

#include <iostream>
#include <time.h>
#include <string>
using namespace std;

string type[4] = {"Hearts" , "Diamonds" , "Spades" , "Clubs"};
string num[13] = {"1","2","3","4","5","6","7","8","9","10","J","Q","K"};

int random(int x){
    return rand()%x;
}

bool isDrawn(int);
void DrawCard();
int card_remaining = 52;
bool card_is_drawn[52] = {false};

int main(){

    while(1){
    cout<<"\n Enter A Card Number  :   ";
    int n;
    cin>>n;
        if(card_remaining <= 0){
            card_remaining = 52;
            cout<<" No More Cards  ,  Refreshing ...\n";
            cout<<"  Refresh Done ! Try Again if you Want \n";
            for(int i=0;i<52;i++)
                card_is_drawn[i] = false;
        }
        else{
                for(int i=0;i<n;i++){
                DrawCard();
                }
        }
            
    }

    cout<<endl;
    system("PAUSE");
    return 0;
}
void DrawCard(){
    bool check_1 = false;
    int card;
    while(!check_1){
        card = random(card_remaining);
        if(!isDrawn(card))
        check_1 = true;
    }
    if(check_1)
        cout << num[card%13]<<"   OF   " << type[card/13] << endl ;

    card_remaining--;
}
bool isDrawn(int x){
    if(card_is_drawn[x] == false){
        card_is_drawn[x] = true;
        return true;
    }
    return false;
}

檢查功能

bool isDrawn(int x){
    if(card_is_drawn[x] == false){
        card_is_drawn[x] = true;
        return true;
    }
    return false;
}

您可能希望交換兩個返回值。 這意味着:

if(card_is_drawn[x] == false) {
    ...
    return false;    //since the card was NOT drawn;

在函數的最后:

return true;    //since the if-clause evaluated as false what means that the card was drawn;

順便一提:

您可以通過 rand()%cards_remaining 獲得隨機卡片。 這意味着如果你抽取任何一張牌,因此將cards_remaining 減少1,你將無法再抽取俱樂部之王。 像這樣繼續下去,你會從你牌組的“末端”丟掉牌。

應該:

void DrawCard(){
    if (card_remaining <= 0)    // no cards left? can't draw
        return;

    bool check_1 = false;
    int card;
    while(!check_1){
        card = random(52);  // here 52
        if (isDrawn(card))  // here, if the card HAS been drawn
            check_1 = true;
    }
    if(check_1)
        cout << num[card%13]<<"   OF   " << type[card/13] << endl ;

    card_remaining--;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM