[英](Python) Distributing numbers equally
我為標題道歉。 如果有人能想到更具描述性的標題,請告訴我,我會重新發布這個問題,或者編輯標題。 (如果可能的話)您好,我目前正在開發一款游戲。 當發起攻擊時,攻擊者可以從其他玩家獲得潛在的資源編號。 如果防御者有資源給我,我很難弄清楚如何為攻擊者平均分配這些資源。
#this is how many resources the attacker can get, def's resources
attacker_potential = 250
#this is how many resources the defender has
defender.wood = 100
defender.iron = 25
defender.wheat = 76
defender.gold = 50000
#then the attacker would make off with
attacker.wood += 75
attacker.iron += 25
attacker.wheat += 75
attacker.gold += 75
另一個例子:
defender.wood = 2500
defender.iron = 2500
defender.wheat = 5000
defender.gold = 5000
#here, the attacker would make off with 62 for each resource. (250 / 4 = 62.5)
這是另一個例子:
defender.wood = 100
defender.iron = 0
defender.wheat = 1
defender.gold = 0
#attacker would make off with:
attacker.wood += 100
attacker.iron += 0
attacker.wheat += 1
attacker.gold += 0
然后是最后一個例子:
defender.wood = 50000 #pretend the rest are 0
attacker.wood += 250
(我知道攻擊者獲得了多少資源,其余的數學很容易)。 我剛剛在我的代碼中達到了這一點,我花了大約20分鍾試圖弄清楚它是如何工作的。 不過,我覺得答案很簡單。
與您提供的示例一致的一種算法如下:
讓平均戰利品成為攻擊者的潛力除以防御者非零資源的數量。 循環通過防御者的非零資源,如果其中任何一個小於或等於平均戰利品,將其從防御者中移除並將其交給攻擊者。
如果在步驟1中遇到並移動了小於或等於平均戰利品的資源,則重新計算平均戰利品並重復步驟1.否則,繼續執行步驟3。
最后,如果防御者剩下任何資源,只需重新計算平均戰利品並將其從每個資源中移除(將其交給攻擊者)。
python中可能的實現如下:
def step1(dres, aloot, potential):
again = False
ndres = {}
if len(dres) > 0:
avgloot = int(potential / len(dres))
for r in dres:
if dres[r] <= avgloot:
potential -= dres[r]
aloot[r] += dres[r]
again = True
else:
ndres[r] = dres[r]
return (ndres, aloot, potential, again)
def calculate_loot(dres, potential):
aloot = {'wood':0, 'iron':0, 'wheat':0, 'gold':0}
(dres, aloot, potential, again) = step1(dres, aloot, potential)
while again:
(dres, aloot, potential, again) = step1(dres, aloot, potential)
if len(dres) > 0:
avgloot = int(potential / len(dres))
for r in dres:
aloot[r] += avgloot
return aloot
potential = 250
for dres in [
{'wood':100, 'iron':25, 'wheat':76, 'gold':50000},
{'wood':2500, 'iron':2500, 'wheat':5000, 'gold':5000 },
{'wood':100, 'iron':0, 'wheat':1, 'gold':0 },
{'wood':0, 'iron':0, 'wheat':0, 'gold':50000}
]:
print(dres)
print(calculate_loot(dres, potential))
print(' ')
Round Robin用於整數資源。 如果您確實要分割資源,可以檢查剩余資源的總量是否小於資源數並均勻分配。
def distribute(potential, defender_resources):
attacker_resources = [0] * len(defender_resources)
while potential and any(defender_resources):
for i in range(len(defender_resources)):
if potential and defender_resources[i]:
defender_resources[i] -= 1
attacker_resources[i] += 1
potential -= 1
return attacker_resources
print distribute(250, [100,0,1,0])
print distribute(250, [100,25,76,5000])
print distribute(250, [2500,2500,2500,2500])
print distribute(250, [5000])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.