【发布时间】:2017-08-11 20:58:45
【问题描述】:
我正在创建一个 Python 2-Player 战舰游戏,除了一些小问题外,一切都快完成了。在玩家将所有船只都放在棋盘上的阶段——我在验证检查重复船只时遇到了麻烦。这是我的船舶放置循环代码:
while True:
for ship_name, ship_size in Game.SHIP_INFO:
# create ship instance
ship1 = Ship(player1, ship_name, ship_size)
# ask user for starting coordinate for ship in form "A1" and split into x,y variables
x, y = ship1.split_coordinates(ship_name,player1.player)
# ask user for ship's position --horizontal or vertical
direction = ship1.ask_ship_location()
# create all coordinates for ship based on size of ship and location
created_coords = ship1.create_ship_coordinates(x, y, ship_size,direction)
# check to see if ship already on board
for coord in created_coords:
if any(coord in ship for ship in grid1.play_one_board):
print("Sorry you already have a ship in that location")
continue
else:
break
# add coordinates to player's grid
grid1.play_one_board.append(created_coords)
# loop through coords for ship to print out on displayed grid
grid1.print_ship_coordinates(created_coords,direction)
这是我刚刚尝试实现的验证部分,它导致了问题。
for coord in created_coords:
if any(coord in ship for ship in grid1.play_one_board):
print("Sorry you already have a ship in that location")
continue
else:
break
它可以正确识别是否已经放置了现有坐标——但它会继续循环中接下来的两个步骤,打印板,然后继续下一个船舶放置,而不需要再次要求更正的版本重叠的船舶布置。如果船舶重叠出现错误,只需找出循环返回起点的最佳方式。有任何想法吗?谢谢。
EDIT --根据建议将代码更改为此,但未收到任何验证错误。
while True:
for ship_name, ship_size in Game.SHIP_INFO:
# create ship instance
ship1 = Ship(player1, ship_name, ship_size)
ship_exists = True
while ship_exists:
# ask user for starting coordinate for ship in form "A1" and split into x,y variables
x, y = ship1.split_coordinates(ship_name,player1.player)
# ask user for ship's position --horizontal or vertical
direction = ship1.ask_ship_location()
# create all coordinates for ship based on size of ship and location
created_coords = ship1.create_ship_coordinates(x, y, ship_size,direction)
# check to see if ship already on board
for coord in created_coords:
ship_exists = any(coord in ship for ship in grid1.play_board)
if ship_exists:
print("sorry")
else:
break
# function to check for overlapped ships
# ship1.check_overlap(created_coords, grid1.play_one_board)
# add coordinates to player's grid
grid1.play_one_board.append(created_coords)
# loop through coords for ship to print out on displayed grid
grid1.print_ship_coordinates(created_coords, direction)
【问题讨论】:
标签: python