我正在用Python创建一个战列舰游戏,但我想随机生成一个数字列表作为它们的位置。但是,我无法删除重复项,我可以使用set()但它不会给我5个我需要的结果。
#Battleships challenge
import random
place = []#empty list
for i in range(5):
place.append(random.randrange(1,50,1))
print(place)
ships =len(place)
hits = 0
misses = 0
counter = 0
while ships > 0:
hit = int(input("Which space do you want to hit?"))
if hit in place:
place.remove(hit)
print("You have a hit!")
ships = ships -1
hits = hits + 1
else:
print("No!")
misses = misses + 1
if ships == 0:
print("Well done, all ships have disappeared!")
print(hits, "successful hits")
print(misses,"misses")
答案 0 :(得分:2)
all_positions = range(100)
five_positions = random.sample(all_positions,5)
我认为会起作用