我正在python中创建战舰游戏,玩家可以在一台10x10板上随机放置船只的计算机上玩游戏。 船只的安置工作正常,但船只偶尔会重叠。 无论我做什么,它都不会停止与船只重叠。
这是代码: EDITED
ships = {'A': 5, 'B': 4, 'C': 3, 'S': 3, 'D': 2}
comp_board = []
for i in range(10):
comp_board.append([])
for j in range(10):
comp_board[i].append('.')
def print_computer_board(comp_board):
for i in comp_board:
print(' '.join(i))
def comp_place_ships(comp_board, ships):
for key, value in ships.items():
ship_not_placed = True
while ship_not_placed:
ori = random.randint(0,1)
if ori == 0:
x = random.randint(0,9-value)
y = random.randint(0,9)
placement = comp_board[x][y]
if placement == '.':
for ship in range(value):
comp_board[x][y] = key
comp_board[x+ship][y] = key
ship_not_placed = False
elif ori == 1:
x = random.randint(0,9)
y = random.randint(0,9-value)
placement = comp_board[x][y]
if placement == '.':
for ship in range(value):
comp_board[x][y] = key
comp_board[x][y+ship] = key
ship_not_placed = False
elif ori != 0 or 1 and placement != '.':
print('Invalid choice, please try again.')
comp_place_ships(comp_board, ships)
print_computer_board(comp_board)
我尝试使用placement = comp_board [x + ship] [y]和placement_hort = comp_board [x] [y + ship]而不是placement = comp_board [x] [y]来检查展示位置是否有效,但是我收到一个错误:本地变量" ship"在转让前引用。
有人知道如何解决这个问题吗?我已经尝试了很长一段时间创建这个游戏,无论我做什么,我都会遇到一个又一个问题。
答案 0 :(得分:0)
正如JeffUK所提到的,您似乎正在检查新船的末端是否与现有船相交,但没有检查中间部分是否相交。
因此,您需要编写两个循环:一个用于检查交叉点,另一个用于在网格上写出新的正方形。
any_intersections = False
if ori == 0:
x = random.randint(0,9-value)
y = random.randint(0,9)
for z in range(y, y+value):
if comp_board[x][z] != '.': any_intersections = True
if not any_intersections:
for ship in range(value):
comp_board[x][y] = key
comp_board[x+ship][y] = key
.... (ori = 1 is similar. I'll leave it as an exercise.)
if not any_intersections: print("Random allocation failed.")
return any_intersections
具有放置船只的功能似乎也更加灵活,例如
def place_ship(comp_board, ship_size):
ori = random.randint(0,1)
if ori == 0:
x = random.randint(0,9-value)
y = random.randint(0,9) #note: we could set a constant board_size = 10 and then range from 0 to board_size - 1 and board_size - 1 - value
for z in range(y, y+value):
if comp_board[x][z] != '.': return False
for z in range(y, y+value): comp_board[x][z] = key
return True
然后,可以按以下方式运行更通用的place_ships函数。我添加了一些错误检查,这是您不需要的,但是如果您想调整电路板的尺寸,也许会很有趣:
def place_ships(ship_list):
for ship in ship_list:
count = 0
while not place_ship(comp_board, ship.size()):
count += 1
if count = 100:
print("Bailing. Failed 100 times to place ship.")
exit()