我为标题道歉。如果有人能想到更具描述性的标题,请告诉我,我会转载这个问题,或编辑标题。(如有可能) 你好,我正在做一个游戏。当发起攻击时,攻击者有一个潜在的资源编号,他可以从其他玩家那里获得。如果防守方有足够的资源,我很难弄清楚如何将这些资源平均分配给攻击者。在
#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
另一个例子:
^{pr2}$下面是另一个例子:
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中可能的实现如下:
Online Demo
相关问题 更多 >
编程相关推荐