Browse Source

🏷️ Add 'PickRandomlyAmong' function that picks one value from a set of values randomly

This will be used in a few places where we previously used a raw integer random to index into a local array for selection, simplifying that type of logic to a single statement.
pull/2862/head
Juliano Leal Goncalves 5 years ago committed by Anders Jenbo
parent
commit
5607c58daa
  1. 16
      Source/engine/random.hpp
  2. 17
      Source/objects.cpp

16
Source/engine/random.hpp

@ -7,7 +7,9 @@
*/ */
#pragma once #pragma once
#include <algorithm>
#include <cstdint> #include <cstdint>
#include <initializer_list>
namespace devilution { namespace devilution {
@ -57,4 +59,18 @@ int32_t AdvanceRndSeed();
*/ */
int32_t GenerateRnd(int32_t v); int32_t GenerateRnd(int32_t v);
/**
* @brief Picks one of the elements in the list randomly.
*
* @param values The values to pick from
* @return A random value from the 'values' list.
*/
template <typename T>
const T PickRandomlyAmong(const std::initializer_list<T> &values)
{
const auto index { std::max<int32_t>(GenerateRnd(values.size()), 0) };
return *(values.begin() + index);
}
} // namespace devilution } // namespace devilution

17
Source/objects.cpp

@ -3966,26 +3966,11 @@ bool OperateFountains(int pnum, int i)
void OperateWeaponRack(int pnum, int i, bool sendmsg) void OperateWeaponRack(int pnum, int i, bool sendmsg)
{ {
ItemType weaponType { ItemType::ITYPE_NONE };
if (Objects[i]._oSelFlag == 0) if (Objects[i]._oSelFlag == 0)
return; return;
SetRndSeed(Objects[i]._oRndSeed); SetRndSeed(Objects[i]._oRndSeed);
switch (GenerateRnd(4) + ITYPE_SWORD) { ItemType weaponType { PickRandomlyAmong({ ITYPE_SWORD, ITYPE_AXE, ITYPE_BOW, ITYPE_MACE }) };
case ITYPE_SWORD:
weaponType = ITYPE_SWORD;
break;
case ITYPE_AXE:
weaponType = ITYPE_AXE;
break;
case ITYPE_BOW:
weaponType = ITYPE_BOW;
break;
case ITYPE_MACE:
weaponType = ITYPE_MACE;
break;
}
Objects[i]._oSelFlag = 0; Objects[i]._oSelFlag = 0;
Objects[i]._oAnimFrame++; Objects[i]._oAnimFrame++;

Loading…
Cancel
Save