2015-05-26 5 views
0

Я пишу игру yahtzee для моего класса программирования C++. Одна из моих трудностей, с которыми я столкнулся, - это система подсчета очков для разных категорий. Я думаю, что я выяснил, как это сделать для добавления 1s, 2s и т. Д., Но я не знаю, как определить программу, когда были свернуты 3 вида, 4 вида и т. Д. Вот мой код до сих пор.Как оценивать yahtzee в C++

#include "stdafx.h" 
#include <iostream> 
#include <cstdlib> 
#include <ctime> 
#include <string> 
#include <vector> 
using namespace std; 


int _tmain(int argc, _TCHAR* argv[]) 
{ 
    //Declare variables 
    int players; 
    int turn = 1; 
    vector<string> names; 
    string playerName; 
    int dice[5]; 
    int finalScore = 0; 
    char reroll[5]; 
    char rollDice; 
    int tries = 1; 
    const int DICE = 5; 
    int roll[DICE]; 
    int scorecard; 
    int scoreThisTurn(int scorecard); 
    int turnScore = 0; 

    //Introduction, get number of players. 
    cout << "Hello, welcome to Yahtzee! How many players are there?" << endl; 
    cin >> players; 

    if (players > 4) { 
     cout << "Sorry, the maximum number of players is 4." << endl; 
     cout << "How many players are there?" << endl; 
     cin >> players; 
    } 

    //Get player names 
    string getNames(); 
    for (int i = 0; i < players; i++) { 
     cout << "Hello player " << i + 1 << ", please enter your name" << endl; 
     cin >> playerName; 
      names.push_back(playerName); 
     } 

    srand(time(NULL)); //random seed 

    cout << "Welcome to Yahtzee!\n"; 

    while (turn <= 13) {  //roll dice 
     cout << "Press 'r' to roll" << endl; 
     cin >> rollDice; 
     if (rollDice == 'r') { 
      for (int i = 0; i < DICE; i++) { 
       roll[i] = rand() % 6 + 1; 
      } 
     } 
     cout << "You rolled: " << roll[0] << ", " << roll[1] << ", " << 
      roll[2] << ", " << roll[3] << ", " << roll[4] << endl; 
     cout << "Type y to reroll or n to keep. For example yynnn would keep the first three dice" << endl; 
     cin >> reroll[0] >> reroll[1] >> reroll[2] >> reroll[3] >> reroll[4]; 

     for (int i = 0; i < DICE; i++) { 
      if (reroll[i] == 'y') { 
       roll[i] = rand() % 6 + 1; 
      } 
      else if (reroll[i] == 'n') { 
       roll[i]; 
      } 
      else cout << "Sorry you entered an invalid letter." << endl; 
     } 

     cout << "Your second roll is: " << roll[0] << ", " << roll[1] << ", " << 
      roll[2] << ", " << roll[3] << ", " << roll[4] << endl; 

     cout << "Type y to reroll or n to keep. For example yynnn would keep the first three dice" << endl; 
     cin >> reroll[0] >> reroll[1] >> reroll[2] >> reroll[3] >> reroll[4]; 

     for (int i = 0; i < DICE; i++) { 
      if (reroll[i] == 'y') { 
       roll[i] = rand() % 6 + 1; 
      } 
      else if (reroll[i] == 'n') { 
       roll[i]; 
      } 
      else cout << "Sorry you entered an invalid letter." << endl; 
     } 

     cout << "Your third roll is: " << roll[0] << ", " << roll[1] << ", " << 
      roll[2] << ", " << roll[3] << ", " << roll[4] << endl; 

     //displays scorecard categories 
     cout << "Which category would you like to score this in" << endl; 
     cout << "1 - ones: " << endl; 
     cout << "2 - twos: " << endl; 
     cout << "3 - threes: " << endl; 
     cout << "4 - fours: " << endl; 
     cout << "5 - fives: " << endl; 
     cout << "6 - sixes: " << endl; 
     cout << "7 - 3 of a kind: " << endl; 
     cout << "8 - 4 of a kind: " << endl; 
     cout << "9 - small straight: " << endl; 
     cout << "10 - large straight: " << endl; 
     cout << "11 - full house: " << endl; 
     cout << "12 - yahtzee: " << endl; 
     cout << "13 - chance: " << endl; 

     //asks player to choose where to score 
     cout << "\nEnter 1-14 to choose a category." << endl; 
     cin >> scorecard; 

     //assigns points 
     for (int i = 0; i < DICE; i++) { 
      turnScore = 0; 
      if (scorecard == 1) { 
       if (roll[i] == 1) { 
        turnScore = turnScore + 1; 
       } 
      } 
      if (scorecard == 2) { 
       if (roll[i] == 2) { 
        turnScore = turnScore + 2; 
       } 
      } 
      if (scorecard == 3) { 
       if (roll[i] == 3) { 
        turnScore = turnScore + 3; 
       } 
      } 
      if (scorecard == 4) { 
       if (roll[i] == 4) { 
        turnScore = turnScore + 4; 
       } 
      } 
      if (scorecard == 5) { 
       if (roll[i] == 5) { 
        turnScore = turnScore + 5; 
       } 
      } 
      if (scorecard == 6) { 
       if (roll[i] == 6) { 
        turnScore = turnScore + 6; 
       } 
       if (scorecard == 7) { 
        if (roll[i] == 2) { 
         turnScore = turnScore + 2; 
        } 
       } 

     } 

     cout << scorecard << endl; 

     turn++; 
    } 


    system("pause"); 
    return 0; 
} 

Как вы можете видеть, что я создал счет в течение первых 6 категорий, но не знаю, как поступить.

+0

Какие конкретные проблемы вы с? – Qix

+0

Проблемы @qix 2 в настоящее время. Когда я пытаюсь забить 1, например, кости, прочитанные 11211, оценка должна = 4, однако выход равен 1. Я с тех пор перевел инициализацию turnScore в 0 за пределами начального цикла подсчета очков, но проблема остается. Вторая проблема заключается в том, что я не знаю, как сделать подсчет 3-го вида, 4 вида и т. Д. Как я могу заставить программу распознавать один из этих типов рулонов и оценивать его соответственно? –

ответ

0

Я не знаю, как определить программу, когда было свернуто 3 вида, 4 вида и т. Д.

  1. Создайте переменную, чтобы помочь вам следить за количеством кубиков, имеющих заданное число.

    int diceCount[DICE] = {0}; 
    

    и заполнить массив:

    for (int i = 0; i < DICE; i++) { 
        diceCount[roll[i-1]]++ 
    } 
    
  2. Создать вспомогательные функции, чтобы определить, были ли брошены пять, четыре или три из вида.

    int getNOfAKind(int diceCount[], int N) 
    { 
        // This will need moving DICE out of `main` 
        // making it a global variable. 
        for (int i = 0; i < DICE; ++i) 
        { 
         if (diceCount[i] == N) 
         { 
         return i+1; 
         } 
        } 
        return -1; 
    } 
    
    int getFiveOfAKind(int diceCount[]) 
    { 
        return getNOfAKind(diceCount, 5); 
    } 
    
    int getFourOfAKind(int diceCount[]) 
    { 
        return getNOfAKind(diceCount, 4); 
    } 
    
    int getThreeOfAKind(int diceCount[]) 
    { 
        return getNOfAKind(diceCount, 3); 
    } 
    

    и использовать его как:

    int fiveCount = getFiveOfAKind(diceCount); 
    if (fiveCount != -1) 
    { 
    } 
    
    int fourCount = getFourOfAKind(diceCount); 
    if (fourCount != -1) 
    { 
    } 
    
    int threeCount = getThreeOfAKind(diceCount); 
    if (threeCount != -1) 
    { 
    } 
    
+0

@R Sahu Спасибо за ваш ответ. Я попробую это. Если посмотреть на мой код, знаете ли вы, почему при подсчете 1, 2 и т. Д. Результат неверен? Например, если кубик читается 22111, выход для 2s должен быть 4, но он выводится как 2. Я переместил оператор, инициализирующий turnScore, на 0 вне начального цикла, но проблема сохраняется. –

+0

@RyanA, вам нужно переместить строку 'turnScore = 0;' вне цикла 'for'. В противном случае он инициализируется на '0' на каждой итерации цикла. –