给定一个结构列表,有没有办法可以根据预定的指标(比如游戏难度)改变概率属性?该概率属性是随机选择房间的概率。
我当前的概率属性已设置,是一个不断更新的噩梦。既然我想引入一个可以调整这些值的外部设置,我需要完全重新设计这个概率的设置方式。请参阅下面的当前设置:
defmodule Sandbox do
defstruct description: nil, chance: nil
def all, do: [
%Sandbox{
description: "Description 1",
chance: 1..40
},
%Sandbox{
description: "Description 2",
chance: 41..60
},
%Sandbox{
description: "Description 3",
chance: 61..100
},
]
def random do
rand = Enum.random(1..100)
Enum.find(all(), fn %{chance: chance} -> rand in chance end)
end
end
问题
答案 0 :(得分:2)
我会在每个结构中存储每个难度的概率,然后让random
接受难度级别:
defmodule Sandbox do
defstruct description: nil, easy: nil, medium: nil, hard: nil
def all, do: [
%Sandbox{
description: "Description 1",
easy: 1..40,
medium: 1..50,
hard: 1..60,
},
%Sandbox{
description: "Description 2",
easy: 41..60,
medium: 51..80,
hard: 61..90,
},
%Sandbox{
description: "Description 3",
easy: 61..100,
medium: 81..100,
hard: 91..100,
},
]
def random(difficulty) do
rand = Enum.random(1..100)
Enum.find(all(), fn s -> rand in Map.get(s, difficulty) end)
end
end
IO.inspect Sandbox.random(:easy)
IO.inspect Sandbox.random(:medium)
IO.inspect Sandbox.random(:hard)
答案 1 :(得分:0)
我会根据难度选择百分比机会来选择房间:
defmodule Sandbox do
defstruct description: nil, chance: nil
def all, do: [
%Sandbox{
description: "Description 1",
chance: %{easy: 75, medium: 40, hard: 10}
},
%Sandbox{
description: "Description 2",
chance: %{easy: 100, medium: 100, hard: 100}
},
%Sandbox{
description: "Description 3",
chance: %{easy: 100, medium: 50, hard: 10}
},
]
def random_by_difficulty(rooms, difficulty) do
mark = Enum.random(1..100)
rooms
|> Enum.filter(fn room -> room.chance[difficulty] >= mark end)
|> Enum.random()
end
end