I'm new to c++ and I'm having a play around with arrays and I'm trying to figure something out.
For this little game I'm trying to have it so that a random element of the array is selected and put into he variable 'Gold'. I'm scratching my head trying to figure out how to get it work.
// ChestTest1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "math.h"
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
usingnamespace std;
// Variables
int Gold=0;
int Chest[5]={10, 20, 30, 40, 50};
// Function
void LootChest()
{
// Generates random number between 0-4 to give player when chest looted
srand( (unsigned)time(0) );
int ChestRoll=0;
ChestRoll=rand() % 5;
}
int main()
{
cout<<"The chest gave you "<<Gold<<" gold."<<endl;
return 0;
}
I'm not quite sure how to get the output of 'ChestRoll' to take that number element of 'Chest[]' and put it into the int called 'Gold'.
Make use of return keyword, and return looted gold from LootChest function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int Chest[5]={10, 20, 30, 40, 50};
int LootChest()
{
int ChestRoll=rand() % 5;
return Chest[ChestRoll];
}
int main()
{
srand( (unsigned)time(0) ); // only needed once per program life
cout<<"The chest gave you "<< LootChest() <<" gold."<<endl;
return 0;
}
Then you can think of going one step further - making function int LootChest(int* Chest) that you can use with different chests, containg different treasures:
1 2 3 4 5 6 7
int CommonChest [] = {1, 5, 10, 20};
int NoblemanChest [] = {10, 50, 100, 200};
int EpicChest[] = {100, 500, 1000, 2000};
cout<<"The CommonChest gave you " << LootChest(CommonChest) <<" gold."<<endl;
cout<<"The NoblemanChest gave you "<< LootChest(NoblemanChest) <<" gold."<<endl;
cout<<"The EpicChestgave you " << LootChest(EpicChest) <<" gold."<<endl;