From 5607c58daa90e9834ee833e4bf2ff0493349fc8a Mon Sep 17 00:00:00 2001 From: Juliano Leal Goncalves Date: Mon, 6 Sep 2021 22:22:05 -0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=8F=B7=EF=B8=8F=20Add=20'PickRandomlyAmon?= =?UTF-8?q?g'=20function=20that=20picks=20one=20value=20from=20a=20set=20o?= =?UTF-8?q?f=20values=20randomly?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- Source/engine/random.hpp | 16 ++++++++++++++++ Source/objects.cpp | 17 +---------------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/Source/engine/random.hpp b/Source/engine/random.hpp index 95e683448..59ae02e98 100644 --- a/Source/engine/random.hpp +++ b/Source/engine/random.hpp @@ -7,7 +7,9 @@ */ #pragma once +#include #include +#include namespace devilution { @@ -57,4 +59,18 @@ int32_t AdvanceRndSeed(); */ 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 +const T PickRandomlyAmong(const std::initializer_list &values) +{ + const auto index { std::max(GenerateRnd(values.size()), 0) }; + + return *(values.begin() + index); +} + } // namespace devilution diff --git a/Source/objects.cpp b/Source/objects.cpp index 73e462ca6..6a9eea0ae 100644 --- a/Source/objects.cpp +++ b/Source/objects.cpp @@ -3966,26 +3966,11 @@ bool OperateFountains(int pnum, int i) void OperateWeaponRack(int pnum, int i, bool sendmsg) { - ItemType weaponType { ItemType::ITYPE_NONE }; - if (Objects[i]._oSelFlag == 0) return; SetRndSeed(Objects[i]._oRndSeed); - switch (GenerateRnd(4) + ITYPE_SWORD) { - 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; - } + ItemType weaponType { PickRandomlyAmong({ ITYPE_SWORD, ITYPE_AXE, ITYPE_BOW, ITYPE_MACE }) }; Objects[i]._oSelFlag = 0; Objects[i]._oAnimFrame++;