массивы — игра в кости c ++ имитирует бросание двух кубиков

Я новичок в C ++, мне нужно создать игру в кости, имитирующую бросание двух кубиков. Я довольно запутался с использованием файла заголовка. Но, прежде всего, зачем мне возвращать номер кости? Во-вторых, что делает функция int roll? Сбросить значения и грани? Если так, каково значение по умолчанию? И последняя функция Dice (int n), могу ли я использовать эту функцию для управления максимальной суммой значений костей? Функция должна иметь заголовочный файл класса с этими функциями:

class Dice{

private:
int face;    // no. of faces of the dice
int value;    // the face-value that shows up

public:
int getFace()// returns the no. of face of the dice
{
};

int getVal()
{
int dice1;
int dice2;
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
};    // returns the face value that shows up

int roll();     // simulate the roll pf the dice, the  value field is set  and  returned.
Dice();   // default constructor , a standard six-face dice is created with value = 1
Dice(int size);  // create a dice of given size

};

1

Решение

Надеюсь, это ответит на ваши вопросы по порядку:

Единственная причина, по которой я могу видеть количество граней каждого кубика, заключается в том, чтобы сообщить пользователю, какой кубик в данный момент катится. Я показал пример этого в своем коде ниже, где у меня есть dOne.getFaces () и dTwo.getFaces ().

Функция int roll () и getVal () должны были быть такими же, как я предполагаю. Я пошел дальше и удалил getVal () и просто использовал roll () вместо этого.

Dice () и Dice (int size) просто инициализируют количество граней для каждой кости. Кости по умолчанию будут иметь 6 граней, но пользователь может бросить кости с более чем 6, следовательно, размер int.

#include <iostream>
#include <cstdlib>
#include <time.h>

class Dice
{
private:
int faces; // no. of faces of the dice
int value; // the face-value that shows up
public:
int getFaces() {return faces;} // returns the no. of faces of the dice
int roll() // returns the face value that shows up
{
value = rand() % faces + 1;
return value;
}
Dice() : faces(6) {}; // default constructor, create a dice of standard size
Dice(int size) : faces(size) {}; // create a dice of given size
};

int main()
{
srand( time(NULL) ); // Initialize random seed
char yesNo;

std::cout << "\nWould you like to roll two normal dice? (y/n)\n";
std::cin >> yesNo;

if ( yesNo == 'y' )
{
Dice dOne, dTwo;

std::cout << "\nA dice with " << dOne.getFaces() << " faces rolled: " << dOne.roll() << '\n';
std::cout << "A dice with " << dTwo.getFaces() << " faces rolled: " << dTwo.roll() << '\n';
}
else
{
int dFaces;
std::cout << "\nHow many faces would you like each dice to have?\n\n";

std::cout << "Dice 1: ";
std::cin >> dFaces;
Dice dOne(dFaces);

std::cout << "Dice 2: ";
std::cin >> dFaces;
Dice dTwo(dFaces);

std::cout << "\nA dice with " << dOne.getFaces() << " faces rolled: " << dOne.roll() << '\n';
std::cout << "A dice with " << dTwo.getFaces() << " faces rolled: " << dTwo.roll() << '\n';
}

return 0;
}
2

Другие решения

Вам нужно определить конструктор. Что делает конструктор — это устанавливает состояние класса, поэтому в этом случае он устанавливает информацию о кости.

Если вы хотите поместить их прямо в заголовок, тогда формат для конструктора выглядит так:

//file: dice.h
//this is default constructor, note the lack of parameters being passed in
Dice(): face(?), value(?) // here we are initializing "face" and "value", replace the question marks with the correct values as per your specification
{
}

Если вы делаете это в файле cpp, он немного отличается, но логика должна оставаться прежней.

//file: dice.h
Dice(); //This is only a declaration

//file: dice.cpp
#include "dice.h"Dice::Dice(): face(?), value(?) //This is where we define the constructor. note the Dice:: part here, we need to tell the compiler where to look
{
}

В остальном это очень похоже. Если вы боретесь, я бы посоветовал вам изучить некоторые ресурсы C ++ дальше. Я бы посмотрел конструкторы / деструкторы, а также списки инициализации.

0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector