gpt4 book ai didi

python - 战舰: How to automate instances creation?

转载 作者:行者123 更新时间:2023-11-30 22:10:11 26 4
gpt4 key购买 nike

我正在制作一款战舰游戏。我创建了一个 Ship 类来为船只提供位置。

创建类后,我必须创建所有实例,我想知道是否有一种方法可以自动化它。

大部分程序都是无关紧要的,但我将其保留,以防万一它可能会影响它是否可以自动化。

import random

class Ship(object):

def __init__(self, length):
self.length = length

def direction(self):
vh = random.choice(['v','h'])
return vh

def location(self):
space = []
row = random.randint(0, 10-self.length)
column = random.randint(0, 10-self.length)
if self.direction == 'v':
for x in range(self.length):
space.append(f'{column}{row+x}')
else:
for x in range(self.length):
space.append(f'{column}{row+x}')
return space

ships_amount = {
'carrier' : 1,
'battleship' : 2,
'cruiser' : 3,
'destroyer' : 4
}

ships_length = {
'carrier' : 5,
'battleship' : 4,
'cruiser' : 3,
'destroyer' : 2
}

我想这样做:

carrier1 = Ship(ships_length['carrier'])
battleship1 = Ship(ships_length['battleship'])
battleship2 = Ship(ships_length['battleship'])
cruiser1 = Ship(ships_length['cruiser'])
cruiser2 = Ship(ships_length['cruiser'])
cruiser3 = Ship(ships_length['cruiser'])
destroyer1 = Ship(ships_length['destroyer'])
destroyer2 = Ship(ships_length['destroyer'])
destroyer3 = Ship(ships_length['destroyer'])
destroyer4 = Ship(ships_length['destroyer'])

但自动化

最佳答案

您可以迭代您想要的船只并查找它们的长度来制造它们:

 ships = []
for type_of_ship in ships_amount:
ships.append(Ship(ships_length[type_of_ship]))

甚至

ships = [Ship(ships_length[k]) for k in ships_amount]

(在第二个示例中,ky 是 key 的简写,或者现在在 for 循环中称为 type_of_ship)

这将为您提供每种类型的船只之一。

这不会为您提供名为“Carrier1”等的变量,但您将能够对ships中的每个项目进行操作。

例如

for ship in ships:
print(ship.length)

要获得规定的数量或每种类型船只的数量,您需要在循环中制造额外的船只。通过迭代 items(),您将获得一个键和值,我将其称为 kv,尽管它们值得更好的名称。字典中的值告诉您有多少:

ships = []
for k, v in ships_amount.items():
ships.extend([Ship(ships_length[k]) for _ in range(v)])

这将为您提供所需的 10 艘舰船。

关于python - 战舰: How to automate instances creation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51730056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com