我想让敌人不在相同的坐标上。 我不想要任何其他建议,比如让我的代码更干净的建议。 这是代码的一部分:
class enemy(object):
def __init__(self,x,y):
self.x=x
self.y=y
def move(self):
if self.x*tilesize>x:
self.x-=1
if self.x < 0:
self.x += 1
elif mappi[self.y][self.x] == stone or mappi[self.y][self.x] == wood:
self.x += 1
if self.y*tilesize<y:
self.y+=1
if self.y > mapheight-1:
self.y -= 1
elif mappi[self.y][self.x] == stone or mappi[self.y][self.x] == wood:
self.y -= 1
if self.x*tilesize<x:
self.x+=1
if self.x > mapwidth-1:
self.x -= 1
elif mappi[self.y][self.x] == stone or mappi[self.y][self.x] == wood:
self.x -= 1
if self.y*tilesize>y:
self.y-=1
if self.y < 0:
self.y += 1
elif mappi[self.y][self.x] == stone or mappi[self.y][self.x] == wood:
self.y += 1
enemies=[enemy(random.randint(0,mapwidth-1),random.randint(0,mapheight-1)),
enemy(random.randint(0,mapwidth-1),random.randint(0,mapheight-1)),
enemy(random.randint(0,mapwidth-1),random.randint(0,mapheight-1)),
enemy(random.randint(0,mapwidth-1),random.randint(0,mapheight-1)),
enemy(random.randint(0,mapwidth-1),random.randint(0,mapheight-1)),
enemy(random.randint(0,mapwidth-1),random.randint(0,mapheight-1)),
enemy(random.randint(0,mapwidth-1),random.randint(0,mapheight-1)),
enemy(random.randint(0,mapwidth-1),random.randint(0,mapheight-1)),
enemy(random.randint(0,mapwidth-1),random.randint(0,mapheight-1)),
enemy(random.randint(0,mapwidth-1),random.randint(0,mapheight-1)),]
答案 0 :(得分:0)
如果提前你做了
from itertools import product
然后您可以使用
将该十行分配替换为enemies
mapxy = list(product(range(mapwidth),range(mapheight)))
enemies = [enemy(*xy) for xy in random.sample(mapxy, 10)]
这使用random.sample
,从群体中选择给定数量的元素(此处为10),不重复。
我们选择的人口是地图位置,此处由range(mapwidth)
和range(mapheight)
的笛卡尔积描述。遗憾的是,random.sample
不适用于product
的结果等迭代,因此我们必须将其读入列表。
10个选定的元素是元组(x,y)。我们将每个元组xy
解包为两个参数,以构建一个enemy
,其中包含enemy(*xy)
中的星号。