我正在尝试用python3创建游戏Battleship,用户在玩CPU。我在Ship Generator上遇到了一些问题,这是脚本放置自己的船只的地方。该方法接受参数“ map”(它是地图的二维数组)(该数组必须填充类似于空地图的字母“ O”)和“ numtimes”(应放置多少艘船的计数) (第一艘船的大小为2个街区,每次创建新船时增加一个)。根据字母,船上会标有字母。例如,如果制造了2艘船,则第一艘船将由字母“ A”组成,而第二艘船将由字母“ B”标记。 现在问题是: 每当我为4艘船运行10x10地图的方法时,地图只会在地图上返回一条船,其块长为1。这是我运行未完成的脚本时的结果:
O O O O O O O O O O
O O O O O O O O O O
O O O O O O O O O O
O O O O O O O O O O
O O O O O O O O O O
O O O O O O O O O O
O O O O O O O O O O
O O A O O O O O O O
O O O O O O O O O O
O O O O O O O O O O
方法是:
from random import randint
from string import ascii_uppercase
def shipmaker(map, numtimes): #only works if map is a square filled with 'O' & max numtimes is 4
asci = ascii_uppercase #alphabet
themap = len(map)-1 #array/board size
truth = False #Used for first while loop below
for i in range(numtimes):
while truth == False:
size = 2+i #size increases along with numtimes. Ship number one is two units long
direction = randint(0,1) #This depicts whether the ship will be vertical or horizontal
while True: #For the first coordinate
row = randint(0,themap-size) #row of first coordinate
col = randint(0,themap-size) #column of first coordinate
if map[row][col] == "O": #If the coordinate was "O", it hasn't been used yet. The ships cannot overlap each other
map[row][col]=asci[size-2]
break
for x in range(size-1):
if direction == 1: #vertical
if map[row+x][col]!="O": #further continues breaking the loop if coordinate was already used
break
else: #if coordinate wasn't used
row+=x
map[row][col] = asci[size-2] #Makes ship equal to letter corresponding to the alphabet
else: #horizontal; Same thing below except the column coordinates are changed since this is horizontal
if map[row][col+x]!="O":
break
else:
col+=x
map[row][col] = asci[size - 2]
if map[row][col] == asci[size-2]:
truth = True #breaks the while loop if everything was good and goes on to the next ship in the superior for loop
答案 0 :(得分:0)
您的问题出在以下三行:
truth = False
for i in range(numtimes):
while truth == False:
当您退出while循环并开始下一艘船时,您永远不会将真值重置为True
,因此对于所有其余船都将跳过while循环。而是将truth
放在for循环中,如下所示:
for i in range(numtimes):
truth = False
while truth == False: